/* tips.js - utility function used by DollarTimes.com  */
/* open - hidden windows that are open */
var open = [];
/* errMsgs - divs with error messages */ 
var errMsgs = [];

/* Tabbing functionality from Elated.com - http://www.elated.com/articles/javascript-tabs/ */	
var tabinit = false;
var tabLinks = [];
var contentDivs = [];

function initTabs() {
	var tabs = document.getElementById('tabs');
	$("#loading-gif").hide()
	if (tabs==null)
	{
		return false;
	}
	var tabListItems = tabs.childNodes;
	for ( var i = 0; i < tabListItems.length; i++ ) {
		if ( tabListItems[i].nodeName == "LI" ) {
			var tabLink = getFirstChildWithTagName( tabListItems[i], 'A' );
			var id = getHash( tabLink.getAttribute('href') );
			tabLinks[id] = tabLink;
			contentDivs[id] = document.getElementById( id );
		}
	}
	var i = 0;
	for ( var id in tabLinks ) {
		tabLinks[id].onclick = showTab;
		tabLinks[id].onfocus = function() { this.blur() };
		if ( i == 0 ) tabLinks[id].className = 'selected';
		i++;
	}
	var i = 0;
	for ( var id in contentDivs ) {
		if ( i != 0 ) contentDivs[id].className = 'tabContent hide';
		i++;
	}
	/* resend verification button */
	$("#resend-verification").hide();
}

function showTabId(selectedId) {
	for ( var id in contentDivs ) {
		if ( id == selectedId ) {
			tabLinks[id].className = 'selected';
			contentDivs[id].className = 'tabContent';
		} else {
			tabLinks[id].className = '';
			contentDivs[id].className = 'tabContent hide';
		}
	}
	// Stop the browser following the link
	return false;
}

function showTab() {
	var selectedId = getHash( this.getAttribute('href') );
	for ( var id in contentDivs ) {
		if ( id == selectedId ) {
		tabLinks[id].className = 'selected';
		contentDivs[id].className = 'tabContent';
		} else {
			tabLinks[id].className = '';
			contentDivs[id].className = 'tabContent hide';
		}
    }
    return false;
}
function getFirstChildWithTagName( element, tagName ) {
	for ( var i = 0; i < element.childNodes.length; i++ ) {
		if ( element.childNodes[i].nodeName == tagName ) return element.childNodes[i];
	}
}
/* Returns the part of the url appearing after the # symbol*/
function getHash( url ) {
	var hashPos = url.lastIndexOf ( '#' );
	//alert(hashPos);
	return url.substring( hashPos + 1 );
}

/* change the settings */
function tryChgSettings() {
	remind = document.getElementById('setting_email_reminder').checked;
	content = document.getElementById('setting_email_new').checked;
	settings= CreateRequestObject();
	settings.open("post", "/budget/settings.php", true);
	var post = "";
	if (remind) {
		post = post + "&email_reminder=on"
	}
	if (content)
	{
		post = post + "&email_content=on"
	}
	settings.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	settings.setRequestHeader("Content-length", post.length);
	settings.setRequestHeader("Connection", "close");
	settings.onreadystatechange = function() {
			var response;
			if( settings.readyState == 4){
				response = settings.responseText;
				if (response=="settings=1")
				{
					/* display success message*/				
					chgErrorMsg('dt_settings_msg','<h2>Your settings have been changed.</h2>');
				} else {
					/* display error error message */
					chgErrorMsg('dt_settings_msg','<h2>Error - Unable to change your settings</h2>');
				}
			}
	}
	settings.send(post);
}
/* subscribe to email and prompt to create account */
function subscribe(id,event) {
	var email = document.getElementById('dtEmail').value;
	if (email != email.match(/^[A-Za-z0-9._%+-]+\x40[A-Za-z0-9.-]+\.[a-zA-Z]{2,4}$/))
	{
		alert("Please enter a valid email address.");
		//document.getElementById('dtEmail').value = "";
		return false;
	}	
	setEmailReminder(CreateRequestObject(),email,event,id);
}

/* Escape when focus is on an input, and escape is pressed */
function checkEscape(event,id) {
	if (event.keyCode==27)
	{
		if(id!=null)
			toggleVisibility(id);
	}
}

function closeAll() {
	var i = open.length;
	while(i--) {
		var el = document.getElementById(open.pop());
		if (el!=null)
		{
			if(!el.className.match('hidden')) {		
				el.className = el.className.concat(' hidden');
			}
		}
	}
}
function clearAllErrorMsgs() {
	var i = errMsgs.length;
	while(i--) {
		var el = document.getElementById(errMsgs.pop());
		if (el!=null)
		{
			el.innerHTML='';
		}
	}
}

/* Created this function - for toggling visibility on sub areas of a page */
function makeVisible(id) {
	var el = document.getElementById(id);
	var classname = el.className;			
	if(classname.match('hidden')) {	
		classname = classname.replace('hidden', '');
	}
	else {
		classname = classname.concat(' hidden');
	}	
	el.className=classname;	
}

/* Modifies the visibility, like makeVisible, also closes any visible divs contained in open */
function toggleVisibility(id) {
	if (!tabinit)
	{
		initTabs();
	}
	// TODO - switch this to using JQUERY
	var el = document.getElementById(id);
	var classname = el.className;			
	if(classname.match('hidden')) {	
		closeAll();
		open.push(id);
		classname = classname.replace('hidden', '');
		$('#overlay').removeClass('hidden');
	}
	else {
		closeAll();
		open.pop();
		classname = classname.concat(' hidden');
		$('#overlay').addClass('hidden');
	}	
	el.className=classname;	
}

function chgErrorMsg(id,msg) {
	var el = document.getElementById(id);
	if (el!=null)
	{
		errMsgs.push(id);
		el.innerHTML = msg;
	}
}

function clearErrorMsg(id) {
	chgErrorMsg(id,'');
}

function setFocus(id) {
	var el = document.getElementById(id);
	if (el!=null) {
		el.focus();
	}
}
function commentScrub() {
	var comment = document.getElementById('dt_comment').value;
	if (comment.length > maxCommentLength)
	{
		alert('Your comment is too large');
		document.getElementById('dt_comment').value = substring(0,maxCommentLength);
	}
}

/* put the window to the left, just above center */
function centerLeft(id, e) {
	var el = document.getElementById(id);
	if (el!=null)
	{
		var top = (e.clientY -180) + 'px';
		var left = (e.clientX - 480 ) + 'px';
		//alert('client x: '+top + ' client y: '+left);
		el.style.top = top;
		el.style.left = left;
	}
}

/* center the window about the mouse click*/
function center(id, e) {
	var el = document.getElementById(id);
	if (el!=null)
	{
		var top = (e.clientY -120) + 'px';
		var left = (e.clientX - 120 ) + 'px';
		//alert('client x: '+top + ' client y: '+left);
		el.style.top = top;
		el.style.left = left;
	}
}

/* center the window about the mouse click*/
function centerRight(id, e) {
	return false;
	var el = document.getElementById(id);
	if (el!=null)
	{
		var left = (e.clientX) + 'px';
		var top = (e.clientY - 100) + 'px';
		el.style.left = left;
		el.style.top = top;
	}
}

function center(id, e) {
	$(id).addClass("center");
}

/* put the window below, and to the left */
function centerBelowLeft(id, e) {
	return false;
	var el = document.getElementById(id);
	if (el!=null)
	{
		newX = (e.clientY + 50);
		newY = (e.clientX - 500);
		X=String(newX)+"px";
		Y=String(newY)+"px";
		//alert('new x: '+X + ' new y: '+Y);
		//el.style.top = X; //"10px"; //newY;
		//el.style.left = Y; //"10px"; //newX;
		el.style.top = newX+'px';
		el.style.left = newY+'px';
	}

}

function logout() {
	request = CreateRequestObject();
	request.open("get", "/budget/logout.php", true);
	request.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
	request.setRequestHeader("Content-length", 0);
	request.setRequestHeader("Connection", "close");
	request.onreadystatechange = function() {
			if( request.readyState == 4){
				/* refresh page to logout */
				window.location.reload();
			}
	}
	request.send(null);

}

/*  AJAX snippet: */
function CreateRequestObject() {
	var ro;
	try
	{
		var browser = navigator.appName;
		if(browser == "Microsoft Internet Explorer"){
			ro = new ActiveXObject("Microsoft.XMLHTTP");
		}else{
			ro = new XMLHttpRequest();
		}
		return ro;
	}
	catch (e)
	{
		alert('error using xmlhttp: '+e.message);
	}
}

function setEmailReminder(emailHttp,email,event,id)
{
	if(emailHttp==null)
	{
		alert('Unable to join mailing list at this time.');
	}	
	emailHttp.open("post", "/budget/reminder.php", true);
	var post = "email=" + escape(email);
	emailHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	emailHttp.setRequestHeader("Content-length", post.length);
	emailHttp.setRequestHeader("Connection", "close");
	emailHttp.onreadystatechange = function() {
			var response;
			if( emailHttp.readyState == 4){
				response = emailHttp.responseText;
			}
			else {
				return;
			}
			if (response.length > 0)
			{
				//toggleVisibility('dt_join_email');
				alert( response );		
			} else {
				toggleVisibility(id);
			}

	}
	emailHttp.send(post);
}
function submitTipIdea(id) {
  var name = $("#submit-tip-name").val();
  var tip = $("#submit-tip-idea").val();
  $.post('/budget/submit.php', 
         { name: name, tip : tip }, 
         function() {
           
         });
  alert('Thank you for your submission.\nYour ideas are always appreciated!');
  toggleVisibility(id);
}

