var IDN = function(){

    var init = {};/*A collection of public functions with DOM bindings */
    var $item = false;
    
    init.modal = function(){    
        $.extend($.modal.defaults, {
            opacity:80,
            onClose: function(){
            	$('.box-body-item-hover-ul').removeClass('box-body-item-hover-ul');
            	$.modal.close();
            	return;
            },
            overlayClose: true,
            maxHeight:500,
             position: ['8%'],
            //closeClass: 'popup-close'
        });
        //Rebind for live
        $('.simplemodal-close').live('click',function(e){
            e.preventDefault();
            $.modal.close();
            return;
        });
        /*
        $('.modal').live('click',function(e){
            e.preventDefault();
            $this = $(this)
            $.get($this.attr('href'),function(d){
				$this.parents('form').html(d);
            });
        });*/
    };
    init.site_search = function(){
    	$('#site-search').focus(function(){
    		$(this).val('');
    	});
    }
    init.verification_center = function(){
        $('.verification-center-right-btns, .verification-center-right-inner-btns').live('click',function(e){
            e.preventDefault();
            $this = $(this);
            //Not sure why this function is running after modal close
            if($this.hasClass('simplemodal-close')){ return; }
            if($this.hasClass('rpx')){ 
                //Popup window
                new_window = window.open($this.attr('href'),'Enter your login information.','height=600,width=650,scrollbars=1');
                if (new_window.focus) {
                	new_window.focus();
                	$.modal.close();
                }
            }
            $form = $this.parents('.verification-center-holder').find('form');
            //Are we on the confirm page?
           	var confirming =  ($form.find('[name=dovalidate]').length) ? true : false;
           	if(! confirming){
           		verify_type = $('.verification-center-nav').find('.active').attr('href').substring(1);
           		//Put this type in the form
				$form.find('#id_type').val(verify_type);
           	}
            resource = $form.attr('action');
            data = $form.serialize();
            $.post(resource,data,function(d){
                //May be able to use a $.modal function
                $('.simplemodal-data').html(d);
                if(confirming){
                    handle_item_action($item,'get_badge');
                }
            });
         });
         $('.verification-center-nav p a').live('click',function(e){
         	e.preventDefault();
            //TODO: Some css class manipulation bullshit 
            //since there 12 different css classes for these buttons
            $(this).addClass('active').parent().siblings().children().removeClass('active')
            //Show the help text on the right
            if(! $(this).hasClass('disabled')){
            	var to_show = $(this).attr('href').substring(1);
                //Show the verify button
            	$('.verification-center-right-btns').show();
                //Show the help text
            	$('#'+to_show).show().siblings('div').hide();
            }
         });
         $('.verification-center-holder .modal').live('click',function(e){
         	e.preventDefault();
         	$this = $(this)
            $.get($this.attr('href'),function(d){
            	$form = $this.parents('form');
            	$this.parents('.verification-center-content').data('form',$form).html(d);//Attach the form to the DOM, replace the content.
            });
         	
         });
    };
    init.verification_search = function(){
        $('.verify-expand').live('click',function(e){
            e.preventDefault();
            $('#verify_icons').toggle();
        });
        $('.verify-popup a').live('click',function(e){
            //Should use event delegation
            img_path = '/static/images/verify/icons/';
            e.preventDefault();
            provider = $(this).attr('href').substring(1);
            $('.verify-expand > img').attr('src',img_path+provider+'.png');
            $('#verify_icons').hide();
            $('#verify_provider').val(provider);
            $('#verify_username').focus();
        });
        $('#verify_username').focus(function(){
            $(this).val('');
        });
        $('.verify-popup-holder .popup-close').live('click',function(){
            $('#verify_icons').hide();
        });
        $('#verification_search_form').live('submit',function(e){
            e.preventDefault();
            var $field = $('#verify_username');
            if (!$field.val() || $field.val() == 'Enter Username'){
            	$field.focus();
            	return false;
            }
            $form = $field.parents('form');
            $.post($form.attr('action'),$form.serialize(),function(d){
                $.modal(d);
            });
        });
    };
    init.slide_menu = function(){
        $('.header-signin-register,.header-manage').click(function(e){
            e.preventDefault();
             $('.slide-menu').modal();
        });
    };
    init.password_fields = function(){
        $('.password').live('focusin',function(){ 
            if(! $(this).siblings('#password-strength').length){
                $(this).pstrength({
                    'displayMinChar': false,
                    'minChar': 6
                });
            }
        }); 
    };
    init.header_search = function(){
    	$('.header-search-btn').click(function(){
    		$(this).parents('form').submit();
    	});
    };
    init.expand_collapse = function(){
        $('.expand-collapse-btn').live('click',function(e){
            if( ! $(e.target).is('a')){
                $kids = $(this).parent().siblings('.box-body');
                if(! $kids.length){
                    $kids = $(this).parent().siblings('.box-body-item-group');
                }
                if($(this).hasClass('expand')){
                    $(this).removeClass('expand').addClass('collapse');
                }
                else{
                     $(this).removeClass('collapse').addClass('expand');
                }
                $kids.toggle(300);
             }
        });
    
    };
    init.forms = function(){
        //AJAX forms
        $forms = $('.ajax');
        
        ajax_form_response = function(d,status_text,xhr,$form){
			if(typeof(d.loc) != 'undefined'){
				//Redirect
				window.location.href = d.loc;
				//return false;
			}	
        };
		//GET the forms
		$forms.livequery(function(){
			//live('submit') followed by an
			// ajaxSubmit() was not working in safari or chrome.  This does.
			var form_options = {
				target: this,
				success: ajax_form_response
			};
			$(this).ajaxForm(form_options);
		
		});
        $forms.each(function(i,f){
            var url = $(f).attr('action');
            $.get(url,function(d){
                $(f).html(d);
            });
        });
        $.prettyLoader({
            loader: '/static/images/prettyLoader/ajax-loader.gif'
        });
    };
    init.acct_settings = function(){
        $('.account-settings-tabs a').click(function(e){
            e.preventDefault();
            tar = $(this).attr('href').substring(1);
            $(this).addClass('account-settings-tabs-selected')
            .parent().siblings().children('a').removeClass();
            $('#'+tar).show().siblings().hide();
        });
        $('#last4_form .save_button').live('click',function(e){
        	e.preventDefault();
        	$(this).parents('#last4_form').hide().siblings().show();
        });
    };
    init.avatar = function(){
    	$avatar = $('.box-body-basic-avatar');
    	$avatar.live('click',function(){
          	$menu = $('#edit_only_menu').clone();
			$(this).append($menu.show().html());
        });
        $avatar.live('hover',function(){
        	$(this).toggleClass('avatar-hover');
        });
        $avatar.live('mouseleave',function(){;
             $(this).parent().find('.backend-right-click-holder').remove();
        });
        $('#existing_avatars a').live('click',function(e){
        	e.preventDefault();
        	resource = $(this).attr('href');
        	$.post(resource,function(){
        	
        	});
        });
        $('#crop').livequery(function(){
        //Only livequery supports these event-less bindings
			$(this).Jcrop({
				onChange: update_coordinates,
				onSelect: update_coordinates,
				aspectRatio: 1
			});
		});
		show_preview = function(coords){
		//Disabled: behaving strangely right now
			var rx = 100 / coords.w;
			var ry = 100 / coords.h;
		
			$('#preview').css({
				width: Math.round(rx * 100) + 'px',
 				height: Math.round(ry * 70) + 'px',
				marginLeft: '-' + Math.round(rx * coords.x) + 'px',
				marginTop: '-' + Math.round(ry * coords.y) + 'px'
			});
		};
		update_coordinates = function(c){
			$('#x').val(c.x);
			$('#y').val(c.y);
			$('#x2').val(c.x2);
			$('#y2').val(c.y2);
			$('#w').val(c.w);
			$('#h').val(c.h);
		};
		get_avatar = function(sel){
			$(sel).get('/profile/get_avatar/',function(d){
				$(this).find('img').attr('src',d);
			});
		}
    
    };
    init.profile = function(){
        $('.box-body-item-ul').live('mouseenter',function(){
        	if(! ($(this).parents('.box-body-basic').length)){
				if($('#wrapper').data('public')){
					$(this).addClass('box-body-item-hover-ul');
				}
				else{
					$(this).addClass('box-body-item-hover-ul');
				 }
			 }
         });
         $('.box-body-item-ul').live('mouseleave',function(){
             $(this).removeClass('box-body-item-hover-ul');
             $(this).parent().find('.backend-right-click-holder').hide();
         });
        $('.box-body-item-hover-ul').live('click',function(e){
            var $menu = $(this).parent().find('.backend-right-click-holder');
            $tar = $(e.target);
            if($tar.is('a')) return;
            if($tar.hasClass('gray')){
                $tar = $(this);
            }
            if ($menu.length){
                $menu.remove();
                //$('.box-body-item-editmode-basic-ul').hide();
            }
            else if($tar.is('ul')){
            	$item = $tar;
                if($tar.children().find('.value').hasClass('gray')){
                    handle_item_action($tar,'edit');
                }
                else if($('#wrapper').data('public')){
                	 handle_item_action($tar,'verify');
                }
                else{
                    $menu = $('#manage_menu').clone();
                    if(! $tar.children('li').hasClass('gray')){
                    	$menu.find('#public_private').html('Private');
                    }
                    $menu.show();
                    $(this).append($menu.html());
               }
            }
        });
        $('.backend-right-click-holder a').live('click',function(e){
            e.preventDefault();
            e.stopPropagation(); 
            
            $menu = $(this).parents('.backend-right-click-holder').hide();
            $item = $menu.parents('.box-body-item-ul');
            var action = $(this).attr('href').substring(1);
            if(action == 'avatar'){
            	show_avatar_editor();
            }
            else if($item.length){
                handle_item_action($item,action);
            }
            else{//Add the very first item
                get_new_attribute_set($menu);
            }
            $menu.hide();
        });
        $('.cancel').live('click',function(){
            $(this).parent('ul').hide();
        });
        $('.save').live('click',function(e){
            $this = $(this);
            $item = $this.parents('.box-body-item-ul');
            handle_item_action($item,'save');
		});
        $('.content-left-tabs li').click(function(e){
            e.preventDefault();
            $(this).addClass('active').siblings().removeClass();
            action = $(this).children('a').attr('href').substring(1);
            data = {};
            resource = '/profile/';
            if (action == 'public'){
					data = {show_public: 1};
					$('#wrapper').data('public',true);
			}
			else{
					$('#wrapper').data('public',false);
			}
            $.get(resource,data,function(d){
                content = $(d).find('.content-left-profile').html();
                $('.content-left-profile').hide().html(content).fadeIn(200);
                if (action == 'public'){
					init.badges();
				}
            });
        });
         $box_titles = $('.box-title:not(.basic)');
         $box_titles.live('hover',function(){
         	if(! $('#wrapper').data('public')){
            	$(this).toggleClass('box-title-hover');
             }
         });
         $box_titles.live('mouseleave',function(){
			 $(this).parent().find('.backend-right-click-holder').remove();
         });
         $box_titles.live('click',function(e){
                $menu = $(this).parent().find('.backend-right-click-holder');
                if($menu.is(':visible')){
                    $menu.remove();
                }
                else if(! ($(e.target).is('.expand-collapse-btn') || $('#wrapper').data('public'))){
                    $menu = $('#manage_group_menu').clone();
                    $menu.show();
                    $(this).append($menu.html());
                }
         });
    };
    init.badges = function(){
          $badges = $('.small_badge');
          $badges.hover(function(){
          	 $this = $(this);
          	 setTimeout(function(){
          	 	//$item = $this.prev('ul');
                //badge_class = handle_item_action($item,'get_badge');
                $tooltip = $('#verify_tooltip').clone();
                $this.append($tooltip.show().html());
            }, 1200);
         },
         function(){
             $this.parent().find('.frontend-tooltip').remove();
         });
         $('.frontend-tooltip-viewmore-btn').live('click',function(e){
            e.preventDefault();
            $badge = $(this).parents('.small_badge');
            $item = $badge.prev('ul');
            handle_item_action($item,'show_verifications');
         });
        $('.frontend-verification-popup-holder .popup-close').live('click',function(){
            $(this).parent().remove();
        });
        $('.frontend-verification-popup-tabs li').live('click',function(e){
        	e.preventDefault();
        	$this = $(this);
        	$this.siblings().removeClass().addClass('frontend-verification-popup-li-disabled');
			var to_show = $this.children('a').attr('href').substring(1);
        	$this.removeClass().addClass('frontend-verification-popup-'+to_show)
        	.siblings().removeClass().addClass('frontend-verification-popup-li-disabled');			
			$('.val_detail_list').hide();
			$('#'+to_show).show();
        });
    
    
    
    };
    get_edit_box = function($inputs,verified){
             var edit_box = '<ul class="box-body-item-editmode-basic-ul">';
              $inputs.each(function(){
                   edit_box += '<li>';
                   edit_box += $(this).addClass('box-profile-input').parent().html();
                   edit_box += '</li>';
                });
                display = (verified) ? 'block' : 'none';
               edit_box += ' \
               <li class="save"><img width="50" height="20" class="box-body-item-editmode-save-cancel-btns" alt="" src="/static/images/btns/save.png"/></li>\
              <li class="cancel"><img width="50" height="20" class="box-body-item-editmode-save-cancel-btns" alt="" src="/static/images/btns/cancel.png"/></li>';
              edit_box += '<p class="profile-error-2" style="display:'+display+'">Editing This Field Will Reset its Verification Status</p>';
              
             edit_box += '</ul>';
             return edit_box;
    };
    clear_profile = function(){
        $('.box-body-item-editmode-basic-ul,.backend-right-click-holder').hide();
    };
    capitalize = function(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }
    get_new_attribute_set = function($menu){
        $group = $menu.parents('.profile-box-holder');
        model_name = $group.attr('id');
        resource = '/profile/form/'+model_name+'/';
        $.get(resource,function(f){
            $form = $(f);
            $blank_group = $('#blank_group').clone();
            items = '';
            $form.find('input,textarea,select').each(function(){
                name = $(this).attr('name');
                if (name){
                    items +=' \
                    <ul id="'+name+'" class="box-body-item-ul"> \
                        <li class="gray"><strong>'+capitalize(name)+':</strong>&#160;<span class="value gray">Edit '+capitalize(name)+'</span></li> \
                    </ul>';
                }
            });
           //find('.group_title').html(model_name).end()
             $blank_group.find('.box-body-item-group').append(items)
            .end().show();
            $group.find('.box-body').append($blank_group.html());
        });
    };
    show_avatar_editor = function() {
		 $.get("/profile/avatar/",function(data){
				$.modal(data);
		  });		
	}
    handle_item_action = function($item,action){
        //TODO: Make this more jQuery plugin like and chainable. e.g. $item.save().hide();
        var $item_group = $item.parents('.box-body-main-group');
        var model_name = $item.parents('.profile-box-holder').attr('id');
        var model_id = $item.siblings('span').attr('id');
        var field_name = $item.attr('id');
        var $form = $item.siblings('form');
        var verified = $item.next().is('.small_badge');
        var $inputs = [];
        switch(action){
                case 'edit':
                    if(! $form.length){
                        
                        if(model_name){
                            resource = '/profile/form/'+model_name+'/';
                            if(model_id){
                                resource += model_id+'/';
                            }
                            $.get(resource,function(f){
                                $form = $(f);
                                $item.siblings('form').remove();
                                $form.appendTo($item.parent()).hide();
                                if($item.parents('.profile-right').length){
                                    $inputs = $form.find('select,:text');
                                }
                                else{
                                    $inputs = $form.find('#id_'+field_name);
                                }
                                if($inputs.length){
                                    edit_box = get_edit_box($inputs,verified);
                                    $item.append(edit_box);
                                }
                            });
                        }
                    }
                    else {
                    //Use existing form
                        $input = $form.find('#id_'+field_name);
                       if($item.parents('.profile-right').length){
                            $inputs = $form.find('select,:text');
                        }
                        else{
                            $inputs = $form.find('#id_'+field_name);
                        }
                        if($inputs.length){
                            edit_box = get_edit_box($inputs,verified);
                            $item.append(edit_box);
                        }
                    }
                    return false;
                    break;
                case 'visibility':
                	if(! model_id){
						//Pull it from the form action
						res_arr = $form.attr('action').split('/');
						model_id = res_arr[4]; 
					}
                    resource = '/profile/visibility/'+model_name+'/'+model_id+'/'+field_name+'/';
                    $.post(resource,function(){
                    	$item.find('li').toggleClass('gray');
                    });
                    break;
                case 'delete':
                    confirmed = confirm('Are you sure you want to delete this?');
                    if (confirmed){
                        $.ajax({
                            url: '/profile/form/'+model_name+'/'+model_id+'/'+field_name+'/',
                            type: "DELETE",
                            success: function(){
                                $item.next('.small_badge').andSelf().remove();
                            }
                        });
                                
                    }
                    break;
                case 'verify':
                 	if(! model_id){
						//Pull it from the form action
						res_arr = $form.attr('action').split('/');
						model_id = res_arr[4]; 
					}
                 	resource = '/profile/verification/'+model_name+'/'+model_id+'/'+field_name+'/';
                 	username = $('#wrapper').data('username');
                 	if (username){
                 		resource += username+'/';
                 	}
                    $.get(resource,function(data){
                        $.modal(data);
                      });
                    break;
                case 'show_verifications':
                    resource = '/profile/verification/detail/'+model_name+'/'+model_id+'/'+field_name+'/';
                    $.get(resource,function(d){
                        $item.after(d);
                    });
                break;
                case 'save':
					right_side = ($item.parents('.profile-right').length) ? true : false;
					
					$updated = $this.parent().find('input,select,textarea');
					$updated.each(function(){
						new_value = $(this).val();
						$form.find('#'+$(this).attr('id')).val(new_value);
					});
                    
                    resource = $form.attr('action');
                    $form.append('<input type="hidden" name="field_name" value="'+field_name+'" />');
					$.post(resource,$form.serialize(),function(d){
						if(d.errors){
							var error_str = '';
							$.each(d.errors,function(k,v){
							   error_str += '<b>'+k+'</b>: '+v+'<br />';
							});
							$item.find('.profile-error-2').show().html(error_str);
						}
						else{
							$this.parent('ul').remove();
							$form = $(d);
							$item.siblings('form').remove();
							$form.appendTo($item.parent()).hide();
							if(right_side){
								//Change label and attribute.  No img yet.
								var $select = $form.find('select');
								var label = capitalize($select.val());
								var $input = $form.find(':text');
								$item.find('strong').html(label+': ');
								new_value = $input.val();
								$item.next('ul').remove();
							}
                            if(verified){
                                $item.next('.small_badge').remove();
                            }
							$item.removeClass('box-body-item-hover-ul')
							.find('.value')
							.html(new_value)
							.removeClass('gray');
						}
					 });
				break;
				case 'get_badge':
					resource = '/profile/badge/'+model_name+'/'+model_id+'/'+field_name+'/';
					$.get(resource,function(d){
						if(d){
                            if(verified){
							    $item.next().replaceWith('<div class="small_badge small_badge_'+d+'"> </div>');
                            }
                            else{
							    $item.after('<div class="small_badge small_badge_'+d+'"> </div>');
                           }
						}
					});
				
				break;
				  
            }
    };
    return {
        init:init
    };
}();
$(function(){//Call defaults on Document Ready
    IDN.init.modal();
    IDN.init.verification_search();
    IDN.init.header_search();
    IDN.init.slide_menu();
    IDN.init.site_search();
    IDN.init.password_fields();
    IDN.init.expand_collapse();
    IDN.init.forms();
    IDN.init.acct_settings();
});

