/**
*	@param scope
*/
//  @import com.hedgehoglab.application.controller.BaseController;
//  @import com.hedgehoglab.solomon.model.ContactModel;


function ContactEditController(scope){
	BaseController.call(this,scope);
	// alert("ContactEditController");
    var _this = this;
	var contact;
	var _emails = null;
	var _telephones = null;
	var _websites = null;
	var _addressess = null;
	var _companies = null;
	var _ims = null;
	

	this.show_view = function(empty,callback){
		if (!empty){
			load_contact_data(scope.model.model(),callback);
		}else{
			load_contact_data(empty,callback);
		}
	};


        
	scope.view.subscribe_to('on_save_contact',function(event){
		//Need to notify the select list to select the new contact by default
		contact=event.contact;
		// var message_to_raise = "on_update_contact";
		// if (!contact.id) message_to_raise = "on_save_new_contact";
		//if (!contact.id) message_to_raise = "on_save_contact";
		// 
		scope.contacts_service.save_contact(contact,function(result){
			//	If an error was raised trap it
// console.log("The saved contact is ",result)
				// scope.model.model(result);
				contact=result;
				_this.raise_event("on_save_contact",result);
		});
	});
    

    
        function load_contact_data(event,callback){
			contact = $.extend(true,{},event);
    
                var req_count=0;
                var _notes=null;
                var _tasks=null;
    			scope.view.show_loading();
                if (event.id)
                {
                Async.multi_thread_load([
                    //  Load contact data
                    function(callback){
                        scope.contacts_service.get_contact_by_id(contact.id, function(data){
                           contact = data;
                           callback();
                        });
                    }
                    //  Load all users
                    ,function(callback){
                        scope.user_service.get_all_users(function(data){
                            scope.users_model.model(data);
                            callback();
                        });
    
                    }//  Load tags
                    ,function(callback){
                        scope.contacts_service.get_tags_for_contacts(contact.id,function(data){
                            contact.tags=data;
                            callback();
                        });
                    }
                ]
    
                //  Handle all loaded
                ,function(){
                    _emails = new LinkedList((null!=contact.emailAddresses)?contact.emailAddresses.emailAddress:[]);
                    _telephones = new LinkedList((null!=contact.phoneNumbers)?contact.phoneNumbers.phoneNumber:[]);
                    _websites = new LinkedList((null!=contact.websites)?contact.websites.website:[]);
                    _addresses = new LinkedList((null!=contact.addresses)?contact.addresses.address:[]);
                    _companies = new LinkedList((null!=contact.companies)?contact.companies.company:[]);
					_ims = new LinkedList((null!=contact.instantMessengers)?contact.instantMessengers.instantMessenger:[]);

                    scope.view.render({contact:contact,
                      email_addresses:_emails,
                      telephones:_telephones,
                      websites:_websites,
                      addresses:_addresses,
                      companies:_companies,
					  ims:_ims
                    },"edit");

					callback(function(e){
						//alert("asdasd");
						scope.view.hide_loading();
					});
                });
              }
              else
              {
                contact = $.extend(contact,{tags:{tag:[]}});
                _emails = new LinkedList((null!=contact.emailAddresses)?contact.emailAddresses.emailAddress:[]);
                _telephones = new LinkedList((null!=contact.phoneNumbers)?contact.phoneNumbers.phoneNumber:[]);
                _websites = new LinkedList((null!=contact.websites)?contact.websites.website:[]);
                _addresses = new LinkedList((null!=contact.addresses)?contact.addresses.address:[]);
                _companies = new LinkedList((null!=contact.companies)?contact.companies.company:[]);
				_ims = new LinkedList((null!=contact.instantMessengers)?contact.instantMessengers.instantMessenger:[]);
                
				scope.view.render({contact:contact,
                  email_addresses:_emails,
                  telephones:_telephones,
                  websites:_websites,
                  addresses:_addresses,
                  companies:_companies,
				  ims:_ims
                },"edit");
				
			callback(function(e){
				scope.view.hide_loading();
			});
              }
        };





        scope.view.subscribe_to('on_remove_company_clicked',function(event){
			scope.contacts_service.remove_company_from_contact(contact,event.company.value(),function(e){
            	event.company.remove();
	            contact.companies.company = _companies.serialise();
	            event.remove(event);
			});
        });

        scope.view.subscribe_to('on_add_company_field_clicked',function(event){
            scope.contacts_service.new_company_for_contact(contact,function(e){
                var ee =_companies.new_list_item(e);
                contact.companies.company = _companies.serialise();
                event.show(ee);
            });
        });



        scope.view.subscribe_to('on_remove_email_clicked',function(event){
			scope.contacts_service.remove_email_address_from_contact(contact,event.email.value(),function(e){
				event.email.remove();
	            contact.emailAddresses.emailAddress = _emails.serialise();
	            event.remove(event);
			});
        });
    
        scope.view.subscribe_to('on_add_email_field_clicked',function(event){
              scope.contacts_service.new_email_address_for_contact(contact,function(e){
                  var ee =_emails.new_list_item(e);
                contact.emailAddresses.emailAddress = _emails.serialise();
                event.show(ee);
            });
        });
    
        scope.view.subscribe_to('on_remove_phone_clicked',function(event){
			scope.contacts_service.remove_phonenumber_from_contact(contact,event.phone.value(),function(e){
            	event.phone.remove();
	            contact.phoneNumbers.phoneNumber = _telephones.serialise();
	            event.remove(event);
			});
        });
    
        scope.view.subscribe_to('on_add_phone_field_clicked',function(event){
            scope.contacts_service.new_phonenumber_for_contact(contact,function(e){
                var ee =_telephones.new_list_item(e);
                contact.phoneNumbers.phoneNumber = _telephones.serialise();
                event.show(ee);
            });
        });
    
    
        scope.view.subscribe_to('on_remove_address_clicked',function(event){
			scope.contacts_service.remove_address_from_contact(contact,event.address.value(),function(e){
	            event.address.remove();
	            contact.addresses.address = _addresses.serialise();
	            event.remove(event);
			});
        });
    
        scope.view.subscribe_to('on_add_address_field_clicked',function(event){
            scope.contacts_service.new_address_for_contact(contact,function(e){
                var ee =_addresses.new_list_item(e);
                contact.addresses.address = _addresses.serialise();
                event.show(ee);
            });
        });
    
        scope.view.subscribe_to('on_remove_website_clicked',function(event){
			scope.contacts_service.remove_website_from_contact(contact,event.website.value(),function(e){
	            event.website.remove();
	            contact.websites.website = _websites.serialise();
	            event.remove(event);
			});
        });
    
        scope.view.subscribe_to('on_add_website_field_clicked',function(event){
            scope.contacts_service.new_website_for_contact(contact,function(e){
                var ee =_websites.new_list_item(e);
                contact.websites.website = _websites.serialise();
                event.show(ee);
            });
        });

        scope.view.subscribe_to('on_remove_im_clicked',function(event){
			// console.info("REMOVING IM",event);
			scope.contacts_service.remove_im_from_contact(contact,event.im.value(),function(e){
	            event.im.remove();
	            contact.instantMessengers.instantMessenger= _ims.serialise();
	            event.remove(event);
			});
        });
    
        scope.view.subscribe_to('on_add_im_field_clicked',function(event){
            scope.contacts_service.new_im_for_contact(contact,function(e){
                var ee =_ims.new_list_item(e);
                contact.instantMessengers.instantMessenger = _ims.serialise();
                event.show(ee);
            });
        });
        
    
       scope.view.subscribe_to('on_add_tag',function(e){
           //  Check it doesnt already exist in the list
           var tag={"label":e.tag};
    
           scope.contacts_service.add_tag_to_contact(e.contact,tag,function(eee){
               e.render(e.contact);
           });
       });
    
       scope.view.subscribe_to('on_remove_tag',function(e){
           scope.contacts_service.remove_tag_from_contact(e.contact,{id:e.index},function(eee){
               var newArray = [];
               $.each(e.contact.tags.tag,function(index,existingTag){
                 if (existingTag.id!=e.index)
                 {
                   newArray.push(existingTag);
                 }
               });
               e.contact.tags.tag = newArray;
               e.render(e.contact);
           });
       });
    
    
};