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

var MmsforwardAssistant = Class.create({
	initialize : function(params) {
		this.appController = Mojo.Controller.getAppController();
		this.Messaging = this.appController.Messaging;
		this.attachment;
		this.prePopulatedRecipients = [];
		this.sentRecipients = [];
		
		this.resizeHandler =
			this.handleWindowResize.bindAsEventListener(this);
			
		//this.searchListResizeHandler = 
		//		this.searchListResizeHandler.bindAsEventListener(this);
		
		var listviewSceneAssistant = this.Messaging.listviewSceneAssistant;
		if (listviewSceneAssistant) {
			this.toggleDebugMenu = listviewSceneAssistant.toggleDebugMenu.bind(listviewSceneAssistant,true);
		}

		this.appMenuAttrs = {omitDefaultItems: true};	
		this.appMenuModel = { visible:true, label: $L('Chat view menu'), items: [Mojo.Menu.editItem,Mojo.Menu.helpItem]};   
	 
		if(params && params.focusWindow)
			this.focusWindow = true;
		else
			this.focusWindow = false;

		if (params) {
			Mojo.Log.info("MMS Forward");
			this.passedAttachment = params.messageId + ".mmsforward";
			this.chatBalloonDiv = params.chatBalloonDiv;

			if(params.composeRecipients && params.composeRecipients.length) {
				for (var i = 0; i < params.composeRecipients.length; i++) {
					var recipient = params.composeRecipients[i];
					if (recipient.address) {
						this.prePopulatedRecipients.push({
							value: recipient.address,
							contactDisplay: recipient.address,
							type: (recipient.serviceName ? 'im' : 'phone'),
							serviceName: recipient.serviceName || ''
						});
					}
				}
			}
		}
		
		this.considerForSend = this.considerForSend.bind(this);
		this.handleRecipientsChanged = this.handleRecipientsChanged.bind(this);
	},

  setup: function() {
  	
	Mojo.Log.info("+++++setup");
    this.controller.setupWidget(Mojo.Menu.appMenu, this.appMenuAttrs, this.appMenuModel);

	this.searchList = {
		"property": "to$A",
		"includeEmails": false,
		"includePhones": true,
		"includeIMs": false,
		"includeShortCode": true,
		"hintText": $L('Enter name or number...'),
		"labelText": $L("To:"),
		"focus": true,
		"recipients": this.prePopulatedRecipients,
		"determineTypeFunction": function(str){
			if (str.indexOf("@") > -1) {
				return "email";
			}
			return "phone";
		}
	};
	
	this.controller.setupWidget('mmsContainer', {mode: 'vertical'});

    this.controller.setupWidget('searchList', null, this.searchList);   
  
    this.controller.listen('SendButton',Mojo.Event.tap, this.considerForSend);
	
	//this.controller.listen('searchList', 'resize', this.searchListResizeHandler);
	
	Mojo.Event.listen(this.controller.window, 'resize', this.resizeHandler, false);

  },

  ready: function() {
  	
	Mojo.Log.info("+++++ready");
	
	this.actionButton = this.controller.get('ActionButton');
	this.addressingForm = this.controller.get('addressingForm');
	this.addressingWidget = this.controller.get('searchList');
	this.mmsMessageScroller = this.controller.get('mmsMessageScroller');

	
	// Observe add/delete to the addressing widget
    var that = this;
    [Mojo.Event.addressingRecipientAdded,Mojo.Event.addressingRecipientDeleted].each(function(event) {
      that.controller.listen('searchList',event,that.handleRecipientsChanged);
    });	
	
	this.resizeScroller();
	
	var placeholder = this.controller.get('mmsMessagePlaceholder');

	//Mojo.Log.info(this.chatBaloon.innerHTML);
	Mojo.Log.info(this.chatBalloonDiv);
	
	/*
	 * put div into placeholder
	 */
	placeholder.update(this.chatBalloonDiv);

	/*
	 * Hide items in div that are not actually part of the MMS message
	 * usch as error icon or "Message sent..." delayed receive 
	 * message
	 */
	for (var i=0; i<placeholder.children.length; i++){
		var child = placeholder.children.item(i);

		if (child.hasClassName('delayedMessage')){
			child.hide();
		} else if (child.hasClassName('messageText')){
			/*
			 * look for error img
			 */
			
			for (var j=0; j<child.children.length; j++){
				var grandchild = child.children.item(j);

				if (grandchild.hasClassName('error')){
										
					Mojo.Log.info("found it");
					grandchild.hide();
					
				}
			}
		}
	}
	
	if (this.passedAttachment) {
		this.attachFile(this.passedAttachment);
	}
  },
  
  	handleWindowResize: function(event) {
		this.resizeScroller();
	},
  
  considerForSend: function(){
		var recipientsArray = Mojo.View.serializeMojo(this.addressingForm, true).to$A;

		if ($A(recipientsArray).length > 0) {
			var phoneRecipients = [];

			// separate the different types of recipients
			for(var x=0; x<recipientsArray.length; x++) {
				var recipient = recipientsArray[x];
				if (recipient.serviceName) {
					Mojo.Log.info("forward MSM only to phone recips");
				} else {
					phoneRecipients.push(recipient);
				}
			}

			// send to phone recipients
			if (phoneRecipients.length > 0) {
				this.sendMessage(phoneRecipients);
			}


			this.sentRecipients = recipientsArray;
		} else {
			this.controller.showAlertDialog({
				onChoose: function(){
				},
				title: $L("Please choose a recipient."),
				choices: [{
					label: $L('Done'),
					value: 'Ok'
				}]
			});
		}     
  },
  
	sendMessage: function(recipientsArray) {
		Mojo.Log.info("+++++sendMessage");
		if(!this.handleSentMessageResponse) {
			this.handleSentMessageResponse = this._handleSentMessageResponse.bind(this);
		}
		var params = {
			recipientJSONArray: recipientsArray,
     		messageText: '',
      		onSuccess: this.handleSentMessageResponse
		};
		if (this.attachment) { // sending an attachment
			params.attachment = this.attachment;
			//params.summary = $L('New picture message');
			params.summary = '';
		}
		this.actionButton.addClassName('invisible');
		MessagingMojoService.sendMessageFromCompose(this.controller, params); 
	},
  
   _handleSentMessageResponse: function (result) {
   	Mojo.Log.info("+++++_handleSentMessageResponse");
   	//this.controller.stageController.popScene();
   	
	if(this.sentRecipients.length == 1) {
		Mojo.Log.info("single recipient, go to that chat");
		this.controller.stageController.swapScene({name:'chatview', transition:Mojo.Transition.crossFade}, result.chatThreadId);
	} else {
		Mojo.Log.info("mulitple recipients, go to list view on send");
		// if we have multiple recipients, just pop this scene + set the current view to be the history view
		this.Messaging.setListViewVisible(this.Messaging.Views.HISTORY);
		if(!MessagingUtils.sceneExistsInStack(this.controller.stageController,'listview')) {
			this.appController.assistant.getListChunk(this.controller,this.handleListChunkOnPop.bind(this));
		} else {
			this.controller.stageController.popScenesTo('listview');
		}			
	}

  },
  
    handleRecipientsChanged: function() {
		this.resizeScroller();
  },
  
	attachFile: function(attachmentPath,displayPath) {
		if (attachmentPath) {

			var recipientsArray = Mojo.View.serializeMojo(this.addressingForm, true).to$A;

			this.attachment = attachmentPath;
			this.searchList.includeIMs = false;
			this.controller.modelChanged(this.searchList);
		}
	},
  
  cleanup: function() {
	
    this.controller.stopListening('SendButton',Mojo.Event.tap, this.considerForSend);
	Mojo.Event.stopListening(this.controller.window, 'resize',
						this.resizeHandler, false);
	
  },

  activate: function() {
	if(this.focusWindow) {
		this.focusWindow = false;
		this.controller.stageController.activate();
	}  	
  },
	
	handleListChunkOnPop: function(forceListView,result) {
		this.controller.stageController.popScenesTo('listview');
		this.controller.stageController.pushScene('listview',{forceListView:forceListView, listDataChunk:result});
	},
	
	//searchListResizeHandler: function(){
	//	Mojo.Log.info("+++++++++++++++++++++++HERE");
	//},
	
	resizeScroller: function(){
		this.mmsMessageScroller.setStyle({
			'height': (Mojo.View.getViewportDimensions(this.controller.document).height - this.addressingWidget.offsetHeight) + "px"
		});
		//Mojo.Log.info(this.mmsMessageScroller);
		//this.mmsMessageScroller.setStyle({
		//	'height': "100px"
		//});
	}
  
});
