var margin = 20; // partner slide margin

$(document).ready(function() {

	$('#tabs').show();
	
	var current_tab;
	var moveSlideQty = 6;
	
	var slider = $('.bx-slider').bxSlider({
		pager: false,
		controls: false,
		easing: 'easeOutCirc',
        speed: 800
	});
	
	$('bx-window').addClass('slider-height');
	
	$('.bxslider-thumbnails').bxSlider({
		displaySlideQty: 6,
        moveSlideQty: moveSlideQty, 
        infiniteLoop: false, 
        wrapperClass: 'test',
        hideControlOnEnd:true,
        easing: 'easeOutCirc',
        speed: 800,
        pager: false
	});
	
	$('#tabs-3').live('click', function(){
		var link = $('#monitor_link_3').val();
		$(location).attr('href',link);
	});
	
	$('.bxslider-thumbnails a').click(function(){
 			slider.goToSlide($('.bxslider-thumbnails a').index($(this)) - moveSlideQty); 
			return;
	});
	
	// Tabs startsida
	var taber = $( "#tabs" ).tabs({
		selected: 1,
		show: function(event, ui) {
       		current_tab = ui.index;  //set the new previous tab index to the current index 	
       		get_tab_image(current_tab);
   		}
   	}).tabs("rotate",15000, false);
   	
   	// Tabs proffstränare
   	$('#tabs-tranare').tabs();

	// start flash
	if($('#start-flash').length) {
		swfobject.embedSWF(template_directory +"/media/main_684x402.swf", "start-flash", "684", "402", "10.0.0", "", {xmlPath: template_directory +"/xml.php"}, {wmode: "transparent"});
	}
	
	// Tabel styling för proffstränare
	$('body.single-proffstranare #content .body .entry table tbody tr:first td').each(function(index, value) {
		$(this).addClass('head');
	});
	
	$('body.single-proffstranare #content .body .entry table tbody tr:odd').addClass('odd');
	
	// remove the margin on large images
	$('#content .entry p').has('img').each(function(key, item) {
		if($(item).find('img').width() >= 530) {
			$(item).addClass('image');
		}	
	});
	
	// animate the information bar
	var information_bar = $('#information-bar');

	if($(information_bar).length) {
		var viewport = $(information_bar).find('.viewport');
		
		$(viewport).find('p').width($(viewport).width());
		animate_ib_text(viewport);
	}
	
	$.history.init(function(url) {
		var link = getSubContentLink(url);

		if(link.type !== "" && link.url !== "") {
			showSubContentContent(link.type, link.url);
		}
	});
	
	// sub content menu
	$('#sub-content ul li a').click(onClickSubContentMenu);
	$('#sub-content .content .data a.post').live('click', onClickSubContentPost);
	
	// load the first sub content item automaticly
	if($('#sub-content').length) {
		var first_item = $('#sub-content .menu li:first a');
		
		var link = getSubContentLink($(first_item).attr('href'));
		showSubContentContent(link.type, link.url, true);
	}
	
	// style tables
	$('#content table.resultatkommentarer').each(function(rKey, rItem) {
		var tr = $(rItem).find('tr');
		var tr_length = $(tr).length;
		
		var header = '<div class="rk-header"><ul class="right">';
		
		for(var x = 1; x <= tr_length; x++) {
			if(x == 1) {
				header += '<li class="left num-'+ x +' active"><a href="#" onclick="return false">'+ x +'</a></li>';
			} else {
				header += '<li class="left num-'+ x +'"><a href="#" onclick="return false">'+ x +'</a></li>';
			}
		}

		header += '<li class="clear"><!-- --></li></ul><div class="clear"><!-- --></div></div>';
		
		$(rItem).before(header);
		
		$(tr).each(function(key, item) {
			$(item).find('p').has('img').addClass('image');
			
			if(key > 0) {
				$(item).hide();
			}
		});
	});
	
	$('.rk-header a').live('click', function() {
		var index = parseInt($(this).text())-1;
		var rk = $(this).parent().parent().parent().next();

		$(rk).find('tr').hide();		
		$(rk).find('tr:eq('+ index +')').show();
		
		$(this).parent().parent().find('li').removeClass('active');
		$(this).parent().addClass('active');
	});
	
	$('#content table.tabell').each(function(tKey, tItem) {
		$(tItem).find('tr').each(function(key, item) {
			if(key === 0)
				$(this).addClass('first');
			else if(key == 1)
				$(this).addClass('second');
			else if(key > 1 && key % 2 == 0)
				$(this).addClass('odd');
				
			$(this).find('td:first').addClass('first');
			$(this).find('td:last').addClass('last');
		});
	});

	// ATG

	$('#atg-wrapper ul.active').show();
	
	$('#atg-wrapper .races a').click(function(){
		var klass = $(this).attr('class');
		number = klass.split('-');
		
		var selector = 'ul.' + number[1];
		
		$(this).parent().parent().find('ul').hide();
		$(this).parent().parent().find(selector).show();
		return false;
		
	});	
	
	$('#content table.proffstranare').each(function(tKey, tItem) {
		$(tItem).find('tr').each(function(key, item) {
			if(key == 0)
				$(this).addClass('first');
			else if(key == 1)
				$(this).addClass('image');
			else if(key > 1 && key % 2 == 0)
				$(this).addClass('odd');
			
				if($(this).find('td').text() == "")
					$(this).find('td').html('&nbsp;')
				
			$(this).find('td:first').addClass('first');
			$(this).find('td:last').addClass('last');
		});
	});

	// Shop

    /*
	$('#checkout').submit(function(e) {
		console.log('asdasd');
		if(!$('#terms-and-conditions-accepted').is(':checked')) {
			alert('Du måste godkänna villkoren för att kunna slutföra köpet.');
			
			e.stopPropagation();
			e.preventDefault();
			return false;
		}
	});
	*/
	
/*
	$('*').each(function () { 
	   if ($(this).children().length == 0) { 
	   		$(this).text($(this).text().replace('(+0,00',''));
	   		$(this).text($(this).text().replace('kr)',''));
	   } 
	});
*/
	
	partner_slide_init();
	var partner_slide_interval = setInterval("partner_slide()", 3000);
});

function get_tab_image(current_tab) {
	if(current_tab == 0) {
		jQuery('.flag-container').find('.company-flag-standing').remove();
		jQuery('.flag-container').find('.company-flag').remove();
		if(first_tab_standing == 1) {
			jQuery('.flag-container').html('<div class="company-flag-standing"><img src="' + first_tab_image + '" /></div>');
		} else {
		
		}
	} else if (current_tab == 1) {
		jQuery('.flag-container').find('.company-flag-standing').remove();
		jQuery('.flag-container').find('.company-flag').remove();
		if(second_tab_standing == 1) {
			jQuery('.flag-container').html('<div class="company-flag-standing"><img src="' + second_tab_image + '" /></div>');
		} else {
			if(second_tab_image !== null) {
				jQuery('.flag-container').html('<div class="company-flag"><img src="' + second_tab_image + '" /></div>');
			}
		}

	} else if (current_tab == 2) {
		jQuery('.flag-container').find('.company-flag-standing').remove();
		jQuery('.flag-container').find('.company-flag').remove();
		if(third_tab_standing == 1) {
			jQuery('.flag-container').html('<div class="company-flag-standing"><img src="' + third_tab_image + '" /></div>');
		} else {
			if(third_tab_image !== null) {
				jQuery('.flag-container').html('<div class="company-flag"><img src="' + third_tab_image + '" /></div>');
			}	
		}

	}		
}

function partner_slide_init() {
	if($('#partners').length == 0)
		return;
	
	$('#partners .items p').each(function(key, item) {
		$(item).css('margin-left', margin);
		margin += 42 + $(item).width();
	});
}

function get_item_with_lowest_margin() {
	var pitem = "";
	$('#partners .items p').each(function(key, item) {
		if(pitem == "" || parseInt($(item).css('marginLeft')) < parseInt($(pitem).css('marginLeft')))
			pitem = item;
	});
	return pitem;
}

// partner slide
function partner_slide() {
	if($('#partners').length == 0)
		return;

	var item_width = 0;
	$('#partners .items p').each(function(key, item) {
		if(key == 0)
			item_width = $(item).width() + 42;

		if(item_width > 0) {
			$(item).animate({marginLeft: parseInt($(item).css('marginLeft')) - item_width}, 800, 'easeOutCirc', function() {
				// move the first item to the end after last animation
				if(key == $('#partners .items p').length-1) {
					var pitem = get_item_with_lowest_margin();
					$(pitem).css('marginLeft', parseInt(margin - item_width));
				}
			});
		}
	});
}

var subContentLoading = false;

// event handler for sub-content menu. fetch link and type, then get the content
function onClickSubContentMenu() {
	$('#sub-content ul li').removeClass('active');
	$(this).parent().addClass('active');

	if(subContentLoading)
		return false;
	
	var link = getSubContentLink($(this).attr('href'));
	showSubContentContent(link.type, link.url, true);
	
	return false;
}

function onClickSubContentPost() {
	if(subContentLoading)
		return false;
	
	var link = getSubContentLink($(this).attr('href'));
	showSubContentContent(link.type, link.url, true);
	
	return false;
}

// extract the link type and url
function getSubContentLink(href) {	
	var type = href.replace(/^.*#/, '').replace(/\/.*/, '');
	

		var url = href.replace(/^.*#/, '').replace(/^(category|external|page|post)\//, '');
	
	return {
		type: type,
		url: url
	};
}



// fetch either category posts, single pages or
// external links depending on type
function showSubContentContent(type, url, history) {
	if(!history || history !== true)
		history = false;

	$('#sub-content .content .data').html("");
	$('#sub-content .loader').show();
	
	if(subContentLoading)
		return false;
		
	subContentLoading = true;
	
	if(history === true)
		$.history.load(type +'/'+ url);
	
	// embeds the external link in an iframe
	if(type == "external") {
		$('#sub-content .content .data').append('<iframe src="'+ url +'" width="100%" height="320" scrolling="no" frameborder="0"></iframe>');
		$('#sub-content .loader').hide();
		subContentLoading = false;		
		return;
	}
	
	// get data from WP
	$.ajax({
		type: 'POST',
		url: template_directory +'/ajax.php',
		data: "link="+ url +"&type="+ type,
		success: function(data, status) {
			if(status != "success" || data == "-1") {
				alert('Något gick snett när innehållet skulle hämtas.');
				return;
			}
			
			$('#sub-content .loader').hide();
			$('#sub-content .content .data').html(data);
			
			subContentLoading = false;
		}
	});
}

// run an animation recursivley that moves the information box
function animate_ib_text(viewport) {
	$(viewport).find('p').animate({
		'marginLeft': 0-parseInt($(viewport).width())
	},
	15000,
	'linear',
	function() {
		$(this).css('marginLeft', $(this).width());
		animate_ib_text(viewport);
	});
}
