if (typeof(social_auth) == 'undefined') {
	var social_auth	= '';
}

/**
 * Executed when document is finished loading elements into DOM
 */
$(document).ready(function() {
	// make last tab as wide as it need to be to reach right side
	$('.tabs').each(function(){
		var tabs = $(this);
		var li_widths = 0;
		tabs.find('li').each(function(){
			li_widths += $(this).width();
		});
		var diff = tabs.width() - li_widths;
		if (diff > 0) {
			var last_el = tabs.find('li:last a');
			last_el.width(last_el.width() + diff - 2);
		}
	});

	// confirm box
	$('.confirm').click(function(){
		return confirm('Vai tiešām vēlaties turpināt?');
	});

	if (typeof(jQuery.fn.tabs) == 'function') {
		$('.tabs').tabs('.panes > div', {
			effect: 'fade',
			onBeforeClick: function(event, tabIndex) {
				var tabs = this.getTabs();
				var link = $(tabs[tabIndex]);
				if (link.hasClass('external')) {
					redirect(link.attr('href'));
					return false;
				}
			}
		});
	}

	// replace all textual info[at]domain.com style emails to js
	$('.email').each(function(){
		var email = $(this).text().replace('[at]', '@');
		$(this).html('<a href="mailto:'+email+'">'+email+'</a>');
	});

	flashMessage();

	if ($('#banners .item').length > 1) {
		setInterval("switchBanners()", 3000);
	}

	$('.overview .latest-tasks ul a').click(function() {
		var task_id;

		task_id = $(this).attr('rel');

		if (task_id) {
			$('#task-'+task_id).fadeIn();
		} else {
			$('.overview .latest-tasks .item').fadeOut();
		}

		return false;
	});

	if ($('#TeamUpdateForm').length) {
		updateUserForm();
	}

	if ($('#TeamRegionId').length) {
		loadRegionSchools();
	}

	if (typeof(sw) == 'object') {
		sw.pathToImages = webroot+'img/sw/';
		sw.init();
	}

	$('input[placeholder]').placeholder();

	if ($('#newest-videos').length) {
		loadPiece(webroot+'videos/newest/'+video_category, '#newest-videos');
	}

	// set quiz answer
	$('.quiz-answer').click(function() {
		$('#QuizAnswer').val($(this).attr('rel'));
		$('#QuizQuestionsForm').submit();
		return false;
	});

	//quiz all top show/hide
	$('.all-top-btn').click(function(){
		$('.all-top').slideToggle(400, function(){
			draugiemResizeIframe();
		});
		return false;
	});

	$('#admin-tools').hover(
		function(){$(this).stop().animate({left: '0'}, 200);},
		function(){$(this).stop().animate({left: '-25px'}, 200);}
	);

	$('.pop').fancybox();

	$('.gallery-pop').fancybox({
		className: 'fancy-gallery',
		titlePosition: 'inside',
		centerOnScroll: true,
		title: '&nbsp;',
		padding: 15
	});

	$('#reset-passwd').live('click', function(){
		var url = $(this).attr('href');

		$.fancybox({
			type: 'ajax',
			href: url,
			autoDimensions: false,
			cache: false,
			width: 310,
			height: 'auto',
			padding: 0,
			overlayOpacity: 0.6,
			overlayColor: '#000',
			centerOnScroll: true,
			showCloseButton: false,
			onComplete: function(){
				$('input[placeholder]').placeholder();
			}
		});

		return false;
	});

	if ($.browser.msie && parseInt($.browser.version, 10) == 6) {
		$.ajax({
			url: webroot+'ws/old_browser',
			success: function(data){
				$('body').prepend(data);
			}
		});
	}

	$('.blog-entry-gallery input').change(function(){
		var el = $(this);
		if (el.val() != '') {
			el.parent().next().show();
		}
	});
});

/**
 * Loads in a URL into a specified divName, and applies the function to
 * all the links inside the pagination div of that page (to preserve the ajax-request)
 * @param string href The URL of the page to load
 * @param string divName The name of the DOM-element to load the data into
 * @return boolean False To prevent the links from doing anything on their own.
 */
function loadPiece(href,divName) {
    $(divName).load(href, {}, function(){
        var divPaginationLinks = divName+" #paginator a";
        $(divPaginationLinks).not('.all-video').click(function() {
            var thisHref = $(this).attr("href");
            loadPiece(thisHref,divName);
            return false;
        });
    });
}

function switchBanners() {
	var $active = $('#banners .active');
	if ($active.length == 0) {
		$active = $('#banners div:last');
	}
	var $next = $active.next().length ? $active.next()	: $('#banners div:first');
	$active.addClass('last-active');
	$next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() {
		$active.removeClass('active last-active');
	});
}

function showTask(id) {
	$.fancybox({
		type: 'ajax',
		padding: 0,
		href: webroot+"tasks/view/"+id+"?r="+Math.random(),
		autoDimensions: true,
		overlayOpacity: 0.6,
		overlayColor: '#000',
		centerOnScroll: true,
		showCloseButton: false,
		scrolling: 'no',
		cache: false,
		onComplete: function(){

			var max_height, els, i;

			$.fancybox.resize();

			// izlīdzinam visus atbildes boxus vienādā augstumā

			els = $('#fancybox-wrap .answer');

			max_height = 0;

			for (i=0; i<els.length; i++) {
				if ($(els[i]).height() > max_height) {
					max_height = $(els[i]).height();
				}
			}

			for (i=0; i<els.length; i++) {
				if ($(els[i]).height() != max_height) {
					$(els[i]).height(max_height);
				}
			}
		}
	});
}

function showLogin() {
	$.fancybox({
		type: 'ajax',
		href: webroot+"teams/login",
		autoDimensions: false,
		cache: false,
		width: 310,
		height: 'auto',
		padding: 0,
		overlayOpacity: 0.6,
		overlayColor: '#000',
		centerOnScroll: true,
		showCloseButton: false,
		onComplete: function(){
			$('input[placeholder]').placeholder();
		}
	});
}

function createTask() {
	$.fancybox({
		type: 'iframe',
		href: webroot+'tasks/create/1',
		autoDimensions: false,
		showCloseButton: false,
		overlayOpacity: 0.6,
		overlayColor: '#000',
		centerOnScroll: true,
		scrolling: 'no',
		margin: 0,
		padding: 0,
		width: 554,
		height: 550
	});
}

function flashMessage() {
	if ($('#flash-message').length) {
		$.fancybox({
			content: $('#flash-message').html(),
			overlayOpacity: 0.6,
			overlayColor: '#000',
			centerOnScroll: true,
			showCloseButton: false,
			autoDimensions: false,
			padding:0,
			width:400,
			height:'auto',
			onComplete: function() {
				$('#fancybox-wrap .plain-btn').focus();
			}
		});
	}
}

function socialAuth() {
	$.fancybox({
		type: 'ajax',
		href: webroot+"users/auth",
		autoDimensions: true,
		padding: 0,
		cache: false,
		overlayOpacity: 0.6,
		overlayColor: '#000',
		centerOnScroll: true,
		showCloseButton: false,
		scrolling: 'no',
		onComplete: function(){
			$.fancybox.resize();
		}
	});
}

/**
 * Print email link (protection from spambots)
 * If javascript is disabled, nothing is visible
 *
 * @param string p1 Part 1 - this is username
 * @param string p2 Part 2 - this is domain and TLD
 * @param string name (optional) Display value
 */
function writemail(p1, p2, name) {
	if (typeof(name) == "undefined") {
		name = p1+"@"+p2;
	}

	document.write("<a href='mailto:"+p1+"@"+p2+"'>"+name+"</a>");
}

/**
 * Redirect user to specified page
 *
 * @param string url Address to redirect to
 */
function redirect(url) {
	document.location = url;
}

function submitComment() {
	$('#CommentCreateForm').submit();
}

function updateUserForm() {
	if ($('#UserChangePassword').length) {
		var chk = $('#UserChangePassword');
	} else if ($('#TeamChangePassword').length) {
		var chk = $('#TeamChangePassword');
	}

	if (chk.is(':checked')) {
		$('input[type=password]').each(function() {
			$(this).parent().removeClass('disabled');
			$(this).removeAttr('disabled');
		});
	} else {
		$('input[type=password]').each(function() {
			$(this).parent().addClass('disabled');
			$(this).attr('disabled', true);
		});
	}
}

function loadRegionSchools(school_id) {
	var region_id;

	if (typeof(school_id) == 'undefined') {
		school_id = 0;
	}

	region_id = $('#TeamRegionId').val();

	$('#registration-regions img:visible').fadeOut();
	$('#registration-regions .region-'+region_id).fadeIn();


	if (region_id == '' || region_id == '0') {
		$('#TeamSchoolId').html('');
	} else {
		options = $('#schools-'+region_id).html();
		$('#TeamSchoolId').html(options).val(school_id);
	}
}

function authQuizzes(id) {
	if (typeof(id) == 'undefined') {
		id = $('#quizz_id').val();
	}
	redirect(webroot + 'quizzes/start/' + id);
}

function showDraugiemLogin(url) {
	var x, y, w, h;

	w = 400;
	h = 400;
	x = (screen.width/2)-(w/2);
	y = (screen.height/2)-(h/2);

	window.open(url, 'draugiem', 'scrollbars=no, width='+w+', height='+h+', left='+x+', top='+y);
}

function toggleTeamHelp() {
	var visible;

	if ($('#team-help .inner').is(':visible')) {
		$('#team-help .inner').slideUp();
		visible = 0;
	} else {
		$('#team-help .inner').slideDown();
		visible = 1;
	}

	$.ajax({
		url: webroot+'teams/show_help/'+visible,
		cache: false
	});
}

function toggleTeamInfo() {
	var visible;

	if ($('#team-info .inner').is(':visible')) {
		$('#team-info .inner').slideUp();
		visible = 0;
	} else {
		$('#team-info .inner').slideDown();
		visible = 1;
	}

	$.ajax({
		url: webroot+'teams/show_info/'+visible,
		cache: false
	});
}

function showAllActionLog(el) {
	var element = $(el);

	$.ajax({
		url: element.attr('href'),
		success: function(data){
			element.siblings('.inner').html(data);
			element.remove();
		}
	});

	return false;
}
