// Additions to core javascript objects
String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, '')};

// Functions common to the entire application
var Common = {};

Common.KEY_UP = 38;
Common.KEY_DOWN = 40;
Common.ENTER = 13;
Common.MESSAGE_DIALOG_WIDTH = 600;

Common.main = function() {
	
    jQuery.ajaxSetup({'beforeSend': function(xhr) { xhr.setRequestHeader("Accept","application/json"); } });
    
    /****************************************************
     * Protect against CSRF attacks and still do the ajax
     ****************************************************/
    $(document).ajaxSend(function(event, xhr, settings) {
        if (typeof(AUTH_TOKEN) == "undefined") return;
        // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
        settings.data = settings.data || "";
        settings.data += (settings.data ? "&" : "?") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
    });
    
    Common.hide_flashes();

    Page.init();
};

$(document).ready(Common.main);

/**
 * Wires the standard image form
 * params hidden_input_selector: the element in the real form that the image is associated with
 */
Common.wire_image_form = function(hidden_input_selector) {
	$('.image_form').ajaxForm(function(data) { 
		if(data) {
			var result = JSON.parse(data);
			$("#avatar").attr('src', result.avatar_url);
			$(hidden_input_selector).val(result.avatar_id);
		} else {
			alert("could not upload image");
		}
    });
    
    $("#submit_image").click(function() {
        $('.image_form').submit();
    });
};

/**
 * Initalizes a common validated form
 */
Common.Validation = {
    opts: {
	    meta: 'validate', 
		invalidHandler: function(form, validator) {
	      	var errors = validator.numberOfInvalids();
	      	if (errors) {
				$("#form_errors").html("<div>Something is not right.  " + 
						"Please check errors and submit again.</div>").fadeIn();
				$(".settings_links").addClass('settings_links_with_error');
			} else {
				$("#form_errors").fadeOut();
        		$(".settings_links").removeClass('settings_links_with_error');
			}
	        
	    },
	    highlight: function(element, errorClass) {
            $(element).addClass("field_with_errors");
            $(element.form).find("label[for=" + element.id + "]")
                    .addClass("field_with_errors");
        },
        unhighlight: function(element, errorClass) {
            $(element).removeClass("field_with_errors");
            $(element.form).find("label[for=" + element.id + "]")
                    .removeClass("field_with_errors");
        }
	},
	
	click: function() {
	    Common.Forms.HintedFields.clear();
	    var parentForm = $(this).parents("form");
	    if(parentForm.valid()) {
	        if(!$(parentForm).hasClass("disabled")) {
        	    $(parentForm).find(".loading").css('display', 'block');
        	    $(parentForm).addClass("disabled");
                parentForm.submit();   
            } else {
                Common.Forms.reset_handlers();
            }
	    } else {
            Common.Forms.reset_handlers();
        }
	}
};

Common.wire_validation = function() {
    // $('.validated_form').validate(Common.Validation.opts);
    // $(".validated_form .submit").click(Common.Validation.click);
};

Common.Forms = {
    wire_sectional: function() {
        
        var activate_section = function(section_name) {
            var form_element = $('.form_sections li.' + section_name);
            if(!$(form_element).hasClass('active')) {
                $('.form_sections li').removeClass('active');
                $(form_element).addClass('active');
                $('.form_section').css('display', 'none');
                $('.forms .' + section_name).css('display', 'block');
                $.scrollTo($('div.forms'));
                Common.Status.hide_success($('form'));
                Common.Status.hide_error($('form'));
            }
            
        };
        
        $('.form_sections li').click(function() {
            var section = this.className;
            activate_section(section);
        });
        
        $('a.form_link').click(function() {
            var data = $(this).metadata();
            if(data && data.section) {
                activate_section(data.section);
            }
        });
    },
    
    wire_normal_form: function() {

        $('form').validate(Common.Validation.opts);
        $('a.submit').click(function() {
            Common.Forms.HintedFields.clear();
            $(this).parents("form").submit();
        });
        
        $('input').keypress(function(evt) {
            setTimeout( function() {
                var keyCode = evt.keyCode;
            	if( keyCode == Common.ENTER ) {
                    Common.Forms.HintedFields.clear();
                    $(evt.target).parents("form").submit();
            	}
            }, 5);
        });
    },
    
    wire_twitter_action: function() {
        // $('input#text').focus(function() {$('.twitter_button').attr('disabled', true); });
        // $('input#password').focus(function() {$('.twitter_button').attr('disabled', true); });
        // $('input#text').blur(function() {$('.twitter_button').removeAttr('disabled'); });
        // $('input#password').blur(function() {$('.twitter_button').removeAttr('disabled'); });
        // 
        // $('.twitter_button').unbind('click');
        $('.twitter_button').submit(function() {
            $(this).parents('form')[0].submit();
        });
        
        
    },
    
    reset_handlers: function() {
        Common.Forms.HintedFields.reset();
        $("form").removeClass('disabled');
    }
};

Common.Forms.HintedFields = {
    init: function() {
        $(".hinted").each(function() {
            Common.Forms.HintedFields.addHint(this);
        }).focus(function() {
            Common.Forms.HintedFields.clearHint(this);
        }).blur(function() {
            Common.Forms.HintedFields.addHint(this);
        });
    },
    
    addHint: function(elem) {
        var data = $(elem).metadata();
        var val = $(elem).val();
        
        if(0 == val.length || val == data.hint) {
            $(elem).addClass('hint_shown');
            $(elem).val(data.hint);
        }
    },
    
    clearHint: function(elem) {
        var data = $(elem).metadata();
        var val = $(elem).val();
        
        if(0 == val.length || val == data.hint) {
            $(elem).removeClass('hint_shown');
            $(elem).val("");
        }
    }, 
    
    clear: function() {
        $(".hinted").each(function() {
           Common.Forms.HintedFields.clearHint(this); 
        });
    },
    
    reset: function() {
        $(".hinted").each(function() {
           Common.Forms.HintedFields.addHint(this); 
        });
    }
    
};

/**
 * Initializes any tags
 */
Common.Tagging = {
    wire:  function() {
        $(".taggable").autocomplete("/tags", {
    	    max: 5
    	});
    }
};

Common.Status = {
    hide_success: function(form) {
        $(form).find(".save_success").fadeOut('slow');
    },
    
    show_success: function(form) {
        $(form).find(".loading").css('display', 'none');
        $(form).find(".save_success").css('display', 'block');
        $(form).find(".form_errors").css('display', 'none');
        
        var timed_out_hide = function() {
            setTimeout(function() {
                Common.Status.hide_success(form);
            }, 5000);
        }
        $(form).find("input").change(timed_out_hide);
        $(form).find("select").change(timed_out_hide);
        $(form).find("textarea").change(timed_out_hide);
    },
    
    show_error: function(response, form) {
        $(form).find(".loading").css('display', 'none');
        $(form).find(".save_error").css('display', "block");
        
        if(response.error && response.error.length > 0) {
            $(form).find(".form_errors").text(response.error).fadeIn();
        }
        setTimeout(function() {
            $(form).find(".save_error").fadeOut('slow');
        }, 5000);
    },
    
    hide_error: function(form) {
        $(form).find(".form_errors").css("display", "none");
        $(form).find(".save_error").css("display", "none");
    }
};

Common.flash_error_timeout = null;

Common.flash_error = function(message) {
    $('#flash_error').text(message);
    $('#flash_error').slideDown();
    
    if(Common.flash_error_timeout) {
        clearTimeout(Common.flash_error_timeout);
    }
    
    Common.flash_error_timeout = setTimeout(function() {
        $("#flash_error").slideUp()
    }, 5000);
};

Common.flash_notice_timeout = null;

Common.flash_notice = function(message) {
    $('#flash_notice').text(message);
    $('#flash_notice').slideDown();
    
    if(Common.flash_notice_timeout) {
        clearTimeout(Common.flash_notice_timeout);
    }
    
    Common.flash_notice_timeout = setTimeout(function() {
        $("#flash_notice").slideUp()
    }, 5000);
};


Common.hide_flashes = function() {
    setTimeout(function() {
        $("#flash_notice").fadeOut('normal');
    }, 5000);
};

Common.Ajax = {
    success_cb: function(response, statusText) {
        Common.Forms.reset_handlers();
        if(response.success == true) {
            
            if(response.redirect_to) {
                window.location.href = response.redirect_to;
            }
            
            Common.Status.show_success($('.' + response.section));
            
	        if(response.avatar) {
	            $('#avatar').attr('src', response.avatar);
	        }
	        
        } else if(response.success == false) {
            Common.Status.show_error(response, $('.' + response.section));
        }
    }, 
    
    error_cb: function(response, statusText) {
        Common.Forms.reset_handlers();
        var error_response = {success: false, error: "Unable to save. Maybe your image is too large?"};
        Common.Status.show_error(error_response, $('form'));
    },
    
    ajax_success_cb: function(response, statusText) {
        Common.Forms.reset_handlers();
        if(response.success == true) {
            Common.Status.show_success($('.' + response.section));
        } else if(response.success == false) {
            Common.Status.show_error(response, $('.' + response.section));
        }
    },
    
    wire_iframe_form: function(selector, options) {
        $(selector).validate(Common.Validation.opts);
        $(selector + " .submit").click(Common.Validation.click);
        
        if(options) {
            $(selector).ajaxForm(options);
        } else {
        	$(selector).ajaxForm(Common.Ajax.iframe_opts);
        }
    },
    
    wire_form: function(selector, options) {
        $(selector).validate(Common.Validation.opts);
        $(selector + " .submit").click(Common.Validation.click);
        
        if(options) {
            $(selector).ajaxForm(options);
        } else {
        	$(selector).ajaxForm(Common.Ajax.ajax_opts);
        }
    },
    
    load: function(selector, href) {
        $.ajax({
            beforeSend: function(xhr) { xhr.setRequestHeader("Accept","application/xml"); },
            url: href,
            dataType: 'text', 
            success: function(response, statusText) {
                $(selector).replaceWith(response);
            }
        })
    },
    
    wire_pagination: function(selector) {
        $(selector + ' .pagination a').live('click', function() {
            var href = $(this).attr('href');
            $.ajax({
                beforeSend: function(xhr) { xhr.setRequestHeader("Accept","application/xml"); },
                url: href,
                dataType: 'text', 
                success: function(response, statusText) {
                    $(selector).replaceWith(response);
                }
            })
            return false;
        });
    },

    before_xml_send: function(xhr) { xhr.setRequestHeader("Accept","application/xml"); }
};


Common.Ajax.iframe_opts = {
    iframe: true,
    dataType: 'json',
    success: Common.Ajax.success_cb,
    error: Common.Ajax.error_cb
}

Common.Ajax.ajax_opts = {
    iframe: false,
    dataType: 'json',
    success: Common.Ajax.ajax_success_cb
}

var Page = {};
Page.init = function() { /* do nothing, override if you want something to happen */ };


/****************************************************
 * Journalist Javascripts and such
 ****************************************************/
 
var Login = {
    init: function() {
        Common.Forms.wire_normal_form();
    }
}


var Journalists = {
    
    init_edit: function(num_links) {
        Common.Forms.wire_sectional();
    	Common.Tagging.wire();
    	Common.Forms.HintedFields.init();
    	
        // Repeated because jquery pukes if you do it with a common selector
        Common.Ajax.wire_iframe_form('#journalist_basics_form');
        Common.Ajax.wire_iframe_form('#journalist_settings_form');
        
        var journalist_bio_elem = $("#journalist_bio");
        
        if(journalist_bio_elem.length > 0) {
        	journalist_bio_elem.limittext({
        	    limit: journalist_bio_elem.metadata().validate.maxlength,
        	    associated: "#journalist_bio_maxinput"
        	});
    	}
    },

    init_dashboard: function(num_outlets) {
        $('.pitchfilter_button_expand').click(function() {
            var clicked_button = this;
            $(clicked_button).parents('.pitch_summary').fadeOut('normal', function() {
                $(clicked_button).parents('.pitch_details').children('.full_pitch').fadeIn("slow");
                $(clicked_button).parents('.message').find('.rating_box').fadeIn("slow");
            });
        
            var unread_elem = $(clicked_button).parents('.pitch_details').find('.unread');
            Conversations.mark_as_read(unread_elem);
            unread_elem.next(".replied").css('display', 'block');
        });
    
        $('.pitchfilter_button_collapse').click(function() {
            var clicked_button = this;
            $(clicked_button).parents('.message').find('.rating_box').fadeOut('fast');
            $(clicked_button).parents('.full_pitch').fadeOut('normal', function() {
                $(clicked_button).parents('.pitch_details').children('.pitch_summary').fadeIn('slow');
            });
        });
    
        Conversations.init_new_message_dialog();
        $('.reply_button').click(function(){
            var data = $(this).metadata();
            $("#message_subject").html(data.subject);
            $("#message_conversation_id").val(data.conversation_id);
            $("#message_recipient_id").val(data.recipient_id);
            $("#new_message_dialog").dialog('open');
        });
    
        $('.pitchfilter_button_on_target').click(function() {
            Journalists.rate_pitch(this, "on_target", "On Target");
        });
    
        $('.pitchfilter_button_off_target').click(function() {
            Journalists.rate_pitch(this, "off_target", "Off Target");
        });
    },

    rate_pitch: function(element, rating, rating_string) {
        var data = $(element).metadata();
        $.ajax({
            type: "put",
            url: "/pitches/" + data.id,
            dataType: "json",
            data: {'rating': rating},
            success: function(data) {
                Common.flash_notice("Your pitch rating has been recorded");
                var rating_box = $(element).parents('.rating_box');
                $(rating_box).find('.rates').css("display", "none");
                var rated_box = $(rating_box).find('.rating_result');
                $(rated_box).fadeIn();
                $(rated_box).find('h3 span').addClass('on_target').text(rating_string);
            },
            error: function(data) {
                Common.flash_error("Unable to save your pitch rating");
            }
        
        });
    },
    
    init_show: function() {
        
    }
};

/****************************************************
 * Publicist Javascripts and such
 ****************************************************/
var Publicists = {
    init_edit: function(num_links) {
        Common.Forms.wire_sectional();
    	Common.Tagging.wire();
    	Common.Forms.HintedFields.init();
    	
        // Repeated because jquery pukes if you do it with a common selector
        Common.Ajax.wire_iframe_form('#publicist_basics_form');
        Common.Ajax.wire_iframe_form('#publicist_settings_form');
        
    },
    
    init_show: function() {
        $(".button_delete").click(function() {
            var parent = $(this).parents('.person_list_item'); 
            var data = $(this).metadata();
            var name = $(parent).find(".expert_name").val();
            if(confirm("Are you sure you want to delete " + name + " profile?")) {
        	    var url = "/experts/" + data.id;
        	    $.ajax({
        	        dataType: 'json',
        	        success: function(data, status) {
                        window.location.reload();
        	        },
        	        error: function(data, status) {
        	            Common.Status.show_error(data, $('.person_links'));
        	        },
        	        type: "DELETE",
        	        url: url
        	    });       
            }
        });
        
    },
    
    init_dashboard: function() {
        $('.pitchfilter_button_expand').click(function() {
            var clicked_button = this;
            $(clicked_button).parents('.pitch_summary').fadeOut('normal', function() {
                $(clicked_button).parents('.pitch_details').children('.full_pitch').fadeIn("slow");
            });
            
            var unread_elem = $(clicked_button).parents('.pitch_details').find('.unread');
            
            if(unread_elem && unread_elem.length > 0) {
                unread_elem.css('display', 'none');
                var data = unread_elem.metadata();
                $.get("/query_alerts/read/" + data.id);
                unread_elem.next(".replied").css('display', 'block');
            }
        });
    
        $('.pitchfilter_button_collapse').click(function() {
            var clicked_button = this;
            $(clicked_button).parents('.full_pitch').fadeOut('normal', function() {
                $(clicked_button).parents('.pitch_details').children('.pitch_summary').fadeIn('slow');
            });
        });
        
        Pitches.init_new_dialog();
        $('.new_pitch').click(function() {
            var data = $(this).metadata();
            $('#conversation_query_id').val(data.id);
            $('#new_pitch_dialog').dialog('open');
        });
        
        $('.delete_notification').click(function( ) {
            var data = $(this).metadata();
            
            var button_elem = this;
            $.ajax({
                url: "/query_alerts/" + data.id,
                type: "DELETE",
                dataType: 'json',
                success: function(json) {
                    $(button_elem).parents(".query_message_container").fadeOut('slow');
                },
                error: function(json) {
                    Common.flash_error("Unable to delete highlighted query");
                }
            })
        });
    }
}
/****************************************************
 * Outlets
 ****************************************************/
var Outlets = {
    init_edit: function() {
        Common.Forms.wire_sectional();
    	Common.Tagging.wire();
    	Common.Forms.HintedFields.init();
    	
    	var outlets_ajax_opts = $.extend({}, Common.Ajax.iframe_opts, {
    	    success: function(response, statusText) {
                Common.Forms.reset_handlers();
                if(response.success == true) {
                    Common.Status.show_success($('.' + response.section));
                    $('.outlet_id').val(response.id);
                } else if(response.success == false) {
                    Common.Status.show_error(response, $('.' + response.section));
                }
    	    }
        });
        
        // Repeated because jquery pukes if you do it with a common selector
        Common.Ajax.wire_iframe_form('#outlet_basics_form', outlets_ajax_opts);
        Common.Ajax.wire_iframe_form('#outlet_details_form', outlets_ajax_opts);
        Common.Ajax.wire_iframe_form('#outlet_distribution_form', outlets_ajax_opts);
        
        var outlet_description_elem = $("#outlet_description");
        
        if(outlet_description_elem.length > 0) {
        	outlet_description_elem.limittext({
        	    limit: outlet_description_elem.metadata().validate.maxlength,
        	    associated: "#outlet_description_maxinput"
        	});
    	}
        
    },
    
    init_index: function() {
        Pitches.init_new_dialog();
        $('.new_pitch').click(function() {
            var data = $(this).metadata();
            $('#conversation_journalist_id').val(data.journalist_id);
            $('#new_pitch_dialog').dialog('open');
        });
    }
};

/****************************************************
 * Sources 
 ****************************************************/
var Sources = {};
Sources.init_index = function() {
    Queries.init_new_dialog();
    
    $('.call_to_action a').click( function() {
        $('#new_query_dialog').dialog('open');
    });
    
    Conversations.init_new_message_dialog();
    $('.new_message').click(function() {
        var data = $(this).metadata();
        $('#message_recipient_id').val(data.publicist_id);
        $('#expert_id').val(data.expert_id);
        $('#new_message_dialog').dialog('open');
    });
    
};

/****************************************************
 * Experts 
 ****************************************************/
Experts = {
    init_edit: function() {
        
        Common.Forms.wire_sectional();
        Common.Tagging.wire();
    	Common.Forms.HintedFields.init();
    	
    	var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
    	
        // Repeated because jquery pukes if you do it with a common selector
        Common.Ajax.wire_iframe_form('#expert_basics_form');
        Common.Ajax.wire_iframe_form('#expert_background_form');
        Common.Ajax.wire_iframe_form('#expert_social_form');
        Common.Ajax.wire_iframe_form('#expert_settings_form');
        
        var links_ajax_opts = $.extend({}, Common.Ajax.iframe_opts, {
        	    success: function(response, statusText) {
        	        if(response.success == true) {
        	            $("#link").val('');
                        Common.Forms.reset_handlers();
        	            Common.Status.show_success($('.links'));
                        $('#expert_links').load("/experts/" + response.new_link.expert_id + "/expert_links/index?edit=true");
        	        } else if(response.success == false) {
                        Common.Forms.reset_handlers();
        	            Common.Status.show_error(response, $('.links'));
        	        }
        	    }
        });
        Common.Ajax.wire_iframe_form('#expert_links_form', links_ajax_opts);

    	$("#expert_links_form .button_delete").live('click', function() {
    	    if(confirm("Deleting a link cannot be undone.  Continue?")) {
    	        var data = $(this).metadata();
        	    var url = "/experts/" + data.expert_id + "/expert_links/" + data.id;
        	    $.ajax({
        	        dataType: 'html',
        	        success: function(data, status) {
                        $('#expert_links').html(data);
        	        },
        	        error: function(data, status) {
        	            Common.Status.show_error(response, $('.links'));
        	        },
        	        type: "DELETE",
        	        url: url
        	    });
        	}
    	});
    	
    	$("#expert_links_form .button_save").live('click', function() {
    	    var parents = $(this).parents('.expert_link');
    	    var title_box = $(parents).find('input[name="title"]');
    	    var data = $(title_box).metadata();
    	    var value = $(title_box).val();
    	    
    	    var url = "/experts/" + data.expert_id + "/expert_links/" + data.id;
    	    $(parents).find(".loading").css("display", "block");
    	    $.ajax({
    	        dataType: 'json',
    	        success: function(data, status) {
    	            $(parents).find('h3 a').text(value);
                    $(parents).find('h3').css('display', 'block');
                    $(parents).find('.edit_link').css('display', 'none');
                    $(parents).find('.button_edit').text("Edit");
            	    $(parents).find(".loading").css("display", "none");
    	        },
    	        error: function(data, status) {
    	            Common.Status.show_error(response, $('.links'));
    	        },    
    	        type: "PUT",
    	        url: url,
    	        data: {'title': value}
    	    })
    	});
    	
    	$("#expert_links_form .button_edit").live('click', function() {
    	    var text = $(this).text();
    	    if(text == "Edit") {
    	        var parents = $(this).parents('.expert_link');
        	    $(parents).find('h3').css('display', 'none');
                $(parents).find('.edit_link').css('display', 'block');
                $(this).text("Cancel");
            } else {
                var parents = $(this).parents('.expert_link');
        	    $(parents).find('h3').css('display', 'block');
                $(parents).find('.edit_link').css('display', 'none');
                $(this).text("Edit");
            }
        });
        
        var expert_bio_elem = $("#expert_bio");
        
        if(expert_bio_elem.length > 0) {
        	expert_bio_elem.limittext({
        	    limit: expert_bio_elem.metadata().validate.maxlength,
        	    associated: "#expert_bio_maxinput"
        	});
    	}
    	
    },
    
    update_expert_ids: function(json_response) {
        $('.expert_id').val(json_response.expert_id);
    },
    
    wire_publication_link_actions: function(num_links, new_link_url) {
        Experts.num_publications = num_links;

    	$('#create_new_publication').click(function() {
    		Experts.num_publications++;
    		var params = {
    		    'index': Experts.num_publications,
    		    'link_type': $("#new_publication_link_type").val(),
    		    'url': $('#new_publication_link_url').val()
    		}
    		$.get(new_link_url, params, function(data) {
    		    $('tr.new_publication_link:first').before(data);
    		    $('#new_publication_link_type').val("");
    		    $('#new_publication_link_url').val("");
    		});
    	});
    }
    
};
/****************************************************
 * Queries 
 ****************************************************/
var Queries = {
    init_new_dialog: function(id) {
        if(id == null) {
            id = "#new_query_dialog";
        }
    
        Common.Tagging.wire();
    
        $(id).dialog({
            autoOpen: false,
            modal: true,
            width: Common.MESSAGE_DIALOG_WIDTH,
            buttons: { 
                "Ok": function() {
                    $(this).find("form").submit();
                },
                "Cancel": function() {
                    $(this).dialog("close")
                }
            }
        });
    },

    init_index: function() {
        Queries.init_new_dialog();
        $('.new_query').click(function() {
            $('#new_query_dialog').dialog('open');
        });
        
        $('.pitchfilter_button_expand').click(function() {
            var clicked_button = this;
            $(clicked_button).parents('.query_summary').fadeOut('normal', function() {
                $(clicked_button).parents('.query_details').children('.description').fadeIn("slow");
            });
        });
    
        $('.pitchfilter_button_collapse').click(function() {
            var clicked_button = this;
            $(clicked_button).parents('.description').fadeOut('normal', function() {
                $(clicked_button).parents('.query_details').children('.query_summary').fadeIn('slow');
            });
        });
    },
    
    init_new: function() {
        $('#expires_at').datepicker({
            altField: '#expires_at',
            altFormat: "mm/dd/yy",
            dateFormat: 'mm/dd/yy',
            minDate: new Date(),
            closeText: "X"
        });
        $('.date_picker_selector').click(function() {
            $('#expires_at').datepicker('show');
        });
        
        Common.wire_validation();
        Common.Tagging.wire();
    },
    
    deactivate_query: function(id) {
        window.location.href = "/queries/destroy/" + id;
    }
}

/****************************************************
 * Pitches
 ****************************************************/
var Pitches = {
    init_new_dialog: function(id) {
        if(id == null) {
            id = "#new_pitch_dialog";
        }
            
            
        $(id).dialog({
            autoOpen: false,
            modal: true,
            width: Common.MESSAGE_DIALOG_WIDTH,
            buttons: { 
                "Ok": function() {
                    $(this).find("form").submit();
                },
                "Cancel": function() {
                    $(this).dialog("close")
                }
            }
        })
    }
    
};
/****************************************************
 * Conversations
 ****************************************************/
var Conversations = {
    
    init_new: function() {
        var conversation_message_body = $("#conversation_message_body");
        
        if(conversation_message_body.length > 0) {
        	conversation_message_body.limittext({
        	    limit: conversation_message_body.metadata().validate.maxlength,
        	    associated: "#message_maxinput"
        	});
    	}
    	
    	$("#expert_select_dialog").dialog({
    	    modal: true,
    	    width: 410,
    	    resizable: false,
    	    title: "Select an Expert",
    	    autoOpen: false
    	});
    	
    	$('#select_expert_button').click(function() {
    	    $('#expert_select_dialog').dialog('open');
    	});
    	
    	$('.button_use').click(function() {
    	    var expert_id = $(this).metadata().id;
    	    $('#conversation_expert_id').val(expert_id);
    	    var mini_profile = $(this).parents('.mini_profile').clone();
    	    $("#from_mini_profile").html(mini_profile);
    	    $('#expert_select_dialog').dialog('close');
    	    $(mini_profile).find(".button_use").text("Change").click(function() {
    	        $('#expert_select_dialog').dialog('open');
    	    });
    	});
    	
    	var form_submit_options = $.extend({}, Common.Ajax.ajax_opts, {
        	    success: Conversations.ajax_new_conversation_cb
        });
        
    	Common.Ajax.wire_form('#conversation_form', form_submit_options);
    },
    
    init_index: function() {
        
        Common.Forms.HintedFields.init();
        
        var index_form_opts = $.extend({}, Common.Ajax.ajax_opts, {
                beforeSend: Common.Ajax.before_xml_send,
                dataType: 'text',
        	    success: Conversations.ajax_new_message_cb,
        	    error: Conversations.ajax_new_message_error_cb
        });
        

        $('.conversation .conversation_area').live('click', function() {
            var url = "/conversations/" + $(this).parent().metadata().id + ".xml";
            $(this).parent().removeClass('unread');
            var callback = function() {
                Common.Ajax.wire_form('#conversation_form', index_form_opts);
                $("#conversation_display").css('display','block');
                $('#conversation_list').css('display', 'none');
            };
            
            $("#conversation_display").load(url, callback);
        });
        
        var load_conversation_list = function(jquery_elem) {
            var ajax_url = "/conversations?type=";
            if($(jquery_elem).hasClass('story')) {
                var data = $(jquery_elem).metadata();
                ajax_url += "story&story_id=" + data.id;
            } else if($(jquery_elem).hasClass('expert')) {
                var data = $(jquery_elem).metadata();
                ajax_url += "expert&expert_id=" + data.id;
            } else {
                ajax_url += $(jquery_elem).attr('class');
            }
            
            Common.Ajax.load("#conversation_list", ajax_url);
            $('.form_sections li').removeClass("active");
            $(jquery_elem).addClass('active');
            $("#conversation_display").css('display','none');
        };
        
        $('.back_to_inbox').live("click", function() {
            if( 0 == $(".form_sections li.active").length) {
                load_conversation_list($('.form_sections li:first'));
            } else {
                $('#conversation_list').css('display', 'block');
                $("#conversation_display").css('display','none');
            }
        });
        
        var conversation_elements = $(".form_sections li").not('.new_query').not('.sent_queries');
        
        $(conversation_elements).click(function() {
            if(!$(this).hasClass('active')) {
                load_conversation_list(this);
            } else {
                $('#conversation_list').css('display', 'block');
                $("#conversation_display").css('display','none');
            }
        });
        Common.Ajax.wire_pagination("#conversation_list");
        
        $('.new_query').click(function() {
            var url = "/queries/new";
            var callback = function() {
                // TODO: Wire the form for a new query
                $("#conversation_display").css('display','block');
                $('#conversation_list').css('display', 'none');
            };
            
            $('.form_sections li').removeClass("active");
            $(this).addClass('active');
            $("#conversation_display").load(url, callback);
        });
        
        
        
        $('#moveto_stories').nmcDropDown();
        $('#stories_filter').nmcDropDown();
        $('#experts_filter').nmcDropDown();
        
        // Disable the top level li
        $('#stories_filter li').click(function() {
            $('#stories_filter .button_big_combo span').text($(this).text());
            return false;
        });
        
        $('#experts_filter li').click(function() {
            $('#experts_filter .button_big_combo span').text($(this).text());
            return false;
        });
        
        $("#new_story_dialog").dialog({
    	    modal: true,
    	    width: 410,
    	    resizable: false,
    	    title: "New Story",
    	    autoOpen: false
    	});
    	
    	var form_submit_options = $.extend({}, Common.Ajax.ajax_opts, {
        	    success: Conversations.ajax_new_story_cb
        });
        
    	Common.Ajax.wire_form('#new_story_form', form_submit_options);
    	
    	$('#new_story_dialog .button_delete').click(function() {
    	    $('#new_story_dialog').dialog('close');
    	});
    	
    	$('#new_story').live('click', function() {
            $('#new_story_dialog').dialog('open');
        });
        
        var get_convo_ids = function() {
            var conversation_ids = {};
            var idx = 0;
            
            $('#conversation_list .convo_check').each(function() {
                if($(this).is(':checked')) {
                    var data = $(this).metadata();
                    var obj = {};
                    conversation_ids['conversation_id[' + idx + ']'] = data.id;
                    idx++;
                }
            });
            
            return conversation_ids;
        };
        
        $("#moveto_stories .story").live("click", function() {
            var story_id = $(this).metadata().id;
            
            var conversation_ids = get_convo_ids();
            $.post("/stories/" + story_id + "/move",conversation_ids, function(data, textStatus, xmlHttpRequest) {
                if(data.success == true) {
                    load_conversation_list();
                    Common.flash_notice("Successfully Moved Conversations");
                } else {
                    Common.flash_error("Unable to Move Conversations");
                }
            }, 'json');
        });
        
        $(".delete").live('click', function() {
            var conversation_ids = get_convo_ids();
            $.post("/conversations/destroy",conversation_ids, function(data, textStatus, xmlHttpRequest) {
                load_conversation_list();
                Common.flash_notice("Successfully Deleted Conversations");
            }, 'json');
        });
        
        
        $(".undelete").live('click', function() {
            var conversation_ids = get_convo_ids();
            $.post("/conversations/undelete",conversation_ids, function(data, textStatus, xmlHttpRequest) {
                load_conversation_list();
                Common.flash_notice("Successfully Undeleted Conversations");
            }, 'json');
        });
    },
    
    mark_as_read: function(unread_elem) {
        if(unread_elem && unread_elem.length > 0) {
            unread_elem.css('display', 'none');

            var data = unread_elem.metadata();
            $.get("/conversations/read/" + data.id);
            
            var new_message_count = parseInt($("#new_message_count").text());
            if(new_message_count > 1) {
                $("#new_message_count").text(new_message_count - 1);
            } else if(new_message_count <= 1) {
                $("#new_message_count").css("display", "none");
            }
        }
    },

    delete_conversation: function(id) {
        window.location.href = "/conversations/destroy/" + id;
    },
    
    undelete: function(id) {
        window.location.href = "/conversations/undelete/" + id;
    }
};

Conversations.ajax_new_conversation_cb = function(response, statusText) {
    Common.Forms.reset_handlers();
    if(response.success == true) {
        Common.Status.show_success($('.message_edit_box'));
        if(response.redirect_url) {
            window.location.href = response.redirect_url;
        }
    } else if(response.success == false) {
        Common.Status.show_error(response, $('.message_edit_box'));
    }
};

Conversations.ajax_new_story_cb = function(response, statusText) {
    Common.Forms.reset_handlers();
    if(response.success == true) {
        $(".stories_list .story").remove();
        
        var stories = response.stories;
        var stories_ls = [];
        for(var i = 0; i < stories.length; i++ ) {
            stories_ls.push("<li class='story {id: ");
            stories_ls.push(stories[i].story.id);
            stories_ls.push("}'>");
            stories_ls.push(stories[i].story.name);
            stories_ls.push("</li>");
        }
        var stories_html = stories_ls.join("");
        $(".stories_list").prepend(stories_html);
        $("#new_story_dialog").dialog("close");
    } else if(response.success == false) {
        Common.Status.show_error(response, $('#new_story_form'));
    }
}

Conversations.ajax_new_message_cb = function(response, statusText) {
    $('.message_view').replaceWith(response);
    
    var index_form_opts = $.extend({}, Common.Ajax.ajax_opts, {
            beforeSend: Common.Ajax.before_xml_send,
            dataType: 'text',
    	    success: Conversations.ajax_new_message_cb,
    	    error: Conversations.ajax_new_message_error_cb
    });
    Common.Ajax.wire_form('#conversation_form', index_form_opts);
};

Conversations.ajax_new_message_error_cb = function(xmlhttp, statusText, errorThrown) {
    var response = {
        error: "Unable to save message"
    }
    
    Common.Status.show_error(response, $('.message_edit_box'));
}

/*******************************************************************
 * Stories
 *******************************************************************/

Stories = {
    init_edit: function() {
        $("#deadtime").timepickr({
            convention: 12
        });
        
        $('#deaddate').datepicker({});
        
        Common.Forms.wire_sectional();
    	Common.Tagging.wire();
    	Common.Forms.HintedFields.init();
    	
        var stories_ajax_opts = $.extend({}, Common.Ajax.ajax_opts, {
            success: function(response, statusText) {
                    Common.Forms.reset_handlers();
                    if(response.success == true) {
                        Common.Status.show_success($('.' + response.section));
                        var story = response.stories[0].story;
                        window.location.href = '/journalists/' + story.journalist_id + '/stories'; 
                    } else if(response.success == false) {
                        Common.Status.show_error(response, $('.basics'));
                    }
            }
        });
        
        // Repeated because jquery pukes if you do it with a common selector
        Common.Ajax.wire_form('#new_story_form', stories_ajax_opts);
        
        var story_description_elem = $("#story_description");
        
        if(story_description_elem.length > 0) {
        	story_description_elem.limittext({
        	    limit: story_description_elem.metadata().validate.maxlength,
        	    associated: "#story_description_maxinput"
        	});
    	}
    },
        
    init_index: function() {
    	$(".button_delete").click(function() {
            var parent = $(this).parents('.person_list_item'); 
            var data = $(this).metadata();
            var name = $(parent).find("h3").text().replace(/^\W+/,'').replace(/\W+$/,'');
            if(confirm("Are you sure you want to delete " + name + "?")) {
        	    var url = "/journalists/" + data.journalist_id + "/stories/" + data.id;
        	    $.ajax({
        	        dataType: 'json',
        	        success: function(data, status) {
                        window.location.reload();
        	        },
        	        error: function(data, status) {
        	            Common.Status.show_error(data, $('.person_links'));
        	        },
        	        type: "DELETE",
        	        url: url
        	    });       
            }
        });
        
    }
};
/*******************************************************************
 * Profiles
 *******************************************************************/
 
Profiles = {
    init_journalist: function() {
        Pitches.init_new_dialog();
        $('.new_pitch').click(function() {
            var data = $(this).metadata();
            $('#conversation_journalist_id').val(data.journalist_id);
            $('#new_pitch_dialog').dialog('open');
        });
    },
    
    init_expert: function() {
    	Common.Forms.HintedFields.init();
        var message_elem = $('#contact_form_message_message');
        message_elem.limittext({
            limit: message_elem.metadata().validate.maxlength,
            associated: "#contact_form_message_message_maxinput"
        });
    	
        $("#contact_dialog").dialog({
            modal: true,
            width: 410,
            resizable: false,
            title: "Request an Interview",
            autoOpen: false
        });
       
        $('.contact_button').click(function() {
        	$('#contact_dialog').dialog('open');
        });
        
        $('.button_delete').click(function() {
            $('#contact_dialog').dialog('close');
        });
        
        var opts = $.extend({}, Common.Ajax.ajax_opts, {
            success: function(response, statusText) {
                Common.Forms.reset_handlers();
                if(response.success == true) {
                    $("#contact_dialog").dialog('close');
                    Common.flash_notice("Message Sent!");
                } else if(response.success == false) {
                    Common.Status.show_error(response, $('.form'));
                }
            }
        });
        Common.Ajax.wire_form('#expert_contact_form', opts);
    }
}

/******************************************************
 * Public Pages
 ******************************************************/

Public = {
    init: function() {
        $("form.validated").validate({
            meta: "validate",
            errorContainer: "#formErrors",
            errorLabelContainer: "#errorLabelContainer",
            submitHandler: function(form) {
                $(".ajax_loader").css("display", "block");

    			jQuery(form).ajaxSubmit({
    				success: function() {
                        $(".ajax_loader").css("display", "none");
    				    $("#formContainer").css("display", "none");
    				    $("#thanksContainer").fadeIn();
    				},
    				error: function() {
                        $(".ajax_loader").css("display", "none");
    				    $("#serverError").fadeIn();
    				}
    			});
    		}
        });

        $("#tweets").load("/public/tweets");
        $("#blog").load("/public/blog");
    },
    
    init_index: function() {
        Common.Forms.HintedFields.init();
        Common.Forms.wire_normal_form();
        $("#recent_experts .experts").load("/experts/recent");
        
        $("#blog").load("/public/blog");
    }
}

/******************************************************
 * Dashboard Pages
 ******************************************************/
Dashboard = {
    init_publicist: function() {
        Common.Forms.HintedFields.init();
        Common.Forms.wire_normal_form();
        Users.init_resend_dialog();
    }
}

/*******************************************************
 * User Controls
 *******************************************************/
Users = {
    init_resend_dialog: function() {
        $("#activation_resend_link").click(function() {
            $.ajax({
                type: "get",
                url: "/users/resend_confirm",
                dataType: "json",
                data: {},
                success: function(data) {
                    if(data.success == true) {
                        $("#activation_required_box").text("Confirmation code sent! Please check your inbox.");
                    } else {
                        $("#activation_required_box").text("Unable to send confirmation, please try again later");
                    }
                },
                error: function(data) {
                    $("#activation_required_box").text("Unable to send confirmation, please try again later");
                }

            }); 
        });
    }
}

