var article_comment_counts = new Array();
var is_logged_in = null;

var $ = $nymag_j; // resolves namespace conflict
$.ajaxSetup({ timeout: 10000 });

function open_win(url) {
	var qtwin = window.open(url,"login_win",'toolbar=,location=0, directories=0,status=0,menubar=0,scrollbars=1,resizable=1, width=770,height=700');
	qtwin.focus();
}

function open_win_small(url) {
	var qtwin = window.open(url,"login_win",'toolbar=,location=0, directories=0,status=0,menubar=0,scrollbars=1,resizable=1, width=770,height=350');
	qtwin.focus();
}

function update_form_login_state() {
	login_state_changed = is_logged_in == null ? true : (is_logged_in != isLoggedInUser());
	is_logged_in = isLoggedInUser();

	$("#comments_logged_in_user").html(unescape(getUserName()));

	if (login_state_changed) {
		show_error("");
		$("div.submit").show();
		$("#login_form").hide("slow");

		if (is_logged_in) {
			$("#comments_logged_out_warning").hide();
			$("#comments_logged_in_status").show();
			$nymag_j("#logged_out_bar").hide();
			$nymag_j("#logged_in_bar").show();
			$nymag_j("#user_name").html(unescape(getUserName()));
		} else {
			$("#comments_logged_in_status").hide();
			$("#comments_logged_out_warning").show();
			$nymag_j("#logged_out_bar").show();
			$nymag_j("#logged_in_bar").hide();
		}
	}
}

function nym_login_failed(error_message) {
	show_error("<li>" + unescape(error_message) + "</li>");
}

function nym_logged_in() {
	$("#comment-form").submit();
}

function is_blog(url_or_path) {
	if (url_or_path.match(/^http/)) {
		return url_or_path.match(/^http:\/\/[^\/]+\/daily/) ? true : false;
	} else {
		return url_or_path.match(/^\/daily/) ? true : false;
	}
}

function get_article_id_by_url(url) {

    var orig_url = url;

    if (!url) {
            url = window.location.pathname;
    }
    if (url.match(/^http/)) {
        url = url.replace(/^http:\/\/[^\/]+/, "");
    }

    hostname = window.location.hostname;

    if (hostname.match("nymetro")) {
        url = "/daily/food" + url;
    }

    if (is_blog(url) || (orig_url && orig_url.match('grubstreet'))) { //always consider grubstreet domain to be a blog

        return url.replace(/^\//, "").replace(/\//g, "-");
    } else {
        return url.replace(/\/[^\/]*$/, "").replace(/^\//, "").replace(/\//g, "-");
    }
}

function get_article_title() {

    var title = $("meta[name='Headline']").attr("content");

    if (!title) {
        title = $("title").html().replace(/\-.*$/, "");
    }

    return title;
}

// args: { container_id, article_url }
function get_comment_count(args) {
	var container_id = args ? args.container_id : null;
	var article_id = get_article_id_by_url(args && args.article_url ? args.article_url : null);

	if (!isNaN(article_comment_counts[article_id])) {
		return;
	}

	article_comment_counts[article_id] = 0;

	$.ajax({
		type: "GET",
		url: "/comments/stories/" + article_id + "/comments/count",
		success: function(data) {
			show_comment_count(container_id, article_id, data);
		},
		error: function (error, msg) {
			if (error.status == 404) {
				article_comment_counts[article_id] = 0;
				show_comment_count(container_id, article_id, "0");
			}
		}
	});
}

// multi-comment count version, receives an array of the standard
// get_comment_count args
function get_comment_counts(args) {

        var articles = {};
        var article_ids = [];

        for (var i = 0; i < args.length; i++ ){
            var arg = args[i];
            var article_id = get_article_id_by_url(arg && arg.article_url ? arg.article_url : null);

            if (article_id && isNaN(article_comment_counts[article_id])){
                articles[article_id] = {container_id:  arg ? arg.container_id : null};
                article_ids.push(article_id)
            
            }
        }
            article_comment_counts[article_id] = 0;

            $.ajax({
                    type: "GET",
                    url: "/comments/get_all_comments",
                    data: {ids: article_ids},
		    type: 'POST',
                    dataType: "json",
                    success: function(data) {
                            var comments = data.comments;
                            for(var i=0; i < comments.length; i++){
                                var container_id = articles[comments[i].story_id].container_id;
                                show_comment_count(container_id, comments[i].story_id, comments[i].count);
                            }
                    },
                    error: function (error, msg) {
                            if (error.status == 404) {
                                    var container_id = articles[comments[i].story_id].container_id;
                                    article_comment_counts[article_id] = 0;
                                    show_comment_count(container_id, comments[i].story_id, "0");
                            }
                    }
            });
}
function show_comment_count(container_id, article_id, data) {
	if (data && data.match(/\d/)) {
		var container_selector = container_id ? "#" + container_id + " ": "";
		article_comment_counts[article_id] = data.replace(/\D/, "");

		$(container_selector + ".article_comment_count").each(function() {
			this.innerHTML = article_comment_counts[article_id];
		});

		if (article_comment_counts[article_id] == 0) {
			$(container_selector + ".no_comments").each(function() {
				this.style.display = "";
			});
		} else if (article_comment_counts[article_id] == 1) {
			$(container_selector + ".one_comment").each(function() {
				this.style.display = "";
			});
		} else {
			$(container_selector + ".multiple_comments").each(function() {
				this.style.display = "";
			});
		}
	}
}

function show_error(message) {
	$(".miniwarning").html(message ? '<ul class="warning">' + message + '</ul>' : '');

	if (isLoggedInUser()) {
		$("#login_form").hide();
		$("div.submit").show();
	}
}


// The minibrowser object
var minibrowserobj = {

	// Member Variables
	
	minibrowserbox: '#minibrowserbox',
	minibrowser_selector: '.minibrowser',
	article_id: '',
	onreload_enabled: false,

	// Member Functions
	
	//	init args: minibrowserbox, minibrowser_selector, path_prefix, path_postfix, href, onload, onreload
	init: function(args) {
		this.set_minibrowserbox(args.minibrowserbox);
		this.set_minibrowser_selector(args.minibrowser_selector);
		this.set_article_id();
		this.path_prefix = args.path_prefix;
		this.onload = args.onload;
		this.onreload = args.onreload;
		this.get(args.href ? args.href : (
			(args.path_prefix ? args.path_prefix : "") +
			"/stories/" + this.article_id + "/comments/" +
			(args.path_postfix ? args.path_postfix : "viewpost")
		));
		
		return this;
	},
	
	//set_minibrowserbox: set the id of the div which is this particular
	//minibrowser, or just go with the default.
	
	set_minibrowserbox: function(id)
	{
		if (id) {
			this.minibrowserbox = id;
		}
		
		return this;
	},
	
	//set_minibrowser_selector: this is the class name that you use to find
	//that a given anchor or a form should be handled by the minibrowser
	
	set_minibrowser_selector: function (selector) {
	
		if(selector)
		{
			this.minibrowser_selector = selector;
		}
		
		return this;
	},

	set_article_id: function() {
		this.article_id = get_article_id_by_url();
	},
		
	// binds: given an identifier, create the binds
	
	binds: function (identifier) {

		// invoke each of the identifiers.
		this.anchor_binds(identifier);
		this.post_binds(identifier);
	},
	
	//anchor_binds: do binds for anchor tags against an identifier
	
	anchor_binds: function (identifier) {
	
		minibrowser = this;
	
		$(identifier)
			.find( 'a' + minibrowser.minibrowser_selector )
			.each( function () { 
				if (minibrowser.path_prefix != null) {
					this.href = minibrowser.rewrite_url(this.href);
				}

				$(this).bind( 'click', function () {
					minibrowser.get(this.href);
					return false;
				});
			});
	},

	//post_binds: bind form posts against an identifier
	
	post_binds: function (identifier) {
	
		minibrowser = this;
		$(identifier)
			.find( 'form' + minibrowser.minibrowser_selector )
			.each( function () {
			
				form = this;
			
				if (minibrowser.path_prefix != null) {
					$(this).attr("action", minibrowser.rewrite_url($(this).attr("action")));
				}

				$(form)
					.find(':submit,input:image')
					.bind( 'click', function () {
					
						//alert('got click' + form.name);
						form.clk = this;
					})
					.end()
					.bind( 'submit', function () {
						minibrowser.post(this);
						return false;
					});
			});
	},

	// onload gets executed after minibrowser makes an http request (get or post) and 
	// updates its contents
	callback_onload: function() {
		if (typeof this.onload == "function") {
			this.onload();
		}

		if (this.onreload_enabled) {
			this.callback_onreload();
		}

		this.onreload_enabled = true;
	},

	// onreload callback is the same as onload but doesn't get executed at first time, when
	// minibrowser makes its initial request
	callback_onreload: function() {
		if (typeof this.onreload == "function") {
			this.onreload();
		}
	},

	// rewrite_url: makes relative urls and adds path prefix for proxy-passing
	rewrite_url: function (url) {
		return url.replace(/https?:\/\/[^\/]+/, this.path_prefix);
	},
	
	// getformdata: serialize a form.  Watch out, this doesn't do file uploads
	// as far as I know.
	
	getformdata: function (form) {
		if (!form) return {};

		data = {};
		data[form.clk.name] = form.clk.value;

		data.href = window.location.href;
		data.title = get_article_title();

		for (var i=0; i<form.elements.length; i++) {
			var e = form.elements[i];
			if(e.name) {
				if(e.type =='checkbox' || e.type=='radio')
				{
					if(e.checked)
					{
						data[e.name] = e.value;
					}
				}
				else
				{
					data[e.name] = e.value;
				}
			}
		}

		return data;
	},
	
	// get: Perform a Get for a given href and insert the results 
	// into the minibrowser div.
	
	get: function(href) {
	
		minibrowser = this;
		if (!href) return; 
		$.ajax({
			type:'GET',
			url: href,
			success: function (response) {
				if (response.length) {
					$(minibrowser.minibrowserbox)[0].innerHTML = response;
					minibrowser.binds(minibrowser.minibrowserbox);
					minibrowser.callback_onload();
				}
			},
			error: function (error, msg) {
				/*
				//If it is a 404 style error, we need to get the title and the
				//urn and redo this as a post.  We should probably break this
				//out into a seperate area.
				if(error.status == 404)
				{
					$.ajax({
						type: 'PUT',
						url: href,
						data: { title: get_article_title(), href: window.location.href },
						success: function (response) {
							$(minibrowser.minibrowserbox).html(response)
							minibrowser.binds(minibrowser.minibrowserbox);
							minibrowser.callback_onload();
						}
					});
				}
				*/
			},
			complete: function( httpob, text) {
				scrollto = httpob.getResponseHeader('X-NYMAGCOMMENTING-SORTING');
				if(scrollto)
				{
					document.location.hash=scrollto;
				}
			}
		});
	},
	
	// post: gather form stuff and post.
	
	post: function(form) {
		minibrowser = this;
		if (!form) return;

		$.ajax({
			type:'POST',
			url: form.action,
			data: minibrowser.getformdata(form),
			success: function (response) {
				$(minibrowser.minibrowserbox)[0].innerHTML = response;
				minibrowser.binds(minibrowser.minibrowserbox);
				minibrowser.callback_onload();
			},
			error: function (error, msg, e) {
				errormsg = error.responseText;
				show_error(errormsg);
			},
			complete: function( httpob, text) {
				scrollto = httpob.getResponseHeader('X-NYMAGCOMMENTING-SORTING');
				
				if(scrollto)
				{
					document.location.hash=scrollto;
				}
			}
		});
	}
	
	// END.  Remember the last item shouldn't have a trailing ','!
};


// Create the plugin!

jQuery.fn.minibrowser = function(settings) {
	minibrowserbox = this;

	settings = jQuery.extend({  
		minibrowser_selector: '.minibrowser',
		path_prefix: null,
		href: null,
		onload: null,
		onreload: null
	}, settings);

	return minibrowserbox.each(function() { 
		minibrowser = minibrowserobj.init({
			minibrowserbox: minibrowserbox, 
			minibrowser_selector: settings.minibrowser_selector,
			path_prefix: settings.path_prefix,
			href: settings.href,
			onload: settings.onload,
			onreload: settings.onreload
		});		
	});
}

