var ratings;

var b = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
jQuery.browser = {
	safari: /webkit/.test(b),
	opera: /opera/.test(b),
	msie: /msie/.test(b) && !/opera/.test(b),
	msie6: /msie 6.0/.test(b) && !/opera/.test(b),
	mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b)
};

$(document).ready(function() {
    ratings = new Ratings();
});

/**
* Main object, useful for uploader
*/
Ratings = function() {

	var self = this;

	/**
	* Initializes the ratings window (modal window)
	*/
	this.init = function() {
		$('#loginForm').submit(ratings.submitLogin);
		$('#subscriptionForm').submit(ratings.submitSubscription);
		$('#lostPasswordForm').submit(ratings.lostPassword);
	

		// jQuery plugin for counting the characters. Thanks to the author :)
		$('textarea.limited').maxlength({
			'feedback' : '.charsLeft'
		});

		// Adds listener on button "Ajouter mon avis"
		$('#addCommentButton').click(function(){
			if(self.isLogin == 1){
				$('#commentBox').removeClass('hidden');
				$('#commentBox textarea').focus();
			} else {
				$('#loginBox').removeClass('hidden');
				$('#lostPasswordForm').hide();
				$('#loginForm .errorMessage, #loginForm .statusMessage').empty().addClass('hidden');
				$('#loginForm').show();
				$('#email_login').focus();
			}
			$(this).addClass('hidden');
			$('#backButton').removeClass('hidden');
		});

		// Cancel button that collapses the login or comment pane
		$('#backButton').click(function() {
			$('#commentBox, #loginBox, #backButton').addClass('hidden');
			$('#addCommentButton').removeClass('hidden');
		});

		// Add listener on save comment
		$('#submit_comment').click(ratings.addComment);

		// Add listener on validate conditions
		$('#submit_conditions').click(ratings.acceptConditions);

		// Lost password link
		$('#lostPassword').click(function() {
			$('#loginForm').hide(500);
			$('#lostPasswordForm').show(500);
			$('#recoverPassword').removeClass('hidden');
			$('#email_recover').focus();
			return false; // prevent default action
		});

		// jQuery Stars plugin for live rating stars with tooltip
		$('.commentBoxColumn2 .star').rating({
			required: true,
			focus: function(value,link) {
				// Uncessary code which generates errors. No id #ratingTip. Delete it when no side effect is detected.
				//var tip = $('#ratingTip');
				//tip[0].data = tip[0].data || tip.html();
				//tip.html(link.title || 'value: '+value);
			},
			blur: function(value,ling) {
				//var tip = $('#ratingTip');
				//$('#ratingTip').html(tip[0].data || '');
			}
		});

    } // end init

	/**
	 *  Navigate through the comments pages
	 */
	this.page = function(navPageNum) {
		if (! $.browser.msie6) {
			$('#comments').css('opacity','0.5');
		}
		$('#comments_loading').removeClass('hidden');
		$('#TB_ajaxContent').load('/ratings/ratings/detail/azbid/'+azbid+'/page/'+navPageNum,{},function() {
			if (! $.browser.msie6) {
				$('#comments').css('opacity','1.0');
			}
			$('#comments_loading').addClass('hidden');
		});
	}

	/**
	 *  Change the comments sort order
	 */
	this.sort = function(order) {
		if (! $.browser.msie6) {
			$('#comments').css('opacity','0.5');
		}
		$('#comments_loading').removeClass('hidden');
		$('#TB_ajaxContent').load('/ratings/ratings/detail/azbid/'+azbid+'/sort/'+order,{},function() {
			if (! $.browser.msie6) {
				$('#comments').css('opacity','1.0');
			}
			$('#comments_loading').addClass('hidden');
		});
	}

	this.logout = function() {
		var request = '/ratings/members/logout';
		$('#commentBox .star_on').removeClass('star_on');
		$('textarea.limited')[0].value = '';
		$.get(request,function() {
			$('#welcomeMsg, #logout, #backButton, #commentBox, #loginBox').addClass('hidden');
			$('#addCommentButton').removeClass('hidden');
			self.isLogin = 0;
		});
	}

	this.feedback = function(type, co_index) {
		$('#lostPasswordForm').hide(); //ajout AMA pour un problème de mise en page
		
		if (self.isLogin == '1') {
			var request = '/ratings/ratings/feedback/co_index/'+co_index+'/type/'+type;
			if (! $.browser.msie6) {
				$('#feedback'+co_index).css('opacity','0.5');
			}
			$.get(request,function(data) {
				if (! $.browser.msie6) {
					$('#feedback'+co_index).css('opacity','1');
				}
				if (data.indexOf('Error')==0) {
					$('#confirmMsg').html(data.replace('Error: ','')).show();
					setTimeout("$('#confirmMsg').hide('slow');",2000);
				} else {
					var params = data.split('##+##');
					// Debug:
					//console.log(params);
					$('#feedback'+co_index+' .positiveCount').text(params[0]);
					$('#feedback'+co_index+' .negativeCount').text(params[1]);
				}
			})
		} else {
			//$('#lostPasswordForm').addClass('hidden'); //ajout AMA pour un problème de mise en page
			$('#loginBox').removeClass('hidden');
			$('#loginForm .errorMessage, #loginForm .statusMessage').empty().addClass('hidden');
			$('#lostPasswordForm').addClass('hidden'); //ajout AMA pour un problème de mise en page
			$('#email_login').focus();
			$('#addCommentButton').addClass('hidden');
			$('#backButton').removeClass('hidden');

		}
	}

	this.abuse = function(co_index) {
		var request = '/ratings/ratings/abuse';
		if (typeof(co_index) == 'number') {
			request += '/co_index/'+co_index;
			if (! $.browser.msie6) {
				$('#abuse'+co_index).css({'opacity': "0.5"});
			}
			$('#abuse'+co_index+' .wait').css({visibility: 'visible'});
			$.get(request,function(data) {
				if (! $.browser.msie6) {
					$('#abuse'+co_index).css({'opacity': "1"});
				}
				$('#abuse'+co_index+' .wait').css({visibility: 'hidden'});
				if (data.indexOf('Error')==0) {
					$('#confirmMsg').html(data.replace('Error: ','')).show();
				} else {
					var params = data.split('##+##');
					$('#confirmMsg').html(params[0]).show();
					$('#abuse'+co_index).html(params[1]);
				}
				setTimeout("$('#confirmMsg').hide('slow')",4000);
			});
		}
	}

    /**
	 * Add a new rating/comment
	 */
	this.addComment = function() {
		var request = '/ratings/ratings/add';
		request += '/azbid/' + azbid;
		if (! $.browser.msie6) {
			$('#commentBox').css({'opacity': "0.5"});
		}
		$('#commentBox_loading').removeClass('hidden');

		if ($('#competition').is(':checked'))
			$competition = 1;
		else
			$competition = 0;


		$.post(request, {
			comment: $('#commentBox textarea').val(),
			competition: $competition,
			rate: $('#commentBox .star_on').length
		} ,ratings.addCommentCallback);
	}

	this.addCommentCallback = function(data) {
		if (! $.browser.msie6) {
			$('#commentBox').css({'opacity': "1"});
		}
		$('#commentBox_loading').addClass('hidden');
		if (data.indexOf('Error') == 0) {
			$('#commentBox .errorMessage').empty().html(data.replace('Error: ','')).removeClass('hidden');
		} else {
			$('#commentBox').addClass('hidden');
			$('#commentBox .errorMessage').empty().addClass('hidden');
			$('#commentBox textarea').empty();
			$('#backButton').addClass('hidden');
			$('#addCommentButton').addClass('hidden');

			var params = data.split('##+##');

			// display a confirmation message
			$('#confirmMsg').text(params[0]).show();
			setTimeout("$('#confirmMsg').hide('slow')",3000);

			// refresh the average stars and ratings count
			$('#avgStars').css('backgroundImage', 'url(../ratings/public/images/'+params[1]+'.png)');
			$('#rateCount').html(params[2]);

			// refresh the list of comments
			$('#comments').html(params[3]);
		}
	}

    /**
	 * Submits the login information
	 */
    this.submitLogin = function() {
        var request = '/ratings/members/login';
		if (! $.browser.msie6) {
			$('#loginBoxColumn1').css({'opacity': "0.5"});
		}
        $('.loginBox_loading1').removeClass('hidden');
        $('#submit_login').addClass('hidden');
        $.post(request, {
        	email: $('#email_login').val(),
        	password: $('#password_login').val(),
        	language: currentLang
        },ratings.submitLoginCallback);
		return false; // prevent normal form submission
    }

    /**
	 * Calls back submitLogin()
	 */
	this.submitLoginCallback = function(data) {
		if (! $.browser.msie6) {
			$('#loginBoxColumn1').css({'opacity': "1"});
		}
		$('.loginBox_loading1').addClass('hidden');
		$('#submit_login').removeClass('hidden');

		if (data.indexOf('Error') == 0) {
			$('#loginForm .errorMessage').empty().html(data.replace('Error: ','')).removeClass('hidden');
		} else {
			$('#welcomeMsg').empty().html(data);
			$('#welcomeMsg').removeClass('hidden');
			$('#loginBox, #loginBox .errorMessage, #loginBox .statusMessage').addClass('hidden');
            $('#commentBox').removeClass('hidden');
            $('#logout').removeClass('hidden');
			self.isLogin = 1;
		}
    }

	/**
	 * Submits the subscription information
	 */
	this.submitSubscription = function() {
		var request = '/ratings/members/register';
		if (! $.browser.msie6) {
			$('#loginBoxColumn2').css({'opacity': "0.5"});
		}
		$('.loginBox_loading2').removeClass('hidden');
		$('#submit_subscription').addClass('hidden');
		$.post(request, {
			pseudo: $('#name_subscription').val(),
			email: $('#email_subscription').val(),
			password: $('#password_subscription').val(),
			password2: $('#password2_subscription').val(),
			language: currentLang,
			conditions: $('#condition_subscription').is(':checked')
		},ratings.submitSubscriptionCallback);
		return false; // prevent normal form submission
    }

	/**
	 * Callback submitSubscription()
	 */
	this.submitSubscriptionCallback = function(data) {
		if (! $.browser.msie6) {
			$('#loginBoxColumn2').css({'opacity': "1"});
		}
		$('.loginBox_loading2').addClass('hidden');
		$('#submit_subscription').removeClass('hidden');
		if (data.indexOf('Error') == 0) {
			$('#loginBoxColumn2 .errorMessage').empty().html(data.replace('Error: ','')).removeClass('hidden');
		} else if (data.indexOf('Status') == 0) {
			$('#loginBoxColumn2 .errorMessage').empty();
			$('#loginBoxColumn2 fieldset').addClass('hidden');
			$('#loginBoxColumn2 form').removeClass('hidden');
			$('#loginBoxColumn2 .errorMessage').removeClass('hidden');
			$('#loginBoxColumn2 .statusMessage').empty().html(data.replace('Status: ','')).removeClass('hidden');
		}
	}

	/**
	 * Recover lost password
	 */
	this.lostPassword = function() {
		var request = '/ratings/members/lost-password';
		if (! $.browser.msie6) {
			$('#loginBoxColumn1').css('opacity','0.5');
		}
		$('.loginBox_loading1').removeClass('hidden');
		$('#recoverPassword').addClass('hidden');
		$.post(request, {
			email: $('#email_recover').val()
		},ratings.lostPasswordCallback);
		return false; // prevent normal form submission
	}

	this.lostPasswordCallback = function(data) {
		if (! $.browser.msie6) {
			$('#loginBoxColumn1').css('opacity','1');
		}
		$('.loginBox_loading1').addClass('hidden');
		$('#recoverPassword').removeClass('hidden');
		if (data.indexOf('Error') == 0) {
			$('#lostPasswordForm .errorMessage').empty().html(data.replace('Error: ','')).removeClass('hidden');
		} else {
			$('#lostPasswordForm').hide();
			$('#email_login').val($('#email_recover').val());
			$('#loginForm .statusMessage').empty().html(data).removeClass('hidden');
			$('#loginForm .errorMessage').empty().addClass('hidden');
			$('#loginForm').show();
			$('#password_login').focus();
		}
	}

}
