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

var SpeeddialAssistant = Class.create({
    initialize: function(params){//phone, person, cb, noOpCallback){
        this.cb = params.cb;
        this.noop = params.noOpCallback;
        this.person = params.person;
        this.phone = params.phone;
        this.popto = params.popto;
        this.buttons = [{
            number: 1,
            letter: 'E',
			symbol: '1',
            disabled: "disabled",
            hasNumber: 'has-number',
            value: $L('Voicemail')
        }, {
            number: 2,
            letter: 'R',
			symbol: '2',
            hasNumber: 'has-number'
        }, {
            number: 3,
            letter: 'T',
			symbol: '3',
            hasNumber: 'has-number'
        }, {
            number: 4,
            letter: 'D',
			symbol: '4',
            hasNumber: 'has-number'
        }, {
            number: 5,
            letter: 'F',
			symbol: '5',
            hasNumber: 'has-number'
        }, {
            number: 6,
            letter: 'G',
			symbol: '6',
            hasNumber: 'has-number'
        }, {
            number: 7,
            letter: 'X',
			symbol: '7',
            hasNumber: 'has-number'
        }, {
            number: 8,
            letter: 'C',
			symbol: '8',
            hasNumber: 'has-number'
        }, {
            number: 9,
            letter: 'V',
			symbol: '9',
            hasNumber: 'has-number'
        }, {
            letter: 'A',
			symbol: '&'
        }, {
            letter: 'H',
			symbol: '$'
        }, {
            letter: 'I',
			symbol: '%'
        }, {
            letter: 'J',
			symbol: '!'
        }, {
            letter: 'K',
			symbol: ':'
        }, {
            letter: 'L',
			symbol: '\''
        }, {
            letter: 'M',
			symbol: ';'
        }, {
            letter: 'N',
			symbol: '?'
        }, {
            letter: 'O',
			symbol: '"'
        }, {
            letter: 'P',
			symbol: '='
        }, {
            letter: 'Q',
			symbol: '/'
        }, {
            letter: 'S',
			symbol: '-'
        }, {
            letter: 'U',
			symbol: ')'
        }, {
            letter: 'W',
			symbol: '+'
        }, {
            letter: 'Y',
			symbol: '('
        } ];
    },
    
    setup: function(){
        var qdCallback = (function(resp){
            var buttons = this.buttons;
            buttons.each(function(b){
                b.phoneType = "gray";
                b.value = b.value || $L("+ Add Speed Dial")
            })
            resp.list.each(function(person){
                var button = buttons.find(function(b){
                    return b.letter == person.quickDial;
                });
				
				// The button could be null if the quickDial was set to B or Z from a previous build
				// where this used to be allowed.  Don't process this button and allow the user
				// to fix the problem
				if (!button) {
					return;
				}
				
                button.phoneType = "contact-phone-number";
                Object.extend(button, person);
				
				var fullName = "";
				["firstName", "middleName", "lastName"].each(function(field) {
					if (person[field]) {
						fullName = fullName + person[field] + " ";
					}
				});
				button.fullName = fullName.strip() || person.displayText || person.companyName || "";
                button.assigned = "assigned";
            });
            
            this.controller.get("SpeedDialContent").update(Mojo.View.render({
                collection: buttons,
                template: "speeddial/speeddial-button"
            }));
            
            var cb = this.setSpeedDial.bind(this);
            this.controller.select(".SpeedDialButton").each(function(el){
                el.observe(Mojo.Event.tap, cb)
            })
        }).bind(this)
        AppAssistant.contactsService.getQuickDials(this.controller, qdCallback);
        var showRemove = 'display:none;';
        if (this.phone.quickDial) 
            showRemove = '';
        
        this.controller.get("SpeedDialHeader").update(Mojo.View.render({
            object: {
                name: this.person.fullName,
                number: this.phone.value,
                type: this.phone.type,
                showRemove: showRemove,
                letter: this.phone.quickDial
            },
            template: "speeddial/header"
        }));
        
        this.controller.get("RemoveSpeedDial").observe(Mojo.Event.tap, this.confirmSetting.bind(this, false, null));
        
		this.controller.listen(this.controller.sceneElement, Mojo.Event.keypress, this.handleKeyPress.bind(this));
    },
	
	handleKeyPress: function(e) {
		var evt = e.originalEvent;
		
		if (!this.isValidSpeedDialChar(evt.keyCode))
			return;
		
		var ch = String.fromCharCode(evt.keyCode).capitalize();
		
		if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(ch) < 0) {
			for (var i = 0; i < this.buttons.size(); i++) {
				var thisButton = this.buttons[i];
				if (thisButton.symbol == ch) {
					ch = thisButton.letter;
					break;
				}
			}
		}
		
		var target = this.controller.get("sd_" + ch);
		
		this.setSpeedDialHelper(target, ch);
	},
	
	isValidSpeedDialChar: function(keyCode) {
		var s = String.fromCharCode(keyCode);
		var valid="acdfghijklmnopqrstuvwxyACDFGHIJKLMNOPQRSTUVWXY23456789/+()%\"=&-$!:'*#?;";
		
		if( valid.indexOf(s) >= 0 ) {
			return s;
		}
		return null;
	},
	
    setSpeedDial: function(e){
        var target = e.target;
        target = (target.hasClassName("SpeedDialButton")) ? target : target.up(".SpeedDialButton");
        if (target.hasClassName("disabled")) 
            return;
        var letter = target.id;
        letter = letter[3];
		
		this.setSpeedDialHelper(target, letter);
	},
	
	setSpeedDialHelper: function(target, letter) {
        var existingNumber = target.select(".contact-number-text")[0].innerHTML;
		
        if (target.hasClassName("assigned") && existingNumber != this.phone.value) {
            var confirmSetting = this.confirmSetting.bind(this, true);
            var existing = target.select(".contact-name")[0].innerHTML;
			var message = new Template($L("#{letter} is already assigned to #{existing}"));
			message = message.evaluate({
				letter:letter,
				existing:existing
			})
			
			var label = new Template($L("Reassign to #{fullName}"));
			label = label.evaluate({
				fullName:this.person.fullName
			})
            this.controller.showAlertDialog({
                onChoose: function(value){
                    if (value) {
                        confirmSetting(letter);
                    }
                },
                message: message,
                choices: [{
                    label: label,
                    value: true
                }, {
                    label: $L("Cancel"),
                    value: false
                }]
            });
        }
        else {
            this.confirmSetting(false, letter);
        }
    },
    
    //Set remove to true if you're overwriting an existing quickDial, letter is the quickdial you need to clear
    confirmSetting: function(remove, letter){
        if (remove) {
            AppAssistant.contactsService.removeQuickDials(this.controller, letter);
        }

		if (letter) {
			AppAssistant.contactsService.setQuickDial(this.controller, this.phone.id, letter);
			this.phone.hasQuickDial = "show-quick-dial"
		} else {
			AppAssistant.contactsService.removeQuickDials(this.controller, this.phone.quickDial);
			this.phone.hasQuickDial = "";
		}
		this.phone.quickDial = letter;
        this.phone.quickDialDisplay = letter;
        this.phone.size = letter ? "big" : "small";
        if (this.cb) 
            this.cb(this.phone);
        
        this.controller.stageController.popScenesTo(this.popto || 'detail');
    },

    cleanup: function(){
      if(this.noop) this.noop();
    }

})
