$(document).ready(function(){
	var images = new Array('/img/assets/xo.gif', '/img/assets/loading.gif', '/img/assets/blue-bev.gif', '/img/assets/blue-bev-2.gif'); 
	for(var i=0; i<images.length; i++) {
		var img = new Image();
		img.src = images[i];
	}
	
	rsunpos();
	var int = self.setInterval(function(){
		rsuns(); rclocks(); rtimestamps(); rweather(); rsunpos();
	},10000);
	$(".fmap a").click(function() {
		var href = $(this).attr("href");
		$(this).parent().html('<iframe width="100%" height="150" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'+href+'&output=embed"></iframe>');
	});
	$("#email").keyup(function(){
		var email = $(this).val();
		if (email.match(/^[\w.-]+@[\w.-]+\.[a-z]{2,6}$/i)==null) {
			return false;
		}
		var jqxhr = $.get('/ajax/creds/?e='+email, function(data){
			var cred_fields = new Array('name', 'url', 'twitter_name');
			for(var i=0; i<cred_fields.length; i++) {
				var field_value_name = $(data).find(cred_fields[i]).text();
				if(field_value_name!='') {
					$("#"+cred_fields[i]).val(field_value_name);
				}
			}
		}, 'xml');
	});
});
function s_props() {
	var flashVer;
	if(!(flashVer = prettySwfVer())) {
		flashVer = 0;
	}
	var jqxhr = $.get('/ajax/props/?w='+screen.width+'&h='+screen.height+'&f='+flashVer, function(){});
	
}
function aRate(abc, xyz, tk, sid) {
	$("#the-stars").html('<img alt="Loading" src="/img/assets/loading.gif" width="16" height="16" />');
	var jqxhr = $.get('/ajax/stars/?rnum='+abc+'&aid='+xyz+'&tk='+tk+'&sid='+sid, function(data){
		$("#the-stars").html(data);
		$("#top-green").html('<div id="aad" class="info go">Thanks for rating!</div>');
		$("#top-green").show();
		$(".cta-rate").hide();
		var t = setTimeout(function(){
			$("#top-green").hide();
		},3000);
	}, "html");
}
function cRate(abc, def, tk, sid) {
	$("#thumbs-"+def).html('<img class="left" alt="Loading" src="/img/assets/loading.gif" width="16" height="16" /><span class="blind left thumbs-nh"></span><span class="blind left thumbs-nh" style="background-image: url(/img/assets/tdown.gif);"></span>');
	
	var jqxhr = $.get('/ajax/thumbs/?sign='+abc+'&cid='+def+'&tk='+tk+'&sid='+sid, function(data){
		$("#thumbs-"+def).html(data);
	}, "html");
}

/* ############################################ */
/*TWEET*/
function toggle_tweet(e) {
	var e = e.getElementsByTagName('span')[0];
	if(e.style.display=='inline') {
		e.style.display = 'none';
	} else {
		e.style.display = 'inline';
	}
}
function toggleLabel(fname, field, dr) {
	if(dr==0 && fname == field.value) {
		field.value = '';
	} else if(dr==1, field.value == '') {
		field.value = fname;
	}
}
var starPos = new Array();
function origStars() {
	for (var i = 1; i <= 5; i++) {
		starPos[i] = document.getElementById('s'+i).style.backgroundPosition;
	}
}
function setStars(curr) {
	var rest = 5 - curr;
	for (var i = 1; i <= curr; i++) {
		document.getElementById('s'+i).style.backgroundPosition = 'center top';
	}
	
	for (var i = curr+1; i <= curr+rest; i++) {
		document.getElementById('s'+i).style.backgroundPosition = 'center bottom';
	}
}
function clearStars() {
	for (var i = 1; i <= 5; i++) {
		document.getElementById('s'+i).style.backgroundPosition = starPos[i];
	}
}

function cReply(i, lev, url) {
	if(document.getElementById('reply-info')) {
		document.getElementById('reply-info').style.display = 'none';
	}
	
	url = '/articles/'+url+'/1'+i+'/#post';
	
	var e = document.getElementById('c'+i);
	var clear = document.getElementById('clear-'+i);
	var f = document.getElementById('the-form');
	
	var fe = f.childNodes[1];
	fe.setAttribute('action', url);
	
	document.getElementById('cancel-btn').style.display = 'inline';
	
	document.getElementById('email').parentNode.className = 'left';
	document.getElementById('twitter_name').parentNode.className = 'left';
	
	f.style.cssFloat = 'right';
	f.style.width = (lev == 1) ? '511px' : '541px';
	f.style.marginTop = '15px';
	f.style.paddingLeft = '32px';
	f.style.background = 'url(/img/assets/220.gif) left top repeat-y';
	
	e.insertBefore(f, clear);
}
function ccReply(url) {
	url = '/articles/'+url+'/#post';
	var clear = document.getElementById('post');
	var f = document.getElementById('the-form');
	
	var fe = f.childNodes[1];
	fe.setAttribute('action', url);
	
	document.getElementById('cancel-btn').style.display = 'none';
	
	document.getElementById('email').parentNode.className = 'right';
	document.getElementById('twitter_name').parentNode.className = 'right';
	
	f.style.cssFloat = 'none';
	f.style.width = '100%';
	f.style.marginTop = '0';
	f.style.paddingTop = '0';
	f.style.paddingLeft = '0';
	f.style.background = 'none';
	
	clear.parentNode.insertBefore(f, clear.nextSibling);
}
function validateForm(fizorm, fields) {
	var e = document.getElementById('imsg');
	var post_html;
	var errors = new Array();
	
	for (var i in fields) {
		if(fields[i] == 'name') {
			if(fizorm.name.value == '' || fizorm.name.value.match(/^name$/i)) {
				errors.push('Empty name');
			}
		} else if(fields[i] == 'email') {
			if(!fizorm.email.value.match(/^[\w.-]+@[\w.-]+\.[a-z]{2,6}$/i)) {
				errors.push('Invalid email');
			}
		} else if(fields[i] == 'url') {
			if(fizorm.url.value != '' && !fizorm.url.value.match(/^url$/i) && !fizorm.url.value.match(/^(http:\/\/)?([\w.-]+\.[a-z]{2,6})(\/|\/(\S*))?$/i)) {
				errors.push('Invalid URL--Erase to eliminate');
			}
		} else if(fields[i] == 'twitter_name') {
			if(fizorm.twitter_name.value != '' && !fizorm.twitter_name.value.match(/^twitter id$/i) && !fizorm.twitter_name.value.match(/^[a-z\d_]+$/i)) {
				errors.push('Invalid Twitter ID--Erase to eliminate');
			}
		} else if(fields[i] == 'message') {
			if(fizorm.message.value == '' || fizorm.message.value.match(/^message$/i)) {
				errors.push('Empty message');
			}
		} else if(fields[i] == 'shield') {
			if(parseInt(fizorm.shield.value) != new Date().getDate()) {
				errors.push('Invalid date provided');
			}
		} else if(fields[i] == '') {
			errors.push('Empty '+fields[i]);
		}
	}
	
	if(errors.length == 0) {
		return true;
	} else {
		post_html = '<div class="info stop">Please validate any information below before continuing.<ul>';
		for(i=0; i<errors.length; i++) {
			post_html += '<li>'+errors[i]+'</li>';
		}
		post_html += '</ul></div>';
		e.innerHTML = post_html;
		return false;
	}
}

function get_speed() {	
	var imageAddr = '/tools/system-info/image.jpg?n='+Math.random();
	var startTime, elapsedTime;
	var fileSize = 505544;
	
	var theImage = new Image();
	theImage.onload = function() {
		elapsedTime = new Date().getTime()/1000-startTime;
		showResults();
	}
	
	var startTime = new Date().getTime()/1000;
	theImage.src = imageAddr;
	
	function showResults() {
		var byteps = 1/elapsedTime*fileSize;
		var mbitps = byteps/131072;
		var mbyteps = byteps/1048576;
		
		var theHTML = mbitps.toFixed(2)+' Mb/s ('+mbyteps.toFixed(2)+' MB/s)';
		var fileTypes = new Array('MP3 File (5 MB)', 'Video Clip (35 MB)', 'Movie (800 MB)');
		var fileSizes = new Array(5242880, 36700160, 838860800);
		
		for(var i=0; i<fileTypes.length; i++) {
			var dTime = fileSizes[i]/byteps;
			var units = 'sec';
			if(dTime>3600) {
				dTime /= 3600;
				units = 'hours';
			} else if(dTime>60) {
				dTime /= 60;
				units = 'min';
			}
			dTime = Math.ceil(dTime);
			theHTML += '<br />'+fileTypes[i]+': '+dTime+' '+units;
		}
		theHTML += '<br /><a onclick="this.innerHTML=\'<img alt=&quot;Loading&quot; src=&quot;/img/assets/loading.gif&quot; width=&quot;16&quot; height=&quot;16&quot; />\'; get_speed();" style="cursor: pointer;">Reload</a>';
		
		document.getElementById('conn_speed').innerHTML = theHTML;
	}
}

/////////////////////////////////////////////////
///////////// DATES /////////////////////////////
//var g_time_format = 24;
//var g_date_format = 'DMY';
function rweather() {
	$(".rweather").each(function(i, e) {
		var now = toSecs(new Date().getTime());
		var eid = e.id;
		
		var loc = eid.match(/^[^\-]+/).toString().replace(/___/g, ',').replace(/[^,a-z\d]+/ig, '+');
		var size = eid.match(/s[a-z]+/i).toString().replace(/^s/, '');
		var fresh = parseInt(eid.match(/p\-?\d+/).toString().replace(/[^\-\d]/g, ''));
		var exp = fresh+900;
		
		if((fresh && now<fresh) || (exp && now>=exp)) {
			var jqxhr = $.get('/tools/weather/info/?l='+loc+'&s='+size, function(data) {
				var root = $(data).children(":first");
				var current_conds = $(root).children("current_conditions");
				
				var n_fresh = $(root).attr("fresh");
				var date = $(root).attr("date");
				var unit = $(root).attr("unit");
				
				n_fresh = ((n_fresh && now < n_fresh) || (n_fresh && now >= n_fresh)) ? now : n_fresh;
				e.id = eid.replace(/p\-?\d+/, 'p'+n_fresh);
				
				$(root).children("current_conditions").children().each(function(){
					var name = this.nodeName;
					var val = $(this).text();
					var n = $(e).find(".current");
					if(name=='icon') {
						$(n).find("."+name).attr("src", val);
					} else if(name=='temp') {
						$(n).find("."+name).html(val+'&deg;'+unit);
					} else {
						$(n).find("."+name).text(val);
					}
				});
				
				$(root).children("forecast_conditions").children().each(function(i){
					$(this).children().each(function(){
						var name = this.nodeName;
						var val = $(this).text();
						
						var n = $(e).find(".condition").eq(i);
						if(name=='icon') {
							$(n).find("."+name).attr("src", val);
						} else if(name=='high'||name=='low') {
							$(n).find("."+name).html(val+'&deg;'+unit);
						} else {
							$(n).find("."+name).text(val);
						}
					});
				});
				
				
				$(e).find(".rtimestamp").attr("id", function(x, val) {
					val = val.replace(/^\-?\d+/, date);
					return val;
				});
				rtimestamps();
			}, 'xml')
			.error(function() {
				var eid = e.id
				eid = eid.replace(/p\-?\d+/, 'p'+now);
				e.id = eid;
			});
		}
	});
}
function rclocks() {
	$(".rclock").each(function(i, e) {
		var now = toSecs(new Date().getTime());
		var eid = e.id;
		
		var zone = eid.match(/z.+/).toString().replace(/^z/, '').replace(/___/g, '/');
		var type = eid.match(/^[a-z]+/);
		var small = (eid.match(/s1/)!=null) ? true : false;
		var abbv = eid.match(/a[a-z]+/i).toString().replace(/^a/, '');
		var offset = parseInt(eid.match(/o\-?\d+/).toString().replace(/[^\-\d]/g, ''));
		var pre_ts = (eid.match(/p\-?\d+/)!=null) ? parseInt(eid.match(/p\-?\d+/).toString().replace(/[^\-\d]/g, '')) : false;
		var next_ts = (eid.match(/n\-?\d+/)!=null) ? parseInt(eid.match(/n\-?\d+/).toString().replace(/[^\-\d]/g, '')) : false;
		var is_dst = (eid.match(/d\d/)!=null) ? parseInt(eid.match(/d\d/).toString().replace(/\D/g, '')) : 'x';
		is_dst = (!is_dst && next_ts) ? 2 : is_dst;
		
		if((pre_ts && now<pre_ts) || (next_ts && now>=next_ts)) {
			var jqxhr = $.get('/tools/time/zone-info/?z='+zone+'&t='+now, function(data) {
				
				var zone = $(data).find('info').text();
				zone = zone.replace(/\//g, '___');
				var n_abbv = $(data).find('offset').attr('abbv');
				var n_offset = parseInt($(data).find('offset').text());
				var n_is_dst = parseInt($(data).find('offset').attr('is_dst'));
				var n_pre_ts = parseInt($(data).find('pre_ts').text());
				var n_next_ts = parseInt($(data).find('next_ts').text());
				n_pre_ts = (n_pre_ts && now < n_pre_ts) ? now : n_pre_ts;
				n_next_ts = (n_next_ts && now >= n_next_ts) ? now+900 : n_next_ts;
				n_is_dst = (!n_is_dst && n_next_ts) ? 2 : n_is_dst;
				
				e.id = e.id.replace(/a[A-Z]+/, 'a'+n_abbv);
				e.id = e.id.replace(/o\-?\d+/, 'o'+n_offset);
				e.id = e.id.replace(/d\d/, 'd'+n_is_dst);
				e.id = e.id.replace(/p\-?\d+/, 'p'+n_pre_ts);
				e.id = e.id.replace(/n\-?\d+/, 'n'+n_next_ts);
				
				var la = (offset < n_offset) ? "&rarr; " : "&larr; ";
				var na = (offset < n_offset) ? "&larr; " : "&rarr; ";
				
				$('.pts'+zone+' .arrow').html(la+' ');
				$('.pts'+zone+' .rtimestamp').attr('id', function(i, val) {
					val = val.replace(/^\-?\d+/, next_ts-1);
					val = val.replace(/[A-Z]+/, abbv);
					val = val.replace(/\-?\d+$/, offset);
					return val;
				});
				$('.nts'+zone+' .arrow').html(na+' ');
				$('.nts'+zone+' .rtimestamp').attr('id', function(i, val) {
					val = val.replace(/^\-?\d+/, n_next_ts-1);
					val = val.replace(/[A-Z]+/, n_abbv);
					val = val.replace(/\-?\d+$/, n_offset);
					return val;
				});
				
				rtimestamps();
			}, 'xml')
			.error(function() {
				e.id = e.id.replace(/p\-?\d+/, 'p'+now);
				e.id = e.id.replace(/n\-?\d+/, 'n'+(now+900));
			});
		}
		
		var date = date_string(type.toString(), now, offset, abbv, is_dst, small);
		$(this).html(date);
	});
}
function rtimestamps() {
	$(".rtimestamp").each(function(i,e) {
		var eid = e.id;
		var unix = parseInt(eid.match(/^\-?\d+/));
		var date = (eid.indexOf('d')!=-1) ? true : false;
		var alt = (eid.indexOf('a')!=-1) ? true : false;
		var bold = (eid.indexOf('b')!=-1) ? true : false;
		var small = (eid.indexOf('s')!=-1) ? true : false;
		
		var offset = parseInt(eid.match(/\-?\d+$/));
		var abbv = eid.match(/\-[a-z]+/i).toString().replace(/[^a-z]/ig, '');
		var rel = relative_timestamp(unix, null, date, alt, bold, offset, abbv, small);
		$(this).html(rel);
	});
}
function rsuns() {
	$(".rsun").each(function(i,e) {
		var now = toSecs(new Date().getTime());
		var eid = e.id;
		
		var zone = (eid.match(/z.+/)!=null) ? eid.match(/z.+/).toString().replace(/^z/, '').replace(/___/g, '/') : '';
		var ll_string = eid.match(/\-?[_\d]+x\-?[_\d]+/);
		var lat = eid.match(/\-?[_\d]+x/).toString().replace(/_/g, '.').replace(/[^\-\d\.]/g, '');
		var long = eid.match(/x\-?[_\d]+/).toString().replace(/_/g, '.').replace(/[^\-\d\.]/g, '');
		var fresh = parseInt(eid.match(/p\-?\d+/).toString().replace(/[^\-\d]/g, ''));
		var exp = parseInt(eid.match(/n\-?\d+/).toString().replace(/[^\-\d]/g, ''));
		
		if((fresh && now<fresh) || (exp && now>=exp)) {
			var jqxhr = $.get('/tools/time/sun-info/?lat='+lat+'&long='+long+'&t='+now+'&z='+zone, function(data) {
				// 0=>TIMESTAMP, 1=>ALT, 2=>TYPE, 3=>ICON, 4=>ABBV, 5=>OFFSET
				var sun_ids = new Array("past", "future");
				var regexs = new Array(/p\-?\d+/, /n\-?\d+/);
				var calls = new Array("p", "n");
				var selectors = new Array(".sun-fresh", ".sun-exp");
				for(var i=0; i<sun_ids.length; i++) {
					var sun = $(data).find(sun_ids[i]+" sun:first");
					var sun_info = new Array($(sun).text(), $(sun).attr("alt"), $(sun).attr("type"), $(sun).attr("icon"), $(sun).attr("abbv"), $(sun).attr("offset"));
					var error = false;
					if(i===0 && (sun_info[0] && now < sun_info[0])) {
						sun_info[0] = now;
						error = true;
					} else if(i===1 && (sun_info[0] && now >= sun_info[0])) {
						sun_info[0] = now+900;
						error = true;
					}
					e.id = e.id.replace(regexs[i], calls[i]+sun_info[0]);
					if(error) {
						return;
					}
					////////////////////////
					$(e).find(selectors[i]+" .sun_moon").attr("title",  sun_info[1]);
					$(e).find(selectors[i]+" .sun_moon").attr("src", sun_info[3]);
					$(e).find(selectors[i]+" .type").text(sun_info[2]+": ");
					$(e).find(selectors[i]+" .rtimestamp").attr("id", function(x, val) {
						val = val.replace(/^\-?\d+/, sun_info[0]);
						val = val.replace(/[A-Z]+/, sun_info[4]);
						val = val.replace(/\-?\d+$/, sun_info[5]);
						return val;
					});
				}
				rtimestamps();
			}, 'xml')
			.error(function() {
				var eid = e.id
				eid = eid.replace(/p\-?\d+/, 'p'+now);
				eid = eid.replace(/n\-?\d+/, 'n'+(now+900));
				e.id = eid;
			});
		}
	});
}
function date_string(type, stamp, offset, abbv, is_dst, small) {
	var now = toSecs(new Date().getTime());
	stamp = parseInt(stamp);
	stamp = (!stamp) ? now : stamp;
	stamp += offset;
	
	var date = new Date(toMilli(stamp));
	
	var time = (g_time_format==12) ? mHour(date.getUTCHours(), date.getUTCMinutes()) : fHour(date.getUTCHours(), date.getUTCMinutes());
	time += (small) ? ' <span class="small">'+abbv+'</span>' : ' '+abbv;
	var day = date.getUTCDayName();
	var short_day = date.getUTCDayName(true);
	var month = (g_date_format=='MDY') ? date.getUTCMonthName()+' '+date.getUTCDate() : date.getUTCDate()+' '+date.getUTCMonthName();
	var year = (g_date_format=='MDY') ? month+', '+date.getUTCFullYear() : month+' '+date.getUTCFullYear();
	var full = day+', '+year+' - '+time;
	
	var string;
	type = type.toLowerCase();
	type = type.replace(/\s/g, '');
	
	var is_ptype = (type.match(/p$/)!=null) ? true : false;
	var ptype = type.replace(/p$/, '');
	switch(ptype) {
		case 'time':
			string = time;
			break;
		case 'timed':
			string = short_day+'. '+time;
			break;
		case 'day':
			string = day;
			break;
		case 'month':
			string = month;
			break;
		case 'year':
			string = year;
			break;
		case 'full':
			string = full;
			break;
		default:
			string = full;
	}
	
	if(is_ptype) {
		string = (small) ? string+'<span class="small"> ('+pretty_offset(offset)+')</span>' : string;
	}
	
	if(is_dst && is_dst!='x') {
		var colors = new Array('#0f0f0f', '#804020', '#204080');
		string = '<span style="color:'+colors[is_dst]+'">'+string+'</span>';
	}
	return string;
	
}
function relative_timestamp(to, from, show_date, alt, bold, offset, abbv, small) {
	var now = toSecs(new Date().getTime());
	var past = '';
	var future = '';
	var string = '';
	var prep = 'at';
	var date = date_string('time', to, offset, abbv, null, small);
	
	to = parseInt(to);
	from = parseInt(from);
	to = (!to) ? now : to;
	from = (!from) ? now : from;
	if(from > to) { past = ' ago'; } else { future = 'in '; }
	var seconds = Math.abs(to-from);
	
	var values = new Array(31556926, 2629743.83, 604800, 86400, 3600, 60);
	var labels = new Array('year', 'month', 'week', 'day', 'hour', 'minute');
	var patterns = new Array('year', 'month', 'month', 'day', 'time', 'time');
	var preps = new Array('on', 'on', 'on', 'on', 'at', 'at');
	for(var i=0; i<values.length; i++) {
		var value = values[i];
		value = seconds/value;
		if(value >= 1) {
			value = (i===0) ? Math.round(value*10)/10 : Math.round(value);
			
			value = add_commas(value);
			var label = labels[i];
			label = (value == 1) ? label : label+'s';
			date = date_string(patterns[i], to, offset, abbv, null, small);
			prep = preps[i];
			
			string = future+value+' '+label+past;
			if(bold) {
				string = '<b>'+string+'</b>';
			}
			if(show_date) {
				string += ' '+prep+' '+date;
			}
			if(alt) {
				string = '<span title="'+date_string('full', to, offset, abbv)+'">'+string+'</span>';
			}
			break;
		}
	}
	
	if(string=='') {
		string = future+'less than a minute'+past;
		if(bold) {
			string = '<b>'+string+'</b>';
		}
		if(show_date) {
			string += ' '+prep+' '+date;
		}
		if(alt) {
			string = '<span title="'+date_string('full', to, offset, abbv)+'">'+string+'</span>';
		}
	}
	
	
	return string;
}










function rsunpos() {
	$(".rsunpos").each(function() {
		var eid = $(this).attr("id");
		eid = eid.toString();
		
		var lat = parseFloat(eid.match(/\-?[_\d]+x/).toString().replace(/_/g, '.').replace(/[^\-\d\.]/g, ''));
		var long = parseFloat(eid.match(/x\-?[_\d]+/).toString().replace(/_/g, '.').replace(/[^\-\d\.]/g, ''));
		
		var sun_pos = sun_position(lat, long);
		$(this).html('Azimuth: '+sun_pos[0].toFixed(3)+'&deg;<br />Zenith: '+sun_pos[1].toFixed(3)+'&deg;<br />Elevation: '+sun_pos[2].toFixed(3)+'&deg;');
	});
}
