var market = {
	timer: null,
	effectDuration: 3000,
	initialLoad: true
};
var numErrors = 0;

$(document).ready(function() {
	
	// Ads
	if (typeof(MAX_output) != 'undefined') {
		$('.ad-zone').each(function() {
			var zoneId = $.trim($(this).find('span').text());
			if (typeof(MAX_output[zoneId]) != 'undefined') {
	            $(this).html(MAX_output[zoneId]);
	        }
		});
	}
	
	$('.ad-zone:empty').remove();
	
	// Market
	if (settings.market.polling && ($('#market-data').length > 0)) {
		market.timer = window.setInterval(updateMarket, settings.market.interval);
	}
	
	// Opinions, features, ideas tabs
	$('#block-features .block-tabs > div').click(function() {
		if ($(this).hasClass('inactive')) {
			$(this).siblings().removeClass('active').addClass('inactive');
			$(this).removeClass('inactive').addClass('active');
			$('#block-features div.feature-type').hide();
			$('#' + $(this).attr('id').replace(/^feature-tab-/g, "feature-content-")).show();
		}
		Cufon.replace('.block-tabs .tab-center');
	});
	
	// Search
	$('.text-input-caption').each(function() {
		var defaultSearchText = $(this).val();
		$(this).focus(function() {
			if ($(this).val() == defaultSearchText) {
				$(this).addClass('black').val('');
			}
		}).blur(function() {
			if ($.trim($(this).val()) == '') {
				$(this).removeClass('black').val(defaultSearchText);
			}
		});
		$(this).closest('form').find('a').click(function() {
			$(this).closest('form').submit();
		});
	});
	
	if ($('#earlier-news-btn').length > 0) {
    	$('#earlier-news-btn').date_input({
    	    selectDate: function(date) {
                if (typeof(date) == "undefined") {
                  date = this.stringToDate(this.input.val());
                };
                var init = false;
                if (!date) {
                    var init = true;
                    date = new Date();
                }
                
                this.selectedDate = date;
                this.selectedDateString = this.dateToString(this.selectedDate);
                this.selectMonth(this.selectedDate);
                if (!init) {
                	showLoadingModal('Loading archives&hellip;');
                    var url = settings.baseUrl + '/archive/' + this.selectedDateString;
                    window.location.href = url; 
                }
              }
    	});
	}
	
	// Manage account loading modal
	$('#manage-account-top').click(function() {
	    showLoadingModal('Retrieving your information&hellip;');
	});
	
	/*
	var archiveCalendarParams = {
		position: {
			corner: {
				target: 'bottomRight',
				tooltip: 'topRight'
			},
			adjust: { x: 4, y: 3 }
		},
		style: {
			width: 204,
			border: {
				width: 0
			},
			classes: {
				content: 'qtip-calendar'
			}
		},
		show: {
			when: {
				event: 'focus'
			}
		},
		hide: {
			when: {
				event: 'unfocus'
			}
		},
		api: {
			onShow: function(){
				$('.qtip-calendar').datepicker({
					maxDate: 0,
					onSelect: function(dateText, inst) {
						var url = settings.baseUrl + '/archive/' + dateText.substr(6, 4) + '/' + dateText.substr(0, 2) + '/' + dateText.substr(3, 2);
						window.location.href = url; 
					}
				});
			},
			beforeDestroy: function(){
				$('.qtip-calendar').datepicker('destroy');
			}
		}
	};
	
	
	// Earlier News
	$('#earlier-news-btn').qtip(archiveCalendarParams);
	$('#archive-nav div.center a').qtip($.extend(archiveCalendarParams, {
		position: {
			corner: {
				target: 'bottomMiddle',
				tooltip: 'topMiddle'
			},
			adjust: { x: 0, y: 6 }
		}
	}));
	*/
	
	// Our Take
	$('a.our-take').qtip({
		position: {
			corner: {
				target: 'rightMiddle',
				tooltip: 'leftMiddle'
			}
		},
		style: {
			name: 'cream',
			tip: 'leftMiddle',
			fontSize: '12px',
			width: 300,
			classes: {
				content: 'our-take-tip'
			}
		},
		api: {
			onRender: function()
			{
				this.updateContent('<h4>Our Take</h4>' + this.elements.target.next().html());
			}
		}
	});
	
	// Forms
	$('form input[title], form select[title]').each(function() {
		$(this).qtip({
			content: $(this).attr('title'),
			position: {
				corner: {
					target: 'leftMiddle',
					tooltip: 'rightMiddle'
				}
			},
			style: {
				name: 'dark',
				tip: 'rightMiddle',
				fontSize: '11px',
				width: { max: 300 }
			},
			show: {
				when: {
					event: 'focus'
				}
			},
			hide: {
				when: {
					event: 'blur'
				}
			}
		});
		$(this).removeAttr('title');
	});
	
	// Register Reminder
	$('#register-reminder .close a').click(function() {
		$(this).closest('#register-reminder').slideUp();		
	});
	
	// Loading Modal
   $('body').qtip(
   {
      content: {
         text: ''
      },
      position: {
         target: $(document.body), // Position it via the document body...
         corner: 'center' // ...at the center of the viewport
      },
      show: {
         when: false,
         solo: true // And hide all other tooltips
      },
      hide: false,
      style: {
	  	 'font-size': '16px',
		 'font-weight': 'bold', 
         width: 300,
         padding: '14px',
         border: {
            width: 3,
            radius: 3,
            color: '#666666'
         },
         name: 'light'
      },
      api: {
         beforeShow: function()
         {
            // Fade in the modal "blanket" using the defined show speed
            $('#qtip-blanket').fadeIn(this.options.show.effect.length);
         },
         beforeHide: function()
         {
            // Fade out the modal "blanket" using the defined hide speed
            $('#qtip-blanket').fadeOut(this.options.hide.effect.length);
         }
      }
   });

	// Preload loading image
	var preloadImg = document.createElement('img');
	preloadImg.src = settings.baseUrl + '/images/global/loading.gif';
	
	// Create the modal backdrop on document load so all modal tooltips can use it
   $('<div id="qtip-blanket">')
      .css({
         position: 'absolute',
         top: $(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
         left: 0,
         height: $(document).height(), // Span the full document height...
         width: '100%', // ...and full width

         opacity: 0.3, // Make it slightly transparent
         backgroundColor: '#000000',
         zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
      })
      .appendTo(document.body) // Append to the document body
      .hide(); // Hide it initially
	
});

function showLoadingModal(text)
{
	var loadingImg = '<span class="loading-ani"><img src="' + settings.baseUrl + '/images/global/loading.gif" alt="" /></span>';
	$('body').qtip('api').updateContent(loadingImg + text).show();
}

function hideLoadingModal()
{
	$('body').qtip('hide');
}

function updateMarket()
{
	$.post(settings.baseUrl + '/', {
		action: 'getMarket'
	}, function(data, textStatus) {
		var body = $('#market-data').find('tbody');
		var oldHtml = body.html();
		body.empty();
		$.each(data.indices, function() {
			var row = $('<tr>').addClass(this.className);
			row.append(	$('<td>').addClass('symbol').append( $('<a>').attr('href', this.link).text(this.index) ) );
			row.append( $('<td>').addClass('last').text(this.last) );
			row.append( $('<td>').addClass('change').text(this.change + ' (' + this.pct + ')') );
			body.append(row);
		});
		if ((oldHtml != body.html()) && !market.initialLoad) {
			if (body.effect) {
				body.effect('highlight', {}, market.effectDuration);
			}
		}
		$('#market-data').parent().find('div.disclaimer span').text('Updated ' + data.updated);
		market.initialLoad = false;
	}, 'json');
}

function getNumericId(str)
{
	var result = str.match(/\d+$/ig);
	return result[0];
}

function smoothScrollTo(obj, duration)
{
	if (duration == undefined) {
		duration = 1000;
	}
	$('html, body').animate({
		scrollTop: $(obj).offset().top
	}, duration)
}

/* Registration / Manage Account Validation Functions */

function getLabel(obj) {
	var label = $(obj).parent().parent().find('label').text().toLowerCase();
	return label.substring(0, label.length-1);
}

function writeSuccess(obj, showCheck){
	$('#' + $(obj).attr('id') + '-error').remove();
	var row = $(obj).closest('tr');
	$(row).removeClass('error');
	if (showCheck == true) {
		$(row).addClass('success');
	} else {
		$(row).removeClass('success');
	}
	return true;
}

function writeError(obj, errorMsg)
{
	$('#' + $(obj).attr('id') + '-error').remove();
	$(obj).closest('tr').addClass('error').after($('<tr/>').attr({id: obj.attr('id') + '-error', className: 'error-msg'}).append($('<td/>')).append($('<td/>').html(errorMsg)));
	numErrors++;
	return false;
}
