//  @import com.hedgehoglab.application.view.BaseView;
//  @import com.hedgehoglab.solomon.helper.ContactViewHelper;
//	@import com.hedgehoglab.application.helper.BaseHelper;
//  @import com.hedgehoglab.solomon.helper.TagHelper;


/**
*	@todo
			- Autofocus fields when tagging etc..
			- 
*/
function ContactDetailView(scope){
  BaseView.call(this,scope);
  var _this=this;
  var _helpers=new _this.generate_helpers(this,[TagHelper,ContactViewHelper]);
  var _original_merge_message = null;
  ContactViewHelper.call(_this,scope);
  
  this.render=function(event,callback,mode){
      if (mode == 'edit')
      {
        do_edit(event);
        return true;
      }

      switch(event.model.length){
          case 0:do_zero(callback);break;
          case 1:do_one(event,callback);break;
          default:do_many(event,callback);break;
      };
  };

  function do_zero(callback){
	//	This is the true implementation
      _this.render_template_with_view('contacts/NoContactsShowView',{},_helpers,function(rendered_template){
          scope.element.html(rendered_template);
			if(callback) callback();
      });
  };

  function do_many(event,callback){
	//	This is the true implementation
    var _view={};
    var _view2={};


    if(event.model.length > 20)
    {
      _template = 'contacts/ManyManyContactsShowViewSummary';
    }else if(event.model.length > 6){
		_template = 'contacts/ManyContactsShowViewSummary';
	}else
    {
      _template = 'contacts/ManyContactsShowView';
    }// else if 

    _contacts = event.model;
    // Only pass the exact list of contacts to the template!

    _this.render_template_with_view(_template,
      {contacts:_contacts,selected:event.selected},_this,
      function(rendered_template){
          
        var t=$(rendered_template);
        
        $('.toolbar ul li span.tagging-field').hide().removeClass('hide');
        $('.toolbar ul li span.merging-confirm').hide().removeClass('hide');
        scope.element.removeClass('merging-list');


        // Magic merge
        $('a#link-contact-merge',t).bind('click',function(e){
            $('.toolbar ul li',scope.element).hide();
            $('.toolbar ul li.merge-ui a',scope.element).hide();
			$('.toolbar ul li.merge-ui input',scope.element).hide();
			
            $('.toolbar ul li.merge-ui',scope.element).show();
            $('.toolbar ul li p.merge-message',scope.element).show();
            $('.toolbar ul li p.merge-confirm-message',scope.element).hide().removeClass('hide');

            $('.toolbar ul li span.merging-confirm',scope.element).hide().removeClass('hide').show();
            $('.toolbar ul li span.merging-confirm #cancel-merge',scope.element).show();
            scope.element.addClass('merging-list');

          return false;
        });
        
        $('.contacts-fat-list li.contact-card',t).hover(function(){
            if (scope.element.hasClass('merging-list')) {
              $(this).addClass('contact-card-hover');
            }
          },function(){
            if (scope.element.hasClass('merging-list')) {
              $(this).removeClass('contact-card-hover');
            }       
        });
        
        $('.contacts-fat-list li.contact-card',t).bind('click',function(){
			//	Need to refactor the hell out of this!
          if (scope.element.hasClass('merging-list')) {
            $('.contacts-fat-list li.contact-card',scope.element).removeClass('contact-card-selected');
            $(this).addClass('contact-card-selected');
            $('.toolbar ul li span.merging-confirm #confirm-merge',scope.element).show();
            $('.toolbar ul li p.merge-message',scope.element).hide();

			//	??? whats with _original_merge_message?
            if (_original_merge_message==null) _original_merge_message = $('.toolbar ul li p.merge-confirm-message',scope.element).html();

            var destination_name = $('.contact_name',$(this)).html();
            if (destination_name==null || destination_name=="" || destination_name=="&nbsp;") destination_name="the selected contact";
            $('.toolbar ul li p.merge-confirm-message',scope.element).html(_original_merge_message.replace("[NUM]",_contacts.length-1).replace("[NAME]",destination_name));
            $('.toolbar ul li p.merge-confirm-message',scope.element).show();
          }
        });
        
        $('#cancel-merge',t).bind('click',function(){
          $('.contacts-fat-list li.contact-card',scope.element).removeClass('contact-card-selected');
          scope.element.removeClass('merging-list');
          $('.toolbar ul li span.merging-confirm',scope.element).hide();
          $('.toolbar ul li',scope.element).show();
          $('.toolbar ul li.merge-ui a',scope.element).show();
			$('.toolbar ul li.merge-ui input',scope.element).show();
          return false;
        });
        
        $('#confirm-merge',t).bind('click',function(){
          var destination = $('.contact-card-selected').attr("rel");
          _this.raise_event('on_merge_contacts_clicked',{contacts:_contacts,destination:destination});
        });

		/**
        * Everything TAG!!!!
        */
        
        $('a#link-contact-tag',t).bind('click',function(e){
            //  Show the tagging box
           //   $(link-contact-tag)

            //  hide all li's except the ui li
            //  Hide the link in the li
            $('.toolbar ul li',scope.element).hide();
            $('.toolbar ul li.tag-ui a',scope.element).hide();
            $('.toolbar ul li.tag-ui',scope.element).show();
            $('.toolbar ul li span.tagging-field a',scope.element).show();
            $('.toolbar ul li span.tagging-field',scope.element).hide().removeClass('hide').show();
			
			$('.toolbar ul li span.tagging-field ul li',scope.element).show();
			scope.element.addClass('_mark_as_tagging_');
			
			//	Focus the field when the action has been pressed
			$('.toolbar ul li span.tagging-field input#multi-tag-field',t).trigger('focus',{});
			
			 $('.toolbar ul li span.tagging-field input#multi-tag-field',t).bind('keyup',function(e){
                  if (e.keyCode==13) {
                      $('.toolbar ul li span.tagging-field a#add-tag',t).trigger('click');
                  }

                  if (e.keyCode==27) {
                    $('.toolbar ul li span.tagging-field a#cancel-tag',t).trigger('click');
                  }
                });

          return false;
        });

        //  Add autocomplete to tag field
        function load_data(options,callback){
            _this.raise_event('on_tag_term_changed',{
                term:options.q,
                update_tags:function(e){
                    callback(e);
                }
            });
        };

        $('.toolbar ul li span.tagging-field input#multi-tag-field',t).autocomplete(load_data,{
            cacheLength:1,
			delay:400
        });

        bind_remove_tag_action_to_links();
          
        //  Bind remove tag action to tags
        function bind_remove_tag_action_to_links(){
            //  Add hooks onto links to remove contacts
            $('".contacts-fat-list ul li dd ul.tags-list li a',t).bind('click',function(e){
				//	If we are editing tags then allow the click
				
				if(scope.element.hasClass('_mark_as_tagging_')){
					var tag_id=$(this).attr('href');
	                var index=$(this).attr('rel');
	                var _a=$(this);
	                _this.raise_event('on_tag_remove_clicked',{tag_id:tag_id,contact:_contacts[index],update:function(){
	                        _a.parent().fadeOut(function(){
	                            _a.parent().remove();
	                        });
	                    }
	                });
				}
                
                return false;
            });
        };



        $('.toolbar ul li span.tagging-field a#add-tag',t).bind('click',function(e){
            var tag_string=$('.toolbar ul li span.tagging-field input#multi-tag-field',scope.element).val();
            if(tag_string!=""){
                $('.toolbar ul li span.tagging-field input#multi-tag-field',scope.element).val("").trigger('focus',{});
                _this.raise_event('on_tag_contacts_clicked',{tag:tag_string,
                    update:function(e){
                        //  Render each contacts tags
                        $.each(_contacts,function(i,n){
                             var ul=$(".contacts-fat-list ul li[rel='"+n.id+"'] dd ul.tags-list",scope.element);

                            _this.render_template_with_view("many_contacts_tags",{tag:n.tag,contact:n,index:i},_view,
                                function(rendered_template){
                                    var nul=$(rendered_template);
                                    ul.replaceWith(nul);

                                }
                            );

                        });

                        bind_remove_tag_action_to_links();
                    }
                });
            }
        });

        $('a#cancel-tag',t).bind('click',function(e){
            $('.toolbar ul li span.tagging-field input#multi-tag-field',t).val("");
            $('.toolbar ul li span.tagging-field',t).hide();
            $('.toolbar ul li',t).show();
            $('.toolbar ul li.tag-ui a',t).show();
			scope.element.removeClass('_mark_as_tagging_');
            return false;
        });


        $('a#link-contact-delete',t).bind('click',function(e){
          _this.raise_event('on_delete_contacts_clicked',_contacts);
          return false;
        });

        $('a#link-contact-export', t).bind('click', function(e){
	      //_this.raise_event('on_export_contacts_clicked',{});
			//  Show the tagging box
           //   $(link-contact-tag)

            //  hide all li's except the ui li
            //  Hide the link in the li
            $('.toolbar ul li',scope.element).hide();
            $('.toolbar ul li.export-ui a',scope.element).hide();
            $('.toolbar ul li.export-ui',scope.element).show();
            $('.toolbar ul li span.exporting-field a',scope.element).show();
            $('.toolbar ul li span.exporting-field',scope.element).hide().removeClass('hide').show();

			$('.toolbar ul li span.exporting-field ul li',scope.element).show();
          return false;
        });

		//	Make links ajaxy
		
		$('.toolbar ul li span.exporting-field ul li a',t).bind('click',function(e){
			if($(this).attr('href')!="#"){
				var url=$(this).attr('href').split("?");
				$.download(url[0],url[1],'post');
			}
			return false;
		})
		
		
		$('a#cancel-export',t).bind('click',function(e){
            
            $('.toolbar ul li.export-ui a',scope.element).show();
            $('.toolbar ul li.export-ui',scope.element).hide();
            $('.toolbar ul li span.exporting-field a',scope.element).hide();
            $('.toolbar ul li span.exporting-field',scope.element).hide();

			$('.toolbar ul li span.exporting-field ul li',scope.element).hide();
			$('.toolbar ul li',scope.element).show();
			
			return false;
        });
      
		callback(function(e){
			scope.element.append(t);
		});
    });
  };

  function do_one(event,callback){
	_this.render_template_with_view(
		'contacts/ContactView',
        {general_types:scope.general_types_model.get_types()},// Model
        _helpers,// View
        function(rendered_template){
            var t=$(rendered_template);
    		scope.ve_view.setElement($('.contact-card-panel',t));
			scope.nt_view.setElement($('#contact-NT',t));
            scope.contact_deals_view.setElement($('.contact-meta-pane',t));
			callback(function(){
				scope.element.html(t);
				
			});

          }
      );
  };
  
 
  
  // Do initial view
  do_zero();
  
	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(){
		$('.contact-holder',scope.element).hide();
		scope.element.html("");
			scope.element.addClass('loading-pane');
		scope.element.show();
	};
};