var last_options, lastType, changeToType, site = 0, sortTypes = new Array(), lastSort, sortkeyset, changeable, change_sz, change_in_progress;
var monitor = ["Monitor", "Track", "Follow", "Analyze"];
var archive = ["archive", "save", "record", "preserve", "keep", "database"];
var difference = ["difference", "change", "alteration", "edit"]
var action = ["an actionable edge", "competitive advantage", "immediate feedback"];

function swap_random_word(){
	if (change_in_progress == 1) {
		return;
	}
	change_in_progress = 1;
	var index = Math.ceil(Math.random()*change_sz) - 1;
	var specific = changeable.eq(index);
	swap_word(specific);
}

function swap_all_words(){
	changeable.each(function(){swap_word($(this));});
}

function swap_word(word){
	var arr;
	if (jQuery.inArray(word.text(), monitor) >= 0) {
		arr = monitor;
	} else if (jQuery.inArray(word.text(), archive) >= 0) {
		arr = archive;
	} else if (jQuery.inArray(word.text(), difference) >= 0) {
		arr = difference;
	} else if (jQuery.inArray(word.text(), action) >= 0) {
		arr = action;
	}
	if (arr !== undefined) {
		var value = arr[Math.ceil(Math.random()*arr.length) - 1];
		if (value !== word.text()) {
			word.addClass("deletable").fadeOut(
				function(){
					$(this).removeClass("deletable");
					$(this).addClass("addable");
					$(this).text(value);
					$(this).fadeIn(
						function(){
							$(this).removeClass("addable");
							change_in_progress = 0;
						}
					)
				}
			);
		} else {
			change_in_progress = 0;
		}
	} else {
		change_in_progress = 0;
	}
}

$(document).ready(function () {
	changeable = $("span.changeable");
	change_sz = changeable.length;
	setInterval('swap_all_words()', 15000);

	$("#atsign").replaceWith("&#0064;");

	var account_table = $("#account_table");
	$("td.stripeme", account_table).mouseenter(function(){$(this).css("background-color", "#f6f6f6");});
	$("td.stripeme", account_table).mouseleave(function(){$(this).css("background-color", "");});

	var stripe_table = $("table.stripe_table");
	$("tbody.stripable > tr:not(.unstripe, .expanded)", stripe_table).live("mouseenter", function(){$(this).css("background-color", "#f6f6f6");});
	$("tbody.stripable > tr", stripe_table).mouseleave(function(){$(this).css("background-color", "");});

	var top_navigation = $("#top_navigation");
	$("div.menuitem", top_navigation).mouseleave(function(){$(this).css("background-color", "");});

	$("input.submit, #top_navigation div.menuitem").mouseenter(function(){$(this).css("background-color", "#fdee04");});
	$("input.submit").mouseleave(function(){$(this).css("background-color", "#f6f8c2");});
	$("#pageTableBody > tr").mouseleave(function() {if (last_options) {last_options.hide();}});

	$("td.jump", "tbody.jumpable").click(function() {
		window.location = $(this).children("a").attr("href");
		return false;
	});

	$("span.unbubble").click(function(event) {
		event.stopPropagation();
	});

	var growing = $("tbody.growing");
	$("select.growable", growing).mouseenter(function() {
		var the_select = $(this);
		if (the_select.hasClass("growable")) {
			the_select.removeClass("growable");
			var id_data = the_select.parents("tr.version").attr("id").split("_");
			var cid = id_data[1];
			var custom_options;
			var offset = 0;
			$.each(versions_available, function(key, value){
				if (offset == 2) {
					custom_options += "<option>" + value + "</option>";
				} else if (offset > 0) {
					offset++;
				} else if (value == cid) {
					offset = 1;
				}
			});
			the_select.html(the_select.html() + custom_options);
		}
	});

	$("select", growing).change(function() {
		var the_select = $(this);
		var compare_to = the_select.children(":selected").val();
		var id_data = the_select.parents("tr.version").attr("id").split("_");
		var cid = id_data[1];
		$("#compare_link_" + cid).attr("href", './' + cid + ':' + compare_to + '/');		
	});

	$("#pageTableBody > tr", "#pageTable").mouseenter(function() {
		if (last_options) {
			last_options.hide();
		}
		var $this = $(this);
		var id_data = $this.attr("id").split("_");
		var cid = id_data[1];
		var status = id_data[2];
		var cap = id_data[3];
		last_options = $this.children(".version_options");
		if (last_options.is(':visible')) {
			var buttons = '';
			if (status != 'D')
				buttons = buttonView(cid);
			if (cap)
				buttons = buttonCap(cid, cap) + buttons;
			if (status == "N") {
				buttons += buttonLock(cid) + buttonDel(cid);
			} else if (status == "P") {
				buttons += buttonUnlock(cid);
			}
			last_options.html(buttons);
		} else {
			last_options.show();
		}
	});

	var newtype = $("#newtype");
	$("a.newType", newtype).click(function() {
		$("a.newType", newtype).css("background-color", "");
		$(this).css("background-color", "#fcfcd0");
	});

	//change public view comparison type highlighting (see above)
	if (changeToType) {
		if (changeToType == "beside") {
			changeToType = "side-by-side";
		} else if (changeToType == "edit") {
			changeToType = "single page";
		} else if (changeToType == "only") {
			changeToType = "changes only";
		}
		$("a.newType", newtype).css("background-color", "");
		$("a.newType:contains('" + changeToType + "')", newtype).css("background-color", "#fcfcd0");
	}
});

function buttonView(cid) {return "<a href='" + cid + "/' target='_blank'><img src='/images/view.png' alt='view' title='view this version'></a>";}
function buttonDel(cid) {return "<a href='" + cid + "/delete'><img src='/images/delete.png' alt='delete' title='delete this version'></a>";}
function buttonLock(cid) {return "<a href='" + cid + "/lock'><img src='/images/locked.png' alt='protect' title='PROTECT version from deletions'></a>";}
function buttonUnlock(cid) {return "<a href='" + cid + "/unlock'><img src='/images/unlocked.png' alt='unprotect' title='UNPROTECT version from deletions'></a>";}
function buttonCap(cid, cap) {return "<a href='http://versionista.com.s3-website-us-east-1.amazonaws.com/va/" + cap + ".png' target='_blank'><img src='/images/shot.png' alt='screenshot' title='view screenshot of version'></a>";}

function sortme(key, direction, noAjax, noSort) {
	if (lastSort) {$(lastSort).removeClass('headerSortasc headerSortdesc');}
	var keyid = "#kw"+key;
	if (direction) {sortTypes[key] = direction;} else {sortTypes[key] = sortTypes[key] == "asc" ? "desc" : "asc";}
	$(keyid).addClass("headerSort"+sortTypes[key]);
	if (noSort) {} else {
		$("table.sorttable>tbody>tr").tsort(".kw" + key, {order: sortTypes[key]});
	}
	if (noAjax) {} else {
		if (lastSort !== keyid) {
			simpleAJAX(sortkeyset,"sortColumn",key);
		}
		simpleAJAX(sortkeyset,"sortDirection",sortTypes[key]);
	}
	lastSort = keyid;
}

function sortme_submit(key) {
	window.location = './?col=' + key + '&dir=' + (sortTypes[key] == "asc" ? "desc" : "asc") + '&page=' + pageno;
}

function setall(a) {
	var z = document.forms.boxy.elements;
	for (var i=0; i<z.length; i++) {
		if (typeof(z[i].checked) == 'boolean') z[i].checked = a;
	}
	return void(0);
}

function arrow(who, siteNum) {
	var who = $(who);
	var wrapper = who.parents("tr.collapse_wrap");
	var target = wrapper.find("div.collapse_target");
	var trigger = who.children("img");
	if (target.hasClass("h")) {
		target.slideDown().toggleClass("h");
		trigger.attr("src","/images/down.png");
		if ('all' in collapseSites) {
			collapseSites = {};
			$.each(siteIDs, function(){ collapseSites[this] = 1 });
		}
		delete collapseSites[siteNum];
		wrapper.css("background-color", "");
	} else {
		target.slideUp().toggleClass("h");
		trigger.attr("src","/images/right.png");
		collapseSites[siteNum] = 1;
	}
	wrapper.toggleClass("expanded");
	sendCollapseSites();
	return void(0);
}

function arrowall(state) {
	var body_collapsable = $("tbody.collapsable");
	if (state == 0) {
		$("div.collapse_target", body_collapsable).slideUp().addClass("h");
		$("tr.collapse_wrap", body_collapsable).removeClass("expanded");
		$("img.collapse_trigger").attr("src","/images/right.png");
		collapseSites.all = 1;
	} else {
		$("div.collapse_target", body_collapsable).slideDown().removeClass("h");
		$("tr.collapse_wrap", body_collapsable).addClass("expanded");
		$("img.collapse_trigger").attr("src","/images/down.png");
		collapseSites = {};
	}
	sendCollapseSites();
}

function sendCollapseSites() {
	var a = [];
	$.each(collapseSites, function(k){ a.push(k) });
	simpleAJAX("dashboard","collapseSites",a.join(","));
}

function togglePageTitle(showPageTitles) {
	$("a.ptype", "tbody.page_list").toggleClass("h");
	$("a.title_toggle", "tr.homeHead").toggleClass("h");
	simpleAJAX("dashboard","showPageTitles",showPageTitles);
}

function expandable() {
	var sitepage_options = $("#sitepage_options");
	$('div.expandable', sitepage_options).is(':visible') ? $("div.expandable", sitepage_options).slideUp("slow") : $("div.expandable", sitepage_options).slideDown("slow");
	return void(0);
}

function confirm_delete(host) {
	if (confirm('Warning!  This will delete ' + host + ' entirely from our database.  This means all the URLs and cached versions associated with the site will be erased permanently, whether protected or not.  This will free up the space for your use with other sites.')) {
		window.location = './delete';
	}
}

function simpleAJAX(displayLocation, variableKey, variableValue) {
	var url = "http://" + window.location.hostname + "/ajax?type=" + displayLocation + "&variableKey=" + variableKey + "&variableValue=" + variableValue;
	url = url + "&uncacheme=" + Date();
	$.get(url, function(data){});
}

function select_populate(slct, opts, dflt) {
	var optstr = '<option></option>';
	if (opts) {
		for (var i=0; i<opts.length; i++) {
			optstr += '<option' + (opts[i][1] ? ' value="' + opts[i][1] + '"' : '') + ((opts[i][1]||opts[i][0])==dflt ? ' selected="selected"' : '') + '>' + opts[i][0] + '</option>\n';
		}
	}
	$(slct).html(optstr);
}

function chk_ntfy() {
	var opts = $.map($('.opts:checked').get(), function(x){return x.id}).join(',');
	var freq = $('#hfreq').is(':checked') ? 8 : $('#lfreq').is(':checked') ? 168 : 24;
	$.get('http://' + window.location.hostname + "/ajax?type=sitebox&site="+site+"&opts="+opts+"&freq="+freq, function(data){ });
}

function insta_ntfy() {
	$.get('http://' + window.location.hostname + "/ajax?type=pagebox&site="+site+"&page="+page+"&insta="+($('#insta').is(':checked')?1:0), function(data){ });
}


