window.onload = externalLinks;
var total_lines = 0;
var tags_array = []; // outside of function to make it globally available
$(document).ready(function() {
	$('.tag').toggle(function() {
		this.css('color', 'black');
		$('.' + this.id).hide();
		changeTotal();
	}, function() {
		$(this).css('color', 'blue');
		$('.' + this.id).show();
		changeTotal();
	});

	tags_array.push(this.id);
//	reformatTags(tags_array);
	$("INPUT[type='checkbox']").attr('checked', '');
	changeTotal();
});

function changeRanking(id, num_stars, i) {
	$.ajax( {
		url : "/fillin/change_ranking?id=" + id + "&num_stars=" + num_stars,
		success : function(data) {
			refreshLine(id, i)
		}
	});
}

function loadData() {
	var last_id = $(".rowdiv:last").attr("id").replace('div_', '');
	$('.load_more').html('<img src="' + WEB_ROOT + '/img/loading.gif">');
	$.post("/line?action=get&last_id=" + last_id, function(data) {
		if (data != "") {
			$(".rowdiv:last").after(data);
			docReady();
		}
		$('div#data_loader').empty();
	});
//	setTimeout('reformatTags(tags_array);', 1000);
	setTimeout('changeTotal();', 1000);
	setTimeout('$(".load_more").html(loadingText());', 1000);
}

function loadingText() {
	var last_id = $('.rowdiv:last').attr('id').replace('div_', '');
	if(total_lines)
	if (total_lines - last_id < offset) {
		num = total_lines - last_id;
	} else {
		num = offset;
	}
	return num == 0 ? '' : 'Load ' + num + ' More...';
}

function refreshLine(id, i) {
	jQuery.ajax( {
		url : '/line/retrieve',
		type : "POST",
		data : 'id=' + id + '&i=' + i,
		success : function(data) {
			$('#line_div_' + id).html(data);
			expand_line(id);
			blockout();
		},
		error : function(request) {
			alert('error');
		}
	});
	blockout();
}

function checkIsEmpty(input) {
	if ((input.value.length == 0) || (input.value == null)) {
		input.focus();
		input.style.borderColor = "red";
		return false;
	}
	return true;
}

function checkForm(frm) {
	var return_val = true;
	return_val = checkIsEmpty(frm.value_input);
	// return_val = checkIsEmpty(frm.links_input);
	return_val = checkIsEmpty(frm.tags_input);
	if (frm.tags_input.value.indexOf(' ') != -1 && return_val) {
		alert('Only single word tags are allowed.');
		frm.tags_input.focus();
		frm.tags_input.style.borderColor = "red";
		return_val = false;
	}
	return return_val;
}

function externalLinks() {
	if (!document.getElementsByTagName)
		return;
	var anchors = document.getElementsByTagName("a");
	for ( var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href")
				&& anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
	}
}

function allhide() {
	for ( var i = 1; i < 11; i++) {
		var classs = '.' + i;
		$(classs).hide();
	}
}

function allshow() {
	for ( var i = 1; i < 11; i++) {
		var classs = '.' + i;
		$(classs).show();
	}
}

var size_of_lines = 0;
function changeTotal() {
	size_of_lines = $('.rowdiv:visible').length;
	$(".sizeofspan").html(size_of_lines);
}

function eip_line(id, row) {
	var eip_width = 90;
	$("#name_" + id).css('display', 'inline').css('background',
			'rgb(255, 255, 204)');
	$("#parsed_name_" + id).hide();
	$("#name_" + id).editInPlace( {
		url : "/fillin/change_name/id/" + id,
		saving_image : "loading.gif",
		default_text : "Put '**' around **underline** words",
		show_buttons : 1,
		size : eip_width,
		element_id : id,
		row : row,
		success : function(data) {
			// refresh line
		// console.debug(data);
		// alert('yeah!'); //updateTagsDropdown();
		}
	});
	$("#links_" + id).css('display', 'inline').css('background',
			'rgb(255, 255, 204)');
	$("#clickable_links_" + id).hide();
	$("#editable_links_" + id).show();
	$("#editable_links_" + id).editInPlace( {
		url : "/fillin/change_links/id/" + id,
		saving_image : "loading.gif",
		default_text : "Enter links seperated with commas",
		show_buttons : 1,
		element_id : id,
		row : row,
		field_type : "textarea",
		textarea_cols : "70",
		textarea_rows : "10",
		success : function(data) {
		}
	});
	$("#more_info_" + id).show();
	$("#more_info_" + id).editInPlace( {
		url : "/fillin/change_more_info/id/" + id,
		saving_image : "loading.gif",
		default_text : "Enter each point on a seperate line",
		show_buttons : 1,
		element_id : id,
		row : row,
		field_type : "textarea",
		textarea_cols : "70",
		textarea_rows : "10",
		size : 100,
		success : function(data) {
			// refresh line
		// console.debug(data);
		}
	});
	$("#tags_" + id).editInPlace( {
		url : "/fillin/change_tags/id/" + id,
		saving_image : "loading.gif",
		default_text : "Delimit tags with commas",
		show_buttons : 1,
		size : eip_width,
		element_id : id,
		row : row,
		success : function(data) {
			// refresh line
		// console.debug(data);
	}
	});
	$(".edit_stars_" + id).show();
	$(".stars_" + id).hide();
	expand_line(id);
}

function expand_line(id) {
	$("#more_stuff_" + id).slideDown();
	//	el = $("more_stuff_" + id); 
	//	console.log(el);
//el.slideDown();
	$("#more_" + id).html('&ndash;');
}

function contract_line(id) {
	$("#more_stuff_" + id).slideUp();
	$("#more_" + id).html('+');
}

//function reformatTags(tags_array) {
//	for (i = 0; i < tags_array.length; i++) {
//		$('#tag_' + tags_array[i]).show();
//		if ($('.rowdiv').hasClass(tags_array[i])) {
//			size = Math.ceil($('.' + tags_array[i]).length / 5);
//			if (size > 10)
//				size = 10;
//			$('#tag_' + tags_array[i]).attr('class', 'tag_size_' + size);
//		} else {
//			$('#tag_' + tags_array[i]).hide();
//		}
//		if ($('#tag_' + tags_array[i]).css('color') === 'black') {
//			$('.' + tags_array[i]).hide();
//			$('#tag_' + tags_array[i]).css('color', 'blue');
//		}
//	}
//}


show = function(event, selector, msg) {
	$('.' + event.target.id).hide();
	$('#' + event.target.id + '-' + selector).show();
	if (msg != null) {
		$('#' + event.target.id + '-' + selector).html(msg);
	}
}

setFocus = function(event) {
	if (event.target.id
			&& (event.target.type == 'text'
					|| event.target.type == 'textarea' || event.target.type == 'password')) {
		$('#' + event.target.id).css('background-color', '#FAFAFA').css(
				'border', '1px solid #AAA')
		$('#' + event.target.id).css('-moz-border-radius-topright', '0')
				.css('-moz-border-radius-bottomright', '0');
		if ($('.' + event.target.id + ':visible').length == 0)
			show(event, 'info');
	}
}

addEventListener("click", function(event) {
	setFocus(event);
}, false);

addEventListener("change", function(event) {
	switch (event.target.id) {
	case 'UserFullname':
		if (event.target.value.length > 0) {
			show(event, 'good');
		} else {
			show(event, 'error');
		}
		break;
	case 'UserEmail':
		if (event.target.value.length > 0
				&& /\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3}/
						.test(event.target.value)) {
			$
					.ajax( {
						url : "/users/check_email/" + event.target.value,
						success : function(data) {
							if (data == true) {
								show(event, 'good');
							} else {
								show(event, 'error',
										'email has already been taken');
							}
						},
						error : function() {
							show(event, 'error', 'server response error');
						}
					});
		} else {
			show(event, 'error', 'should look like an email address');
		}
		break;
	}
}, false);

$('#UserPassword').focus(function(event) {
	setFocus(event);
});

$('#UserEmail').focus(function(event) {
	setFocus(event);
});

$(window).bind("focus", function(event) {
	setFocus(event);
}, false);

addEventListener("blur", function(event) {
	$('#' + event.target.id).css('background-color', '#FFF').css('border',
			'1px solid #DDD')
}, false);

addEventListener("keyup", function(event) {
	switch (event.target.id) {
	case 'UserUsername':
		if (event.target.value.length > 0) {
			show(event, 'check');
			$.ajax( {
				url : "/users/check_name/" + event.target.value,
				success : function(data) {
					if (data == true) {
						if (event.target.value.length > 0) {
							show(event, 'good');
						} else {
							show(event, 'info');
						}
					} else {
						show(event, 'error',
								'username has already been taken');
					}
				},
				error : function() {
					show(event, 'error', 'server response error');
				}
			});
		} else {
			setFocus(event);
			show(event, 'info');
		}
		break;
	case 'UserPassword':
		if (/^.*(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])(?=.*[\W]).*$/
				.test(event.target.value)) {
			show(event, 'verystrong');
		} else {
			if (/^.*(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[\d\W]).*$/
					.test(event.target.value)) {
				show(event, 'strong');
			} else {
				if (/^.*(?=.{6,})(?=.*[a-z|A-Z])(?=.*[\d\W]).*$/
						.test(event.target.value)) {
					show(event, 'good');
				} else {
					if (/^.*(?=.{6,}).*$/.test(event.target.value)) {
						show(event, 'weak');
					} else {
						show(event, 'short');
					}
				}
			}
		}
		break;
	}
}, false);

function addLine(el) {
	$('#new_line_div').show();
	$('#content').hide();
}

$(document).ready(function() {


	$('#add_line').click(function(){
		addLine(this);
	});
	
	docReady();

});

function blockout() {
	$(".blocked_out").hover(function() {
		$(this).toggleClass("blocked_out_over");
	});

	$(".blocked_out").click(function() {
		$(this).toggleClass("blocked_out_clicked");
	});
}

function docReady() {

    blockout();
    
//	$(".bigcheck").click(function() {
//		$("#line_div_" + $(this).attr('id').replace('checkbox_', '')).hide();
//	});

	$(".expand_contract").toggle(function() {
		expand_line($(this).attr('id').replace('more_', ''));
	}, function() {
		contract_line($(this).attr('id').replace('more_', ''));
	});
	if (total_lines > size_of_lines) {
		show_more = '<a style="margin-left:20px;" class="load_more" href="javascript:void(0);" onclick="loadData();">' + loadingText() + '</a>';
	} else {
		show_more = '';
	}
	total_text = '<span>Total<span class="delimiter">:</span>'
	//		+ delimiter
			+ '</span><span style="color:black;"><span class="sizeofspan" style="font-weight:bold; font-size:110%; color:black;"></span><span style="font-weight:normal;"> of '
			+ total_lines + ' lines</span>' + show_more + '</span>';
	$('.render_total').html(total_text);
	changeTotal();
	
    
}


