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


// TODO: clean up the contract between this and the list assistant
// should probably be widget-like-- the scene includes some generic GAL div and here it's fleshed out
// and behaviors are hooked up to it.  The main interaction with the rest of the scene is just
// reading the filter string, updating the count, and returning a GAL contact to view details. 

GALHelper = Class.create({
	initialize: function(assistant) {
		this.asst = assistant;
		
		this.toggler = this.asst.controller.get("GalDrawerOpener");
		this.counter = this.asst.controller.get("GALCountResults");
		this.counterContainer = this.asst.controller.get("GALCountContainer");
		this.listDiv = this.asst.lookups;
		this.lookupsModel = this.asst.lookupsModel;
		this.controller = this.asst.controller;
		this.timeout = 1;
		this.searching = false;
		this.currentCountQuery = null;
	},
	
	setup: function() {
		
	},
	
	toggle: function() {
		this.toggler.toggleClassName("open");
		this.listDiv.toggle();
	},
	
	reset: function() {
		this.lookupsModel.items = [];
		this.controller.modelChanged(this.lookupsModel);
		this.toggler.removeClassName("open");
		this.listDiv.hide();
		this.counter.update("");
		this.counterContainer.hide();
	},
	
	isOpen: function() {
		return this.toggler.hasClassName("open");
	},
	
	//TODO get better rules for when to search
	doSearch: function(q) {
		this.searching = true;
		this.currentCountQuery = this.asst.controller.serviceRequest("palm://com.palm.mail", {
			method: "queryGAL",
			onSuccess: this.updateCount.bind(this),
			parameters: {
				target: this.asst.filter,
				offset: 0,
				limit: 1
			}
		});		 	
	},
	
	scheduleCountLookup: function() {
		if(!this.searching) {
			this.doSearch();
		} else {
			clearTimeout(this.queued);
			this.queued = setTimeout(this.doSearch.bind(this), this.timeout);
		}
	},
	
	cancelCountLookup: function() {
		if(this.currentCountQuery) {
			this.currentCountQuery.cancel();
			clearTimeout(this.queued);
			this.searching = false;
		}
		this.reset();
	},
	
	updateCount : function(results) {
		this.counter.update(results)
		this.counterContainer.show();
	},
	
	makeContact: function(rawC) {
		var c = new Contact();
		c.firstName = rawC.firstName;
		c.lastName = rawC.lastName;
		c.jobTitle = rawC.jobTitle;
		c.companyName = rawC.companyName;
		rawC.addressList.each(function(addr) {
			if (addr.type === 'EMAIL') {
				var email = new Email(addr.value);
				Object.extend(email, addr);
				c.emailAddresses.push(email);
			}
			if (addr.type === 'PHONE') {
				var number = new PhoneNumber(addr.value);
				Object.extend(number, addr);
				c.phoneNumbers.push(number);
			}
			if(addr.type === 'ADDRESS'){
				var address = new Address({
					freeformAddress: addr.value
				});
				Object.extend(address, addr);
				c.addresses.push(address);
			}
		});
		return c;
	}
	
});
