var jsTimerID = null;
var jsWait = 60000;
var isOnline=0;

function invalidEmailLink(email) {
	var webEmail = email +' - at - crazedsanity - dot - com'
	var realEmail = email +'@crazedsanity.com';
	var link = 'mailto:' + email + '@127.0.0.1';
	
	if(email == 'gmail') {
		webEmail = 'crazedsanity - dot - com - at - gmail - dot - com';
		realEmail = 'crazedsanity' + '.' + 'com' + '@' + 'gmail' + '.' + 'com';
	}
	
	var answer = confirm('FAKE ADDRESS:   ' + webEmail + '\n'
		+'REAL ADDRESS: ' + realEmail + '\n\n'
		+'Just so you understand what\'s about to happen if you decide to continue (by clicking "OK"): a compose screen will show up, where you can write a great email to me (' + link + ') about how you\'ve been trying to contact me forever... unfortunately, since you can\'t seem to read between the lines, you\'ll probably never know that it will NOT GO ANYWHERE.\n\n'
		+'The IP address 127.0.0.1 is a LOOPBACK ADDRESS: when you send the email you\'re about to compose, your poor mailserver will get it & attempt to deliver to itself... and it will probably succeed, though the webmaster @ your isp will probably get kinda mad.\n\nClicking "OK" will allow you to continue... but you won\'t do that, because I just **KNOW** you read this message.')
	if(answer) {
		//they clicked "OK"
		alert('You have chosen POORLY.  Have fun wasting your time composing an email that will never be read... well, at least not by anybody at CrazedSanity.com.')
		window.open(link)
	} else {
		alert('You have chosen WISELY.  Maybe now you\'ll think twice about clicking on a link before reading it.')
	}
}

//Use this for compatibility with Internet Explorer, so elements can actually be found.  Done this
//way instead of via JQuery because JQuery doesn't actually support parsing XML
//(see http://dev.jquery.com/ticket/3143)
//
//SOURCE:::
//http://groups.google.com/group/jquery-en/browse_frm/thread/95718c9aab2c7483/af37adcb54b816c3?lnk=gst&q=parsexml&pli=1
function parseXML( xml ) {
	if( window.ActiveXObject && window.GetObject ) {
		var dom = new ActiveXObject( 'Microsoft.XMLDOM' );
		dom.loadXML( xml );
		return dom;
	}
	if( window.DOMParser )
		return new DOMParser().parseFromString( xml, 'text/xml' );
	throw new Error( 'No XML parser available' );
}

//This is from http://www.w3schools.com/xml/xml_parser.asp
function parseXMLDoc( xml ) {
	if(xml == null || xml == undefined || xml.length < 10) {
		alert("No xml to parse");
	}
	else {
		if (window.DOMParser)
		{
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(xml,"text/xml");
		}
		else // Internet Explorer
		{
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async="false";
			xmlDoc.loadXML(xml);
		}
		return xmlDoc;
	}
}

function ajax_getRequest(type, isAsync, url) {
	if(isAsync != false && isAsync != true) {
		isAsync = true;
	}
	
	myUrl='/ajax/';
	if(url != undefined) {
		myUrl = url;
	}
	
	$.ajax ({
		url			: myUrl + type,
		cache		: false,
		async		: isAsync,
		dataType	: 'text/xml',
		timeout		: (30 * 1000),
		success: function (returnXml) {
			var xml = parseXML(returnXml);
			if($(xml).find('type').text() == 'auth') {
				updateLoginBox(xml);
				
				if($(xml).find('status').text() == 1) {
					jsWait = $(xml).find('authcheckinterval').text();
					jsTimerID = setTimeout("ajax_checkLogin()", jsWait);
					if(isOnline == 0) {
						//they were offline, but came back: update the weather image so it appears.
						autoUpdateWeatherImg();
					}
					isOnline=1;
				}
			}
			if($(xml).find('replacecontent').text() && $(xml).find('replacecontentdata').length) {
				//Information needs to get updated, so update it!
				var divToReplace = $(xml).find('replacecontent').text();
				var dataToLoad = $(xml).find('replacecontentdata').text();
				//alert('Replacing data in div (' + divToReplace +'), data::: '+ decode64(dataToLoad));
				$("#"+ divToReplace).html(decode64(dataToLoad));
			}
		},
		error: function (returnXml) {
			//alert("Call to " + type + " failed::: " + returnXml);
			//something bad happened, check regularly to see if they go back online.
			show_checkingLogin();
			isOnline=0; 
			jsWait = 60000; //once a minute...
			jsTimerId = setTimeout("ajax_checkLogin()", jsWait);
			
		}
	});
}


function show_checkingLogin() {
	$("#infobar_login").hide();
	$("#infobar_logout").hide();
	$("#infobar_checkingLogin").show();
}

function autoUpdateWeatherImg() {
	if($("#weatherImg")) {
		var newTimestamp = new Date().getTime();
		if($("#oldWeatherImg").text().length == 0) {
			$("#oldWeatherImg").text($("#weatherImg").attr('src'));
		}
		var imgUrl = $("#oldWeatherImg").text();
		if(imgUrl.length > 0) {
			var imgUrl = $("#oldWeatherImg").text() + "?csGarbage=" + newTimestamp;
			$("#weatherImg").attr('src',imgUrl);
			
			//about 20 minutes: that's how often the information gets updated anyway.
			var timeToWait = 1000 * 60 * 20;
			setTimeout('autoUpdateWeatherImg()', timeToWait);
		}
	}
}

function updateLoginBox(xmlObj) {
	var loginStatus = $(xmlObj).find('status').text();
	var loginText = $(xmlObj).find('errorcode').text();
	if(loginStatus == '1') {
		$("#infobar_login").hide();
		$("#infobar_checkingLogin").hide();
		$("#infobar_logout").show();
		$("#showLoginUsername").text($(xmlObj).find('showloginusername').text());
	}
	else {
		$("#infobar_login").show();
		$("#infobar_checkingLogin").hide();
		$("#infobar_logout").hide();
	}
}

function handle_ajaxLoginResult(xml) {
	if(typeof xml == "object") {
		updateLoginBox(xml);
		
		//they're logged in.  Redirect.
		if($(xml).find('status').text() == 1 && getURLVar('loginDestination')) {
			var dest = Url.decode(getURLVar('loginDestination'));
			document.location=dest;
		}
	}
}


function ajax_checkLogin() {
	ajax_getRequest('checkLogin');
}

function ajax_logout() {
	ajax_doPost('logout', null, undefined, undefined, false);
}

function ajax_login() {
	
	var postArray = {
		'username'	: $("#loginUsername").val(),
		'password'	: $("#loginPassword").val()
	}
	
	var msgTitle = 'Be Patient';
	var msgBody = 'Please be patient while your request is verified.';

	show_checkingLogin();
	ajax_doPost('login', postArray, msgTitle, msgBody);
}


function ajax_successCallback(xmlData) {
	var xmlObj = parseXMLDoc(xmlData);
	var $xmlObj = $(xmlObj);
	if($xmlObj.find('callback_success').text()) {
		//call the callback function...
		var funcname = $xmlObj.find('callback_success').text();
		//TODO: figure out how to AVOID using eval() here...
		eval(funcname + '(xmlObj)');
	}
}

function do_redirect(xml) {
	document.location = '/';
}



function ajax_doPost(formName, postData, msgTitle, msgBody, isAsync) {
	if(msgTitle != undefined && msgTitle != null && msgTitle.length) {
		$.growlUI(msgTitle, msgBody);
	}
	
	if(isAsync == undefined) {
		isAsync = true;
	}
	
	var myUrl = "/ajax/" + formName;
	
	$.ajax({
		url: myUrl,
		type	: "POST",	
		data	: postData,
		timeout	: (30 * 1000),
		success	: ajax_successCallback
	});
}

$(document).ready(function() {
	ajax_checkLogin();
	autoUpdateWeatherImg();
});



//Code to pull _GET vars, from http://techfeed.net/blog/index.cfm/2007/2/6/JavaScript-URL-variables
function getURLVar(urlVarName) {
	//divide the URL in half at the '?'
	var urlHalves = String(document.location).split('?');
	var urlVarValue = '';
	if(urlHalves[1]){
		//load all the name/value pairs into an array
		var urlVars = urlHalves[1].split('&');
		//loop over the list, and find the specified url variable
		for(i=0; i<=(urlVars.length); i++){
			if(urlVars[i]){
				//load the name/value pair into an array
				var urlVarPair = urlVars[i].split('=');
				if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
					//I found a variable that matches, load it's value into the return variable
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	return urlVarValue;   
}



function updateImage(id) {
	var newTimestamp = new Date().getTime();
	if($("#" + id)) {
		var newImage = $("#" + id).attr('src');
		var imgBits = new Array();
		imgBits = newImage.split("\?");
		if(imgBits.length > 1) {
			newImage = imgBits[0];
		}
		newImage += "?_=" + new Date().getTime();
		$("#" + id).attr('src',newImage);
	}
	else {
		alert("Can't find image with id=(" + id +")");
	}
}
