/* Copyright 2009 Palm, Inc.  All rights reserved. */

var AddCommentAssistant = Class.create({
	
    initialize: function(appDetails, firstname, lastname)
	{
		this._appDetails = appDetails;
		this._details = appDetails.getDetails();
		this._myRating = appDetails.getMyRating();
		this._stars = 0;
		
		this._firstName = firstname;
		this._lastName = lastname;
	},
	
    setup: function()
	{
		this._changeStars = this._changeStars.bindAsEventListener(this);
		
		this.controller.get('title').innerText = this._details.title;
		this.controller.get('subtitle').innerText = this._details.creator;
		this.controller.get('icon').style.backgroundImage = 'url(' + this._details.appIcon + ')';
        
        this.controller.setupWidget(
            'add_comment_subject', 
            {
                hintText: $L('Enter title...'),
                modifierState: Mojo.Widget.steModeSentenceCase,
                focusMode: Mojo.Widget.focusInsertMode,
            }
        );
		this._commentSubject = this.controller.get('add_comment_subject');
        
        this.controller.setupWidget(
            'add_comment_body', 
            {
                hintText: $L('Enter review here...'),
                focus: true,
                multiline: true,
                modifierState: Mojo.Widget.steModeSentenceCase,
                focusMode: Mojo.Widget.focusInsertMode,
            },
			{
				value: this._myRating != null ? this._myRating.comment : ""
			}
        );
		this._commentBody = this.controller.get('add_comment_body');
		
		this._starGroup = this.controller.get('stars');
		var stars = [];
		for (var child = this._starGroup.firstChild; child; child = child.nextSibling)
		{
			if (child.tagName == 'IMG')
			{
				stars.push(child);
			}
		}
		this._stars = stars;
		this._setAverageStars();
		
		// Menus
		Weave.Utilities.AppMenu.useDefault(this);
		
		// Set up a command menu
		this.controller.setupWidget(Mojo.Menu.commandMenu, 
		{
			menuClass: 'no-fade', 
		}, {
			items: [
				{},
				{},
				{
	                label: $L('Save'),
	                command: 'addreview',
					icon: 'send'
	            },
			],
		});
		
		this._commentorModel = 
		{
			choices:
			[
				{label: this._firstName + ' ' + this._lastName, value: "fullname"},
				{label: this._firstName + ' ' + this._lastName.substring(0, 1), value: "firstinitial"},
				{label: $L("Anonymous"), value:"anonymous"}
			],
			commentAs: "firstinitial"
		};
		this.controller.setupWidget('commentasSelector', {label:"", modelProperty: "commentAs"}, this._commentorModel);
    },
	
	activate: function()
	{
		this._starGroup.addEventListener('mouseover', this._changeStars);
	},
	
	deactivate: function()
	{
		this._starGroup.removeEventListener('mouseover', this._changeStars);
	},
	
	handleCommand: function(event)
	{
		if (event.type == Mojo.Event.command && event.command == 'addreview')
 		{
			var score = this._stars.value < 0 ? 0 : this._stars.value;	
			if (score == 0) 
			{
				// ask user to set the score
				var self = this;
				this.controller.showAlertDialog(
				{
			    	onChoose: function(value)
					{
						if (value == 'rate')
						{
							self._addReview();
						}
					},
					title: $L("App Rating"),
				    message: $L("Did you forget to rate the application? Rating is currently set to zero."), 
				    choices:
					[
						{label:$L('Change my rating'), value:'change', type:"primary"},
			        	{label:$L("Rate as zero"), value:'rate', type:"secondary"},
				    ]
			  	});
			}
			else 
			{
				this._addReview(event);
			}
 		}
	},
	
	_addReview: function(event)
	{	
		var comment = this._commentBody.mojo.getValue();
		var score = this._stars.value < 0 ? 0 : this._stars.value;
		var isAnonymous = (this._commentorModel.commentAs == "anonymous");
		var accountId;
		
		if (!isAnonymous)
		{
			for (var i = 0; i < this._commentorModel.choices.length; i++)
			{
				if (this._commentorModel.choices[i].value == this._commentorModel.commentAs)
				{
					accountId = this._commentorModel.choices[i].label;
					break;
				}
			}
		}
	
		
		var self = this;
		Mojo.Log.info("AddCommentAssistant._addReview sending: ", comment, score, isAnonymous);
		Weave.Services.ApplicationServer.addUserComment(this._details.id, comment, score, Mojo.Locale.current, accountId, isAnonymous, false, 
		function(status, response)
		{
			if (status) 
			{
				// refresh this apps details to get new comments & user rating
				self._appDetails.getMyCommentFromServer();
				self.controller.stageController.popScene();
			}
			else
			{
				self.controller.showAlertDialog(
				{
			    	onChoose: function(value){},
					title: $L("Error"),
				    message: $L("Could not submit your review at this time. Try again later."), 
				    choices:
					[
						{label:$L('OK'), value:'ok'}
				    ]
			  	});
			}
		});
	},
	
	_setAverageStars: function()
	{
		var rating = this._myRating != null ? this._myRating.score : 0;
		var halfstars = Math.round(rating * 2);
		var stars = this._stars;
		
		for (var i = 0; i < 5; i++) 
		{
			stars[i].src = this._formatStar(halfstars, i);
		}
		stars.value = rating;
	},
	
	_formatStar: function(halfstars, idx)
	{
		halfstars -= 2 * idx;
		if (halfstars > 0)
		{
			if (halfstars > 1)
			{
				return 'images/star-xl-yellow-full.png';
			}
			else
			{
				return 'images/star-xl-yellow-half.png';
			}
		}
		else
		{
			return 'images/star-blue-empty.png';
		}
	},
	
	_changeStars: function(event)
	{
		var target = event.target;
		var stars = this._stars;
		for (var i = 0; i < 5; i++) 
		{
			if (stars[i] == target) 
			{
				stars.value = i + 1;
				for (var j = 0; j < 5; j++) 
				{
					if (j <= i) 
					{
						stars[j].src = 'images/star-blue-full.png';
					}
					else 
					{
						stars[j].src = 'images/star-blue-empty.png';
					}
				}
				break;
			}
		}
	}
});