var currentWidth = 0;
var animating = false;
var search = false;
var listingsClicked = false;
var gettingListingsData = false;

addEventListener('load', function(event) {
	setTimeout(preloadImages, 0);
	setTimeout(checkOrientAndLocation, 0);
	setInterval(checkOrientAndLocation, 300);
}, false);

addEventListener('unload', function(event) {
	var atags = document.getElementsByTagName('A');
	for (var i=0;i<atags.length; i++) {
		if (atags[i].hasAttribute('selected')) {
			atags[i].removeAttribute('selected');
		}
	}
}, false);

addEventListener('change', function(event) {
	if (event.target.nodeName == 'SELECT')
		window.location = 'http://' + location.host + event.target.value;
	else if(event.target.id == 'quoteInput')
		window.location = '/quotes/' + event.target.value;
	else
		submitForm(findParent(event.target, 'form'));
}, true);

addEventListener('focus', function(event) {
	if (event.target.id == 'quoteInput') event.target.value = '';
}, true);

addEventListener('blur', function(event) {
	if (event.target.id == 'quoteInput' && event.target.value == '') event.target.value = 'Enter Ticker Symbol...';
}, true);

function checkOrientAndLocation() {
	if (animating)
		return;
	if (window.innerWidth != currentWidth) {
		currentWidth = window.innerWidth;
		var orient = currentWidth == 320 ? 'profile' : 'landscape';
		document.body.setAttribute('orient', orient);
		setTimeout(scrollTo, 100, 0, 1);
	}
}

function preloadImages() {
	var preloader = document.createElement('div');
	preloader.id = 'preloader';
	document.body.appendChild(preloader);
}

function submitForm(form) {
	window.location = form.action + '?' + encodeForm(form).join('&');
}

function encodeForm(form) {
	function encode(inputs) {
		for (var i = 0; i < inputs.length; ++i) {
			if (inputs[i].name)
				args.push(inputs[i].name + '=' + escape(inputs[i].value));
		}
	}
	var args = [];
	encode(form.getElementsByTagName('input'));
	encode(form.getElementsByTagName('select'));
	return args;
}

function findParent(node, localName) {
	while (node && (node.nodeType != 1 || node.localName.toLowerCase() != localName))
		node = node.parentNode;
	return node;
}

function overlayBackground(i) {
	setTimeout(function() { scrollTo(0, 1); }, 0);
	var o = $('#overlay');
	o.css('background-position','center center, center center');
	o.css('background-repeat','no-repeat, no-repeat');
	$('#overlay').css('background-image','url(' + i + '),url(/i/loading_black.gif)');
}

function getListings() {
	if (!listingsClicked) {
		listingsClicked = true;
		navigator.geolocation.getCurrentPosition(getListingsSuccess, handleLocationError);
	}
}

function getListingsSuccess(position) {
	if (!gettingListingsData) {
		gettingListingsData = true;
		var r = '';
		$.getJSON('http://ws.geonames.org/findNearbyPostalCodesJSON?callback=?', {lat:position.coords.latitude, lng:position.coords.longitude, maxRows:1, style:'SHORT'}, function(data) {
			r += '<h1>FOX Business Channel</h1>';
			r += '<h3>Lat: ' + position.coords.latitude.toString().substring(0, 5) + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Long: ' + position.coords.longitude.toString().substring(0, 5) + '</h3>';
			$.getJSON('http://interactive.foxbusiness.com/projects/channel-finder/index.php?callback=?', {output:'json',zip:data.postalCodes[0].postalCode}, function(data) {
				r += '<ul>';
				$.each(data.result.items, function(i,item){
					r += '<li>'+item.headendName+' <span>Ch. '+item.channel+'</span></li>';
				});
				r += '</ul>';
				if (gettingListingsData && listingsClicked) { // we check these again to prevent getCurrentPosition lag/cache
					$('.main.listings').empty().append(r);
				}
				listingsClicked = false;
				gettingListingsData = false;
			});
		});
	}
}

function handleLocationError() {
	alert('Your location could not be determined');
	window.location = '/index.html';
}

function showAlert(t) {
	alert('Click \'OK\' below to play your ' + t + '.\n* This may take several seconds to load.\n* Once the ' + t + ' has finished, press the back arrow button to return.');
}

function videoPlayer(filename, a, b, c, d, e, f, g) {
	showAlert('video');
	document.location = 'http://' + location.host + '/media/' + filename + '_ref.mov';
}

function stockSearch(q) {
	window.location = '/index.html?type=quotes&id=' + q.toLowerCase();
}

$(document).ready(function() {
	$('#screen').toggle();
	$('#overlay').toggle();
	$('#search').toggle();
	$('a').click(function() {
		if ($(this).attr('href').indexOf('mailto:') < 0) {
			if ($(this).attr('id') == 'overlay' && !listingsClicked) {
				if (search) {
					search = false;
					$('#search').toggle();
				}
				$('#screen').toggle();
				$('#overlay').empty().toggle();
			} else if ($(this).attr('id') == 'searchButton') {
				search = search ? false : true;
				$('#search').toggle();
				$('#screen').toggle();
				$('#overlay').toggle();
			} else if ($(this).hasClass('back')) {
				history.go(-1);
			} else if ($(this).hasClass('debt-clock-info')) {
				window.location = '/disclaimer/index.html';
			} else if ($(this).attr('type') == 'external')
				window.open(link.attr('href'));
			else if ($(this).attr('type') == 'submit')
				submitForm($(this).parent('form'));
			else if ($(this).attr('type') == 'cancel')
				cancelDialog($(this).parent('form'));
			else if (!$(this).attr('target')) {
				$(this).attr('selected','progress');
				window.location = $(this).attr('href');
			}
		}
		return false;
	});
});
