//  @import com.hedgehoglab.application.view.BaseView;

//  @import com.hedgehoglab.solomon.helper.ContactViewHelper;
//  @import com.hedgehoglab.solomon.helper.TagHelper;

/**
*	@todo
			- Autofocus fields when items are added
			- 
*/

function ContactEditView(scope){
    BaseView.call(this,scope);
    var _this=this;

     var _helpers=new _this.generate_helpers(this,[TagHelper]);
     
     
     var model = null;
    

    this.setElement=function(element){
            scope.element=element;
        };
    
        this.render = function(datamodel){
          model = datamodel;

          model=$.extend(model,scope.general_types_model.get_types());

          var t=scope.element;
          var flag=false;
          var s=null;
          var template = 'contacts/edit_contact';
          
          //TODO check this stays here.
          _this.render_template_with_view(template,model,_helpers,function(f){
            $(scope.element).html(f);

            show_template(scope.element,model);
    			// 
            // $('a#link-contact-confirm', scope.element).bind('click', function(e){
            //   _this.raise_event('on_save_contact',{contact:model.contact});
            //   return false;
            // });

			$('input#link-contact-confirm', scope.element).bind('click', function(e){
              _this.raise_event('on_save_contact',{contact:model.contact});
              return false;
            });

    			//             // 
    		 $('a#link-contact-cancel', scope.element).bind('click', function(e){
   				_this.raise_event('on_edit_cancel',{});
   				return false;
   			 });
          });
          
        };
        
        function show_template(e,model){
            //  Item hover
            $('dd ',e).bind('mouseover',function(){
                $(this).addClass('hover');
            });
    
            $('dd ',e).bind('mouseout',function(){
                $(this).removeClass('hover');
            });
    
            $("input[name='firstName']",e).bind('keyup',function(f){
                model.contact.firstName=$(this).val();
            });
    
            $("input[name='lastName']",e).bind('keyup',function(f){
                model.contact.lastName=$(this).val();
            });
            
            $("input[name='title']",e).bind('keyup',function(f){
                model.contact.title=$(this).val();
            });

            $("textarea[name='info']",e).bind('keyup',function(f){
                model.contact.info=$(this).val();
            });

            /**
             * Bind email address fields
             */
            build_field_bindings({
                iterator:model.companies.iterator()
                //,types:scope.general_types_model.get_types().com

                ,add_action:$('#add_company',e)
                ,fields:$('#companies .company_field',e)
                ,field_template:"company_field"
                ,field_container:$('#companies',e)

                ,controller_add_message:'on_add_company_field_clicked'

                ,handlers:{
                    bind_events:function(options){
                        $("input[name='company']",options.field).bind('keyup',function(eee){
                            options.object.value().name = $(this).val();
                            
                        });

						//	@todo - Bind the autocomplete dropdown to this field for company names
						//	http://localhost:8080/api/companies
						function search(options,callback){
						    // options.limit = 30;
						    $.getJSON("/api/companies",function(e,stat){
						        
								if(e!=null){
									callback(e.company);
									//scope.on_empty_result(scope.element.val());
								}else{
									callback([]);
								}
						    });
						}
						
						$("input[name='company']",options.field).autocomplete(search,{
					        delay:400,
					        //width:297,
					        //autoFill:true,
							// matchContains: false,

							minchars:3,
							parse:function(data){
								var parsed = [];
					            var rows = data;
								if(data){
									$.each(data,function(i,row){
										parsed.push({
											data: row,
											value: row.name,
											result: row.name //options.formatResult && options.formatResult(row, row.city,data.length) || row.city
						   			    });
									});
								}
					            return parsed;
							},
							//	data[i].data, i + 1, max, data[i].value, term
					        formatItem: function(row, i, max, value, term) {
								//return row.city+" [ "+row.country+" ]";
								return row.name;
					        },
							//Data, Value
					        formatResult:function(row,value){
					            return "value";
					        },
							//Data, Value
							cacheLength:1

					    }).result(function(event,data,formatted){
							// scope.on_result(data,event,scope.element.val());
							return false;
					    });
						
                    }
                    ,on_remove_clicked:function(options){
                        _this.raise_event('on_remove_company_clicked',{company:options.object,remove:function(e){
                            $(options.field).slideUp(250,function(){$(this).remove();});
                        }});
                    }
                }
            });



            /**
             * Bind email address fields
             */
            build_field_bindings({
                iterator:model.email_addresses.iterator()
                ,types:scope.general_types_model.get_types().emailTypes.emailType
                
                ,add_action:$('#add_email_address',e)
                ,fields:$('#email_addresses .email_field',e)
                ,field_template:"email_field"
                ,field_container:$('#email_addresses',e)
    
                ,controller_add_message:'on_add_email_field_clicked'
    
                ,handlers:{
                    bind_events:function(options){
                        $("input[name='email']",options.field).bind('keyup',function(eee){
                            options.object.value().email = $(this).val();
                        });
    
                        $("select[name='type']",options.field).bind('change',function(eee){

                            options.object.value().type=options.types[$(this).val()];
                        });

						// $("input[name='email']",options.field).trigger('focus',{});
                    }
                    ,on_remove_clicked:function(options){
                        _this.raise_event('on_remove_email_clicked',{email:options.object,remove:function(e){
                            $(options.field).slideUp(250,function(){$(this).remove();});
                        }});
                    }
                }
            });
    
            /**
             * Bind phone number fields
             */
            build_field_bindings({
                iterator:model.telephones.iterator()
                ,types:scope.general_types_model.get_types().telephoneTypes.telephoneType

                ,add_action:$('#add_telephone_number',e)
                ,fields:$('#telephone_numbers .phone_field',e)
                ,field_template:"telephone_field"
                ,field_container:$('#telephone_numbers',e)
    
                ,controller_add_message:'on_add_phone_field_clicked'
    
                ,handlers:{
                    bind_events:function(options){
                        $("input[name='number']",options.field).bind('keyup',function(eee){
                            options.object.value().number = $(this).val();
                        });
    
                        $("select[name='type']",options.field).bind('change',function(eee){
                            options.object.value().type=options.types[$(this).val()];
                        });

						// $("input[name='number']",options.field).trigger('focus',{});
                    }
                    ,on_remove_clicked:function(options){
                        _this.raise_event('on_remove_phone_clicked',{phone:options.object,remove:function(e){
                            $(options.field).slideUp(250,function(){$(this).remove();});

                        }});
                    }
                }
            });
    
            /**
             * Bind address fields
             */
            build_field_bindings({
                iterator:model.addresses.iterator()
                ,types:scope.general_types_model.get_types().addressTypes.addressType

                ,add_action:$('#add_address',e)
                ,fields:$('#addresses .address-field',e)
                ,field_template:"address_field"
                ,field_container:$('#addresses',e)
    
                ,controller_add_message:'on_add_address_field_clicked'
    
                ,handlers:{
                    bind_events:function(options){
                        $("input[name='street']",options.field).bind('keyup',function(eee){
                            options.object.value().street = $(this).val();
                        });
                        $("input[name='city']",options.field).bind('keyup',function(eee){
                            options.object.value().city = $(this).val();
                        });
                        $("input[name='state']",options.field).bind('keyup',function(eee){
                            options.object.value().state = $(this).val();
                        });
                        $("input[name='zip']",options.field).bind('keyup',function(eee){
                            options.object.value().zip = $(this).val();
                        });
                        $("input[name='country']",options.field).bind('keyup',function(eee){
                            options.object.value().country = $(this).val();
                        });
    
                        $("select[name='type']",options.field).bind('change',function(eee){
                            options.object.value().type=options.types[$(this).val()];
                        });

						// $("input[name='street']",options.field).trigger('focus',{});
                    }
                    ,on_remove_clicked:function(options){
                        _this.raise_event('on_remove_address_clicked',{address:options.object,remove:function(e){
                            $(options.field).slideUp(250,function(){$(this).remove();});
                        }});
                    }
                }
            });
    
    
            /**
             * Bind website fields
             */
            build_field_bindings({
                iterator:model.websites.iterator()
                ,types:scope.general_types_model.get_types().websiteTypes.websiteType

                ,add_action:$('#add_website',e)
                ,fields:$('#websites .website_field',e)
                ,field_template:"website_field"
                ,field_container:$('#websites',e)
    
                ,controller_add_message:'on_add_website_field_clicked'
    
                ,handlers:{
                    bind_events:function(options){
                        $("input[name='url']",options.field).bind('keyup',function(eee){
                            options.object.value().url = $(this).val();
                        });
    
                        $("select[name='type']",options.field).bind('change',function(eee){
                            options.object.value().type=options.types[$(this).val()];
                        });
						
						// $("input[name='url']",options.field).trigger('focus',{});
                    }
                    ,on_remove_clicked:function(options){
                        _this.raise_event('on_remove_website_clicked',{website:options.object,remove:function(e){
                            $(options.field).slideUp(250,function(){$(this).remove();});
                        }});
                    }
                }
            });

			/**
             * Bind I.M. fields
             */
            build_field_bindings({
                iterator:model.ims.iterator()
                ,types:scope.general_types_model.get_types().imTypes

                ,add_action:$('#add_im',e)
                ,fields:$('#instantmessengers .instantmessengers_field',e)
                ,field_template:"instantmessengers_field"
                ,field_container:$('#instantmessengers',e)
    
                ,controller_add_message:'on_add_im_field_clicked'
    
                ,handlers:{
                    bind_events:function(options){
                        $("input[name='account']",options.field).bind('keyup',function(eee){
                            options.object.value().account = $(this).val();
                        });
                        //    
						$("select[name='type']",options.field).bind('change',function(eee){
							options.object.value().product=options.types.enums[$(this).val()];
						});
   						
   						// $("input[name='account']",options.field).trigger('focus',{});
                    }
                    ,on_remove_clicked:function(options){
                        _this.raise_event('on_remove_im_clicked',{im:options.object,remove:function(e){
                            $(options.field).slideUp(250,function(){$(this).remove();});
                        }});
                    }
                }
            });
        };
        
        function encapsulate_field(options){
            options.bind_events(options);
			if(options.field){
				$('a',options.field).bind('click',function(e){
                    options.on_remove_clicked(options);
                });	
			}else{
			}
            
        };
    
        function build_field_bindings(options){
            var i=0;
            while(options.iterator.hasNext()){
                encapsulate_field($.extend({
                    field:options.fields[i]
                    ,object:options.iterator.next(),
                    types:options.types
                },options.handlers));
    
                i++;
            };
    
			options.add_action.bind('click',function(ee){
				_this.raise_event(options.controller_add_message,{
					show:function(model){
                       _this.render_template_with_view(options.field_template,{model:model.value(),types:options.types},_helpers,function(f){
						var f=$(f).hide();options.field_container.append(f);f.fadeIn();
	                       encapsulate_field($.extend({
   	                           field:f
   	                           ,object:model,
   	                           types:options.types
   	                       },options.handlers));
	                   });
                   }
               });
		       return false;
		   });
        };
   
     	this.hide_loading=function(e){
			$('.contact-holder',scope.element).hide();
			scope.element.removeClass('loading-pane');

			setTimeout(function(e){
			//	scope.element.fadeIn(50);
				$('.contact-holder',scope.element).fadeIn(50);
			},1);
		};

		this.show_loading=function(){
			scope.element.html("");
				scope.element.addClass('loading-pane');
			scope.element.show();
		};
};