var fadeA;
var fadeB;
var fadePos;

function fadeHelper() {
	fadePos++;
	if(fadePos < 10) {
		setOpacity(fadeA, (10-fadePos) / 10);
		setOpacity(fadeB, (fadePos) / 10);

		setTimeout(fadeHelper, 50);
	} else if(fadePos == 10) {
		fadeA.style.display = "none";
		setOpacity(fadeA, 1);
		setOpacity(fadeB, 1);
	}
}

function crossFade(a, b) {
	if(typeof a == "string")
		fadeA = document.getElementById(a);
	else
		fadeA = a;
	
	if(typeof b == "string")
		fadeB = document.getElementById(b);
	else
		fadeB = b;

	fadePos = -1;

	setOpacity(fadeB, 0);
	fadeB.style.display = "block";

	fadeHelper();
}

function popup(url) {
	var w = 500;
	var h = 500;

	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;

	return window.open(url, 'popup', 'width='+w+',height='+h+',top='+t+',left='+l+',toolbar=0,statusbar=0,menu=0,scrollbars=1');
}
/* *********************** */

var lol = true;
function rollDown(control, content) {
	if(lol)
		content.style.display = "none";
	else
		content.style.display = "block";

	lol = !lol;
}

function dateCompare(d1, d2) {
	var o1 = new Date(d1);
	var o2 = new Date(d2);

	return o2.getTime() - o1.getTime();
}

function getInnerText(ele) {
	if(typeof ele.innerText == "undefined")
		return ele.textContent;
	else
		return ele.innerText;
}

/****/

function popInVid(title, file) {
	var e = document.createElement("DIV");
	e.style.textAlign = "center";
	putVidInElement(e, file, 480);
	popIn(title, e);
}

function putVidInElement(player, file, width, othervars) {
	var height = Math.floor(width / 16 * 9) + 30;

	var flashvars = "file="+file;
	flashvars += '&#038;';
	flashvars += 'skin=/skins/modieus/modieus.xml';
	
	if(file.indexOf('youtube.com') != -1) {
		var v = file.replace(/^[^v]+v.(.{11}).*/,"$1"); 
		var image = 'http://img.youtube.com/vi/'+v+'/0.jpg';
		flashvars += '&#038;';
		flashvars += 'image=' + image;
		flashvars += '&#038;';
		flashvars += 'stretching=fill';
	}

	if(typeof othervars != "undefined") {
		for(i in othervars) {
			flashvars += '&#038;';
			flashvars += encodeURIComponent(i) + '=' + encodeURIComponent(othervars[i]);
		}
	}

	player.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+width+'" height="'+height+'">' +
		'<param name="movie" value="/player-licensed.swf" />' +
		'<param name="allowfullscreen" value="true" />' +
		'<param name="allowscriptaccess" value="always" />' +
		'<param name="flashvars" value="'+flashvars+'" />' +
		'<param name="wmode" value="opaque">' +
		'<embed' +
		'       type="application/x-shockwave-flash"' +
		'       src="/player-licensed.swf" ' +
		'       width="'+width+'" ' +
		'       height="'+height+'"' +
		'       wmode="opaque"' +
		'       allowscriptaccess="always" ' +
		'       allowfullscreen="true"' +
		'       flashvars="'+flashvars+'" ' +
		'/>' +
		'</object>';

	return false;
}

function saveContactField(field, cid, value) {
	post("account.cgi", { "mode" : "save-contact-field", "cid" : cid, "field" : field, "value": value }, function(t) {
	});
}

function addContactSource() {
	addContactItem("source");
}

function addContactStatus() {
	addContactItem("status");
}

function addContactItem(what) {
	var name = prompt("Name?");
	if(!name || name == "")
		return;
	post("account.cgi", { "mode" : "create-contact-" + what, "name" : name }, function(t) {
		var opt = document.createElement("OPTION");
		opt.appendChild(document.createTextNode(name));
		opt.setAttribute("value", t);

		var e = document.getElementById("contact_" + what);
		e.appendChild(opt);
		e.selectedIndex = e.options.length - 1;

		if(e.onchange)
			e.onchange(e);
	});
}

function makeEditable(ele, field, cid) {
	var txt = getInnerText(ele);
	ele.innerHTML = "";
	ele.onclick = null;

	var input;

	if(field == "quick_note") {
		input = document.createElement("TEXTAREA");
		input.setAttribute("rows", "4");
		input.value = txt;
	} else {
		input = document.createElement("INPUT");
		input.type = "text";
		input.value = txt;
	}

	var save = function() {
		ele.removeChild(input);
		post("account.cgi", { "mode" : "save-contact-field", "cid" : cid, "field" : field, "value" : input.value }, function(t) {
			if(t.indexOf("ID.") != -1) {
				field = t;
			}

			ele.onclick = function() {
				makeEditable(ele, field, cid);
			}

			ele.style.backgroundColor = "transparent";
		});

		var text = document.createTextNode(input.value);
		ele.appendChild(text);
		ele.style.backgroundColor = "#ffffcc";
		/*
		if(field.indexOf("NEW.") != -1) {
			ele.onclick = function() {
				makeEditable(ele, field, cid);
			}
		} else {
			ele.onclick = null;
		}
		*/
	}

	input.onblur = save;

	//if(input.tagName == "input")
	if(field != "quick_note")
	input.onkeypress = function(e) {
		if(!e)
			e = window.event;
		if(!e)
			return;
		var code;
		if(e.keyCode)
			code = e.keyCode;
		else if (e.which) code = e.which;

		if(code == 13) {
			save();
			return false;
		}

		return true;
	}

	input.title = field;

	//ele.appendChild(document.createTextNode(field));
	//ele.appendChild(document.createElement("BR"));

	ele.appendChild(input);
	input.focus();
	input.select();
}

var customMessageCount = 1;

function addAnotherCustomMessage(where, noCheckbox) {
	var list = where.parentNode;

	customMessageCount++;

	var e = document.createElement("LI");

	if(typeof noCheckbox == "undefined") {
		var checkbox = document.createElement("INPUT");
		checkbox.type = "checkbox";
		checkbox.name = "custom";
		checkbox.value = customMessageCount;
		e.appendChild(checkbox);

		e.appendChild(document.createTextNode(" "));
	}

	var input = document.createElement("INPUT");
	input.type = "text";
	input.name = "custom_message-" + customMessageCount;
	input.style.width = "300px";
	if(typeof noCheckbox == "undefined") {
		input.onkeyup = function() {
			checkbox.checked = input.value.length ? true : false;
		}
	}
	e.appendChild(input);

	list.insertBefore(e, where);

	input.focus();
}

function showOverlay() {
	var grey;
	grey = document.createElement("DIV");
	grey.style.backgroundColor = 'black';
	grey.style.zIndex = '11000';
	makeElementCoverScreen(grey);
	setOpacity(grey, 0.8);

	document.body.appendChild(grey);

	return grey;
}

var popInActive = 0;

function popIn(title, html) {
	var grey;
	if(popInActive == 0) {
		grey = showOverlay();
	}

	var holder = document.createElement("DIV");
	holder.className = "popin-holder";

	function close() {
		popInActive--;
		document.body.removeChild(holder);
		if(popInActive == 0)
			document.body.removeChild(grey);
		window.onresize = old;
	}

	var titleBar = document.createElement("DIV");
	titleBar.className = "popin-title-bar";
	titleBar.appendChild(document.createTextNode(title));
	holder.appendChild(titleBar)

	var closeButton = document.createElement("A");
	closeButton.href = "#";
	closeButton.className = "button popin-close-button";
	holder.appendChild(closeButton);
	closeButton.innerHTML = '<img src="/site-icons/delete.png" alt="" /> Close';
	closeButton.onclick = function() {
		close();
		return false;
	}


	var contentHolder = document.createElement("DIV");
	contentHolder.className = "popin-content";
	holder.appendChild(contentHolder);

	function resizePopin() {
		var y = 80;

		var width = 760;
		if(viewableSize()[0] < 760)
			width = viewableSize()[0] - 32;
		var height = viewableSize()[1] - y * 2;

		var x = (viewableSize()[0] - width) / 2;
		if(x < 0)
			x = 0;
		setFixedPosition(holder, x, y);

		// HACK
		holder.style.position = "absolute";

		holder.style.width = width + "px";
		/*holder.style.maxHeight = height + "px";*/

		/*
		contentHolder.style.position = "absolute";
		contentHolder.style.left = "8px";
		contentHolder.style.top = "28px";
		*/

		contentHolder.style.marginLeft = "8px";
	//	contentHolder.style.marginTop = "28px";
		contentHolder.style.marginBottom = "8px";

		contentHolder.style.width = (width - 16) + "px";
//		contentHolder.style.maxHeight = (height - 8 - 28) + "px";
	}

	resizePopin();
	holder.style.zIndex = "11001";

	var old = window.onresize;
	window.onresize = function() {
		resizePopin();
		if(old)
			old();
	}

	document.body.appendChild(holder);
	if(typeof html == "string")
		contentHolder.innerHTML = html;
	else
		contentHolder.appendChild(html);

	popInActive++;

	var pop = new Object();
	pop.close = function() { close(); }

	window.scrollTo(0, 0);

	return pop;
}


function previewQuickEmail(form) {
	var i = document.createElement("IFRAME");
	i.src = "about:blank";
	i.width = "99%";
	i.height = "99%";
	i.setAttribute("id", "qe-target");
	i.setAttribute("name", "qe-target");
	i.style.border = "none";

	popIn("Email Preview", i);

	var oldTarget = form.target;
	form.setAttribute("target", "qe-target");
	var oldMode = form.mode.value;
	form.mode.value = "preview-quick-email";
	form.submit();

	form.mode.value = oldMode;
	form.target = oldTarget;
}

function previewCraigslistImage(file, id) {
	var i = document.createElement("IMG");
	i.alt = "";
	i.src = file;

	popIn("Ad Preview", i);
}

function showCraigslistCode(file, id, un) {
	var div = document.createElement("DIV");
	var i = document.createElement("TEXTAREA");

	i.style.margin = "64px 100px";
	i.style.width = "500px";
	i.setAttribute("rows", "5");
	i.setAttribute("readonly", "readonly");

	var code = '<a href="http://getzus.com/'+un+'"><img src="http://teamzus.com/' + file + '" alt="Check out my Zus page" /></a>';

	i.appendChild(document.createTextNode(code));

	div.appendChild(i);

	var a = document.createElement("A");
	a.className = "button";
	a.href = "http://craigslist.com";
	a.target = "_BLANK";

	a.innerHTML = '<img src="/site-icons/arrow.png" alt="" /> Go to Craigslist';

	div.style.textAlign = "center";
	a.style.marginTop = "16px";
	a.style.marginBottom = "6px";

	div.appendChild(a);

	popIn("Copy and Paste this code to Craigslist", div);

	i.select();
}

function showEventInvite(eid) {
	get("/template/event-invite.html", function(t) {
		popIn("Invite Friends to Event", t.replace("{$eid}", eid));
	});
}

function addFromFriendList(e) {
	get("/account.cgi?mode=get-friends&format=popin-form", function(t) {
		var pop = popIn("Add from Friend List", t);
		var flf = document.getElementById('friend-list-form');
		flf.onsubmit = function() {
			var contents = e.value;
			if(flf.user) {
				if(flf.user.value) {
					if(flf.user.checked) {
						if(e.value.length)
							e.value += ", ";
						e.value += flf.user.value;
					}
				} else {
					var outputted = e.value.length > 0;
					for(i = 0; i < flf.user.length; i++)
						if(flf.user[i].checked) {
							if(outputted)
								contents += ", ";
							else
								outputted = true;
							contents += flf.user[i].value;
						}
					e.value = contents;
				}
			}
			pop.close();

			return false;
		}
	});
}

function checkAll(field, checked) {
	if(field.checked !== null)
		field.checked = checked;
	for(i = 0; i < field.length; i++) {
		field[i].checked = checked;
	}
}

/* ******** */

function addContact(lid) {
	//var e = document.createElement("DIV");
	get("template/add-contact.html", function(t) {
		popIn("Add Contact", t);
		if(lid) {
			var e = document.getElementById("new-contact-list-id");
			e.value = lid;
		}
	});
}

function showUpgrade() {
	get("/account.cgi?mode=get-current-user-id", function(t) {
		var grey = showOverlay();

		var img = document.createElement("DIV");
		var x;
		if(viewableSize()[0] < 700)
			x = 0;
		else
			x = (viewableSize()[0] - 700) / 2;
		setFixedPosition(img, x, 40);
		img.style.position = "absolute";
		img.style.width = "700px";
		img.style.height = "500px";
		img.style.zIndex = '11001';
		img.style.backgroundImage = "url('/homepage/upgrade-popup.png')";
		document.body.appendChild(img);

		var closeButton = document.createElement("DIV");
		closeButton.style.position = "absolute";
		closeButton.style.left = '619px';
		closeButton.style.top = '8px';
		closeButton.style.width = "75px";
		closeButton.style.height = "24px";
		closeButton.style.cursor = "pointer";
		img.appendChild(closeButton);

		closeButton.onclick = function() {
			document.body.removeChild(img);
			document.body.removeChild(grey);
			//history.go(-1);
			location.href = "/homepage.cgi";
		}

		var upgradeButton = document.createElement("A");
		upgradeButton.style.display = "block";
		if(t > 0)
			upgradeButton.href = "http://teamzus.com/buy.cgi?upgrade="+t;
		else
			upgradeButton.href = "http://teamzus.com/buy.cgi";
		upgradeButton.style.position = "absolute";
		upgradeButton.style.left = "273px";
		upgradeButton.style.top = "448px";
		upgradeButton.style.width = "157px";
		upgradeButton.style.height = "33px";
		img.appendChild(upgradeButton);

		//popIn("You must upgrade your membership to use this feature!", "<a href=\"https://teamzus.com/buy.cgi?upgrade="+t+"\">Click here to upgrade now!</a>");
	});
}
function showLogIn() {
	popIn("You must login", "or log in");
}

/* ********* */

function editStatus(e) {
	//e.innerHTML = "edit";
}


function editNote(taskID) {
        get("tasks.cgi?mode=get-notes&id=" + taskID, function(t) {
                popIn("Task Notes", t);
        });
}


/* ******* */

function makeFiveStepElement(holder, e, x, y, w, h) {
	var a = document.createElement(e);
	a.style.position = "absolute";
	a.style.padding = '0px';
	a.style.margin = '0px';
	a.style.overflow = 'hidden';

	a.style.left = x + 'px';
	a.style.top = y + 'px';
	a.style.width = w + 'px';
	a.style.height = h + 'px';
	a.style.display = "block";

	holder.appendChild(a);

	return a;
}

function makeFiveStepHolder(step, next) {
	var a = document.createElement("DIV");
	a.style.position = "absolute";
	a.style.padding = '0px';
	a.style.margin = '0px';
	a.style.overflow = 'hidden';

	a.style.backgroundImage = "url('/steps/step" + step + ".png')";

	var l = viewableSize()[0] - 744;

	a.style.left = l/2 + 'px';
	a.style.top = 80 + 'px';
	a.style.width = 744 + 'px';
	a.style.height = 360 + 'px';
	a.style.zIndex = "11001";

	if(step != 1)
		a.style.display = "none";

	document.body.appendChild(a);

	var holder = a;
	var nextButton;
	if(step < 3)
		nextButton = makeFiveStepElement(holder, "DIV", 557, 153, 104, 37);
	else if(step == 3)
		nextButton = makeFiveStepElement(holder, "DIV", 573, 155, 104, 37);
	else
		nextButton = makeFiveStepElement(holder, "DIV", 557, 191, 104, 37);
	nextButton.style.cursor = "pointer";
	nextButton.onclick = next;

	return a;
}

var globallol;

function makeTypedInputElement(holder, name, type, x, y, w, h) { 
	var radioHtml = '<input type="'+type+'" name="' + name + '"'; 
	radioHtml += '/>'; 

	var radioFragment = document.createElement('div'); 
	radioFragment.innerHTML = radioHtml; 

	var a= radioFragment.firstChild; 
	a.style.position = "absolute";
	a.style.padding = '0px';
	a.style.margin = '0px';
	a.style.overflow = 'hidden';

	a.style.left = x + 'px';
	a.style.top = y + 'px';
	a.style.width = w + 'px';
	a.style.height = h + 'px';
	a.style.display = "block";

	holder.appendChild(a);

	return a;
} 

function showFiveSteps() {
	var grey = showOverlay();

	var holders = Array();

/*
	for(a = 8; a > 0 ; a--) {
		var holder = makeFiveStepHolder(a, a != 8 ? makeCrossFade(a) : close);
		if(a != 1)
			holder.style.display = "none";
		holders.unshift(holder);
	}
*/
	var holder8;
	holder8 = makeFiveStepHolder(8, function() {
		post("account.cgi", {
			"mode" : "save-twitter-info",
			"username" : twitter_username.value,
			"password" : twitter_password.value
		}, function(t) {
			close();
		} );
	});
	var twitter_username = makeFiveStepElement(holder8, "INPUT", 125, 192, 141, 22);
	var twitter_password = makeTypedInputElement(holder8, "",  "password", 349, 192, 141, 22);

	var mam_twitter = makeFiveStepElement(holder8, "DIV", 129, 243, 109, 11);
	mam_twitter.style.cursor = "pointer";
	mam_twitter.onclick = function() { window.open("http://www.youtube.com/watch?v=o4oGjR8MI_U"); }
	var get_twitter = makeFiveStepElement(holder8, "DIV", 385, 243, 77, 11);
	get_twitter.style.cursor = "pointer";
	get_twitter.onclick = function() { window.open('http://twitter.com'); }

	var holder7;
	holder7 = makeFiveStepHolder(7, function() {
		crossFade(holder7, holder8);
	});
	var facebook_link = makeFiveStepElement(holder7, "A", 55, 189, 438, 28);
	facebook_link.appendChild(document.createTextNode("Link with Facebook"));
	facebook_link.target = "_BLANK";
	facebook_link.href="/socialaccounts/fb.php";
	var mam_facebook = makeFiveStepElement(holder7, "DIV", 129, 243, 124, 11);
	var get_facebook = makeFiveStepElement(holder7, "DIV", 400, 243, 77, 11);
	mam_facebook.style.cursor = "pointer";
	mam_facebook.onclick = function() { window.open("http://www.youtube.com/watch?v=0LPrWXLBtwk"); }
	get_facebook.style.cursor = "pointer";
	get_facebook.onclick = function() { window.open("http://facebook.com"); }

	var holder6;
	holder6 = makeFiveStepHolder(6, function() {
		crossFade(holder6, holder7);
		post("account.cgi", {
			"mode" : "save-gmail-info",
			"username" : gmail_username.value,
			"password" : gmail_password.value
		}, function(t) {} );
	});
	var gmail_username = makeFiveStepElement(holder6, "INPUT", 125, 192, 141, 22);
	gmail_username.name = "gmail_username";
	var gmail_password = makeTypedInputElement(holder6, "", "password", 349, 192, 141, 22);

	var mam_gmail = makeFiveStepElement(holder6, "DIV", 129, 243, 104, 11);
	mam_gmail.style.cursor = 'pointer';
	mam_gmail.onclick = function() { window.open("http://www.youtube.com/watch?v=gK_BtB4Z22Q"); }

	var get_gmail = makeFiveStepElement(holder6, "DIV", 381, 243, 87, 11);
	get_gmail.style.cursor = 'pointer';
	get_gmail.onclick = function() { window.open("http://gmail.com"); }


	var holder5;
	holder5 = makeFiveStepHolder(5, function() {
		crossFade(holder5, holder6);
		upload.submit();
	});
	var upload = makeFiveStepElement(holder5, "FORM", 63, 214, 402, 22);
	upload.setAttribute("enctype", "multipart/form-data");
	upload.setAttribute("target", "secret-iframe");
	upload.setAttribute("action", "account.cgi");
	upload.setAttribute("method", "POST");
	var i = document.createElement("INPUT");
	i.setAttribute("type", "file");
	i.setAttribute("name", "image");
	upload.appendChild(i);
	i = document.createElement("INPUT");
	i.setAttribute("type", "hidden");
	i.name="mode";
	i.value="save-profile-picture";
	upload.appendChild(i);
	i = document.createElement("INPUT");
	i.setAttribute("type", "hidden");
	i.name="submode";
	i.value="ajax";
	upload.appendChild(i);

	globallol = upload;

	var holder4;
	holder4 = makeFiveStepHolder(4, function() {
		crossFade(holder4, holder5);
		post("account.cgi", {
			"mode" : "save-headline",
			"headline" : headline.value
		}, function(t) {} );
	});
	var headline = makeFiveStepElement(holder4, "TEXTAREA", 54, 175, 432, 70);
	headline.name = "headline";
	headline.rows="3";

	var holder3;
	holder3 = makeFiveStepHolder(3, function() {
		crossFade(holder3, holder4);
	});

	var holder2;
	holder2 = makeFiveStepHolder(2, function() {
		if((male.checked || female.checked) && zip.value.length >= 5) {
			crossFade(holder2, holder3);
			post("account.cgi", {
				"mode" : "save-initial-info",
				"gender" : (male.checked ? 'm' : 'f'),
				"zip" : zip.value
			}, function(t) {} );
		} else
			alert("Please enter your gender and your Zip code to proceed.");
	});
	var male = makeTypedInputElement(holder2, "gender", "radio", 167, 146, 17, 13);
	male.setAttribute("value", "m");

	var female = makeTypedInputElement(holder2, "gender", "radio", 266, 146, 17, 13);
	female.setAttribute("value", "f");

	var zip = makeFiveStepElement(holder2, "INPUT", 168, 182, 122, 26);
	zip.name="zip";

	var holder1 = makeFiveStepHolder(1, function() {
		crossFade(holder1, holder2);
	});

	function close() {
		document.body.removeChild(holder1);
		document.body.removeChild(holder2);
		document.body.removeChild(holder3);
		document.body.removeChild(holder4);
		document.body.removeChild(holder5);
		document.body.removeChild(holder6);
		document.body.removeChild(holder7);
		document.body.removeChild(holder8);
		document.body.removeChild(grey);
	}

	function addClose(what) {
		var c1 = makeFiveStepElement(what, "DIV", 635, 64, 83, 24);
		c1.style.cursor = "pointer";
		c1.onclick = close;
	}

	addClose(holder3);
	addClose(holder4);
	addClose(holder5);
	addClose(holder6);
	addClose(holder7);
	addClose(holder8);
}

function showTerms() {
	popup("/terms.html");
	return false;
}

function showPrivacy() {
	popup("/privacy.html");
	return false;
}

/* *** */


function checkUserNameAvailable(un, e, msg) {
	get("/account.cgi?mode=check-username-availability&url_name=" + un, function(t) {
		if(t == "true") {
			e.style.backgroundColor = 'white';
			msg.innerHTML = "";
		} else {
			e.style.backgroundColor = '#ffcccc';
			msg.innerHTML = "<br> * Sorry, that name is taken.<br> Please try another one.";
		}
	});

	return true;
}

//var inProgressUNAvailabilityCheck = null;
function checkUserNameAvailableOnSubmit(un, e, msg) {
	get("/account.cgi?mode=check-username-availability&url_name=" + un, function(t) {
		if(t == "true") {
			e.style.backgroundColor = 'white';
			msg.innerHTML = "";
			//if(e.form.onsubmit())
				e.form.submit();
		} else {
			e.style.backgroundColor = '#ffcccc';
			msg.innerHTML = "<br> * Sorry, that name is taken.<br> Please try another one.";
			alert('Sorry, your desired username is already taken. Please try another one.');
			e.focus();
		}
	});

	return false;
}

/* *** */

function sendForget(email, recursionLevel) {
	post("/account.cgi", {
		"mode" : "forgot-credentials",
		"email" : email
	}, function(t) {
		switch(t) {
			case "sent":
				alert("Please check your email. Your log-in information has been sent.");
			break;
			case "no-user":
				if(recursionLevel == 1)
					email = prompt("We couldn't find your email address on file. Do you have another one you might have used?")
				else if (recursionLevel == 2)
					email = prompt("Sorry, that address didn't work either. Do you have another one you might have used?")
				else {
					alert("Your email address doesn't seem to be on file. Please contact support@wealth2.com for further help. Be sure to let support know your full name and your distributor id, if you have one, to help find your account.");
					return;
				}

				if(email)
					sendForget(email, recursionLevel + 1);
				else
					alert("Please contact support@wealth2.com for further help.");
			break;
			//default:
				//alert(t)
		}
	});

}

function forgotSomething() {
	var email = prompt("What is your email address?");
	if(email) {
		sendForget(email, 1);
	}
}

function forgotUsername() {
	forgotSomething();
}

function forgotPassword() {
	forgotSomething();
}

function submitParentForm(e) {
	while(e) {
		if(e.submit) {
			if(e.onsubmit) {
				if(e.onsubmit())
					e.submit();
			} else
				e.submit();
			break;
		}
		e = e.parentNode;
	}
}



function applyPromo(code, plan) {
	var msg = document.getElementById("promo-message");
	switch(code.toLowerCase()) {
		case "":
			msg.innerHTML = "&nbsp;";
		break;
		case "twitter":
			msg.innerHTML = " Any upgrade includes Top Twitter Tips and Facebook Ad Miracle Marketing Reports!";
		break;
		case "worldcup":
			if(plan && plan.indexOf("yearly") == -1) {
				msg.innerHTML = "The worldcup promotion only applies to <big>yearly</big> plans.";
			} else {
				msg.innerHTML = "Promo Code Applied: Premium Level Membership for $199.99 per year with bonus perks!";
			}
		break;
		case "freeyear":
			if(plan.indexOf("yearly") == -1) {
				msg.innerHTML = "The freeyear promotion only applies to <big>yearly</big> plans.";
			} else {
				msg.innerHTML = "Promo code applied - your second year of "+(plan.indexOf('professional') != -1 ? "PROFESSIONAL" : "PREMIUM")+" is FREE!";
			}
		break;
		default:
			msg.innerHTML = "Sorry, your code is not valid or has expired.";
	}
}

function showFriendRequests() {
	get("/account.cgi?mode=friend-requests", function(t) {
		popIn("Friend Requests", t);
	});
}


function showMentorRequests() {
	get("/account.cgi?mode=mentor-requests", function(t) {
		popIn("Mentor Requests", t);
	});
}

var currentFrontPageStep = 1;
function gotoStep(step, relative) {
	if(relative)
		step = step + currentFrontPageStep;
	if(step < 1)
		step = 1;
	if(step > 5)
		step = 5;

	currentFrontPageStep = step;
	
	var s = document.getElementById("step-holder");
	s.style.backgroundImage = "url('/homepage/step-" + step + ".png')";

	var ol = s.getElementsByTagName("OL");
	ol = ol[0];
	var lis = ol.getElementsByTagName("LI");
	for(var a = 0; a < 5; a++) {
		var li = lis[a];
		var color = "white";
		if(a + 1 == step)
			color = "red";

		var side = "";
		if(a == 0)
			side = "-left";
		if(a == 4)
			side = "-right";
			
		li.style.backgroundImage = "url('/homepage/"+color+"-step-background"+side+".png')";
	}

	var txt = document.getElementById("step-link");
	txt.innerHTML =
		step == 1 ? "Launch Social Blaster Now!"
	      : step == 2 ? "Launch Promotion Messages!"
	      : step == 3 ? "Launch Enhanced Blog Now!"
	      : step == 4 ? "Launch Events Calendar Now!"
	      : /*step == 5*/"Launch Contact Manager!";

	txt.href = 
		step == 1 ? "/social-blaster.php"
	      : step == 2 ? "/promote.cgi?mode=promotion-messages"
	      : step == 3 ? "/my-blog.php"
	      : step == 4 ? "/events.cgi"
	      : /*step == 5*/"/account.cgi?mode=contact-manager";
}


function popinLink(a, title) {
	get(a.href, function(t) {
		popIn(title, t);
	});
}

function overImage(ele, isOver) {
	if(isOver) {
		if(ele.src.indexOf("_over.png") == -1)
			ele.src = ele.src.replace(".png", "_over.png");
	} else {
		ele.src = ele.src.replace("_over.png", ".png");
	}	
}


function showGmailPopin() {
	var d = document.createElement("DIV");
	d.innerHTML = "<p>To use this feature, you must set up a <a href=\"/account.cgi?mode=social-accounts\">Google account in Social Accounts</a>.</p>" +

	"<h3>Why Gmail?</h3>" +

	"<ol>" +
		"<li>Mail sent from a Gmail account is secure.</li>" +
		"<li>It allows your &quot;from&quot; address to reflect your personal email address, so your recipients know it's coming from you.</li>" +
		"<li>Gmail has strong spam controls that keep unwanted messages out of your inbox.</li>" +
		"<li>Gmail is web-based, so you can access it from anywhere, including your mobile phone.</li>" +
	"</ol>" +
	
	"<p style=\"text-align: center;\"><a href=\"account.cgi?mode=social-accounts\" class=\"button\"><img src=\"/site-icons/arrow.png\" alt=\"\" /> Link your Google Gmail account to Team Zus now</a></p>";

	popIn("Set up your Gmail!", d);
}

function showLinkNotes(linkId) {
	get("promote.cgi?mode=get-link-tracking-notes&id=" + linkId, function(t) {
		popIn("Trackable Link Notes", t);
	});
}

function testGmail() {
	post("account.cgi", {"mode":"send-gmail-test"}, function(t) {
		alert("A test email has been sent to your Gmail account. Please check your Gmail Inbox to verify you've received it. If you receive the test email, then your Gmail account is properly connected. If you did not receive the test email, the Gmail information you entered here may be incorrect. Click 'Change' to re-enter your Gmail information.");
	});
}

function editMedia(type, mid) {
	get("account.cgi?mode=edit-media&id=" + mid, function(t) {
		popIn("Edit " + type, t);
	});
}

function showChangePassword() {
	var html = "<div>" +
		'<form method="POST" onsubmit="if(this.pw.value != this.cpw.value) { alert(\'Your passwords do not match.\'); return false; } return true;">' +
		'<input type="hidden" name="mode" value="change-password" />' +
			'<table width="66%" align="center">' +
			'<tr><th>Password:</th><td><input name="pw" type="password" /></td></tr>' +
			'<tr><th>Confirm:</th><td><input name="cpw" type="password" /></td></tr>' +
			'<tr><th>&nbsp;</th><td><input type="submit" value="Save Password" /></td></tr>' +
			'</table>' +
		'</form>' +
	"</div>";

	popIn("Changing Password", html);
}


/* *** */


function scrollContent(amount) {
	var content = document.getElementById("slider-content");

	var current = content.scrollLeft;
	current += amount;
	if(current < 0)
		current = 0;
	if(current > content.scrollWidth)
		current = content.scrollWidth;

	content.scrollLeft = current;
}

var scrolling = false;
var scrollingSpeed = 0;
var scrollingTimer = null;

function startScrolling(direction) {
	if(scrolling)
		return;

	scrollingSpeed = direction;

	var accelerator = 0;

	scrollingTimer = setInterval(function() {
		if(accelerator == 0) {
			if(scrollingSpeed > 0 && scrollingSpeed < 15)
				scrollingSpeed++;
			if(scrollingSpeed < 0 && scrollingSpeed > -15)
				scrollingSpeed--;
			accelerator = 6;
		} else
			accelerator--;
		scrollContent(scrollingSpeed);
	}, 20);
}

function stopScrolling() {
	scrolling = false;
	scrollingSpeed = 0;
	clearInterval(scrollingTimer);
	scrollingTimer = null;
}


