/* common.js */
/* Notes
1. html gets js class from modernizr.js - we used to do that in here on the body tag
*/

// Page Initialization (for body onload event)
$(document).ready(function() {
	
	// Fade out some messages
	$('#message h2').addClass('clickable').attr('title', 'Click to close').click(function(){
		$('#message').fadeOut(800);
	});

	// Check if forms.js is loaded
	var scripts = document.getElementsByTagName('script');
	if(scripts.length>0) {
		for(var i=0; i<scripts.length; i++) {
			if(scripts[i].src.toLowerCase().indexOf('forms.js')>=0) {
				// Create the onsubmit event
				$('form').submit(function(event){
					return validateForm($(this).id);
				});
			}
		}
	}
	
	// Account settings expaning link
	var account_link_toggle = $('#account_links>a');
	account_link_toggle.click(function(event){
		event.preventDefault();
		$('#account_links div').toggleClass('open');
		$('#account_links div').css({
			'z-index': 10000
		})
	});


	// External Link
	var links = document.getElementsByTagName('a');
	var domain = window.location.hostname;
	for(var i=1; i<links.length; i++) {
		if(links[i].href.toLowerCase().indexOf('javascript:')==-1 && !links[i].href.match(domain)) {
			links[i].target = "_blank";
			links[i].title += " (New Window)";
		}
	}


	// Search Form
	$('#search_form').submit(function(event) {
		if($('#search_string').val() == '') {
			return false;
		}
	});


	// Table row item links
	$('tr').each(function(){
		var anchors = $(this).find('a');
		if(anchors.length==1) {
			$(this).click(function(){window.location.href=this.getElementsByTagName('a')[0].href; return false;});
			$(this).addClass('clickable');
		}
	});


	// Disable form elements inside .disabled
	$('.disabled input, .disabled textarea, .disabled select').attr('disabled', 'disabled');


	// a.close
	$('a.close').click(function(event){
		event.preventDefault();
		$(this).parent().slideUp('slow');
	});


	// Row Totals
	$('tr td input').change(function(){
		var total = 0;
		if($(this).attr('type') == 'checkbox') {
			$(this).parent().parent().find('td input:checked').each(function(){
				total += $(this).val() *1;
			});
		} else {
			$(this).parent().parent().find('td input').each(function(){
				total += $(this).val() *1;
			});
		}
		
		$(this).parent().parent().find('td:last').html(total);
	});


	// tr.row_hover
	$('.scorecard_display tr').hover(function(){$(this).addClass('row_hover');}, function(){$(this).removeClass('row_hover');});


	// Toggle links
	$('a.quick-login').click(function(event){
		event.preventDefault();
		$('form.login_inline').slideToggle('slow');
	});

	// Overlays
	$('a.overlay_trigger').click(function(event){
		event.preventDefault();
		$('.ie7 #sidebar').fadeOut('slow');
		$($(this).attr('href')).fadeIn('slow').addClass('clickable').click(function(event){
			event.preventDefault();
			$(this).fadeOut('slow').removeClass('clickable');
			$('.ie7 #sidebar').fadeIn('slow');
		});
	});
	
	// Let the escape key hide overlays
	$(document).keyup(function(event) { 
		if (event.which == 27) {
			$('.overlay').fadeOut('slow');
			$('.ie7 #sidebar').fadeIn('slow');
		}
	});
	
	$('.scorecard_entry th:first-child').addClass('clickable').click(function(event){
		event.preventDefault();
		$('#scorecard-tips').fadeIn('slow').click(function(event){
			event.preventDefault();
			$(this).fadeOut('slow');
		});
	});

	// Date Pickers
	if($.datepicker) {
		$.datepicker.setDefaults({
			dateFormat: 'yy-mm-dd',
			maxDate: '+0m +0w',
			nextText: '>>',
			prevText: '<<'
		});
		$('#practice_date, #dateplayed').datepicker();
	}

	// Accordians
	$('.accordian').next().hide();
	$('.accordian').addClass('clickable');
	$('.accordian').click(function(event){
		event.preventDefault();
		$(this).next().slideToggle();
		$(this).hasClass('accordian_close') ? $(this).removeClass('accordian_close') : $(this).addClass('accordian_close');
	});

	// Anchor scrolling
	$(document).ready(function(){
		$('a[href^="#"]').not('.overlay_trigger').click(function(event){
			$(this).closest('nav').find('li a').removeClass('current');
			$(this).addClass('current');
			//prevent the default action for the click event
			event.preventDefault();
	
			var trgt = this.href.split('#')[1];
	
			//get the top offset of the target anchor
			var target_offset = $("#"+trgt).offset();
	
			$('html, body').animate({scrollTop:target_offset.top}, 500);
		});
	});
	
	// Location Picker
	var countryPicker = $('#country_picker');
	var provincePicker = $('#province_picker');
	var currentCountry = $('#current_country');
	var currentCountryLink = $('#current_country a');
	var currentProvince = $('#current_province');
	var currentProvinceLink = $('#current_province a');
	var locationList = $('#locations');
	var countryLinks = $('#locations>li a');
	var provinceLinks = $('#locations ul li a');
	
	currentCountryLink.click(function(event){
		event.preventDefault();
		countryPicker.toggleClass('open');
	});
	
	currentProvinceLink.click(function(event){
		event.preventDefault();
		provincePicker.toggleClass('open');
	});
	
	// Bar Charts on Stats Tables
	var statTables = $('.rowtable.stats');
	var statCells;
	var maxStatVal;
	
	statTables.each(function(i){
		if(i==0) { // Cumulative stats
			$(this).addClass('bar-chart');
			statCells = $(this).find('td');
			maxStatValue = 0;

			statCells.each(function(){
				if(($(this).text() * 1) > maxStatValue) {
					maxStatValue = $(this).text() * 1;
				}
			});
		
			statCells.each(function(){
				newWidth = (100 * $(this).text()) / maxStatValue;
				$(this).wrapInner('<div style="width:' + newWidth + '%"/>');
			});
		}
		
		if(i==1) {  // Per round stats
			$(this).addClass('bar-chart');
			statCells = $(this).find('td');
			maxStatValue = 0;

			statCells.each(function(j){
				if(j<4) { // Stats related to total strokes
					if(($(this).text() * 1) > maxStatValue) {
						maxStatValue = $(this).text() * 1;
					}
				}
			});
		
			statCells.each(function(k){
				if(k<4) { // Stats related to total strokes
					newWidth = (100 * $(this).text()) / maxStatValue;
					$(this).wrapInner('<div style="width:' + newWidth + '%"/>');
				} else { // Stats related to strokes per hole
					newWidth = (100 * $(this).text()) / 18;
					$(this).wrapInner('<div style="width:' + newWidth + '%"/>');
				}
			});
		}
	});
	
	// Slideshow
	var slideshow = $('.js .slideshow');
	var slides = slideshow.find('figure');
	
	slideshow.append('<div class="shim"></div><p class="counter"><span>1</span> of ' + slides.length + '</p>').css({
		position: 'relative'
	});
	
	var shim = slideshow.find('.shim');
	var counter = slideshow.find('.counter span');
	shim.css({
		position: 'absolute',
		top: '0',
		left: '0',
		'z-index': '0',
		width: '1px',
		background: 'transparent',
		height: slides.first().height()
	});
	if(slides.length > 1) {
		slides.addClass('clickable').click(function(event){
			event.preventDefault();
			var nextIndex = slides.index($(this).next());
			// alert(slideIndex);
			if(nextIndex == -1) {
				$(this).fadeOut(800);
				slides.first().delay(800).fadeIn();
				counter.text('1');
			} else {
				$(this).fadeOut(800);
				$(this).next('figure').delay(800).fadeIn();
				counter.text(parseInt(counter.text()) + 1);
			}
		});
	}

	// nth-child support
	$('.ie .new-user #content section > section:nth-child(2n+1)').addClass('odd');
	$('.ie .new-user #content section > section:nth-child(2n)').addClass('even');

	// Save location
	var locationSaver = $('#save-location');
	var country = $('#current_country a').text();
	var province = $('#current_province a').text();
	var ajaxForm = $('#ajaxLocationForm');
	locationSaver.click(function(event){
		event.preventDefault();
		$('#home_country').val(country);
		$('#home_province').val(province);
		var ajaxFormData = ajaxForm.serialize();
		$.post('/account/ajax_save_preferences', ajaxFormData, function(data){
			console.log('callback called');
			console.log(data);
		})
		.success(
			function(){
				console.log('success');
				locationSaver.text('saved...').fadeOut('5000');
				ajaxForm.remove();
			}
		)
		.error(
			function(){
				console.log('error');
				locationSaver.text('error: not saved...').fadeOut('5000');
			}
		)
		.complete(
			function(){
				console.log('complete');
			}
		);
	});

});

// Pop-up functions
function popUp(uri, x, y, mode) {
	if(!x) { x=800; }
	if(!y) { y=600; }

	if(!mode || mode == 'dialog') {
		var opts = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,width='+x+',height='+y+',bgcolor=#cccccc';
	} else if(mode == 'normal') {
		var opts = 'toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+x+',height='+y+',bgcolor=#cccccc';
	}

	if(window.open(uri,'Project Birdie Pop Up',opts)) {
		return false;
	} else {
		return true;
	}
}
