$('ul.files li strong, ul.books li strong').widthTruncate();
$('div#news-contents .section').show();
$('div#news-contents div#news-loading').hide();

Math.mid = function(a, b, c) { return Math.max(a, Math.min(b, c)); };

$.fn.hrefId = function() { return $(this).attr('href').substr($(this).attr('href').indexOf('#') + 1); };


// After fade in effect, IE disables anti-aliasing on text, so fix this.
$.fn.fixIEFade = function() {
	if ($.browser.msie && $.browser.version <= 8)
		return this.each(function() {
			this.style.removeAttribute("filter");
		});
	return this;
};
function fixIEFade() { $(this).fixIEFade(); }


// Clear default values in form fields.
$('input:text.default,textarea.default').each(function() {
	this.defaultText = this.value;
	$(this)
		.focusin(function() { if (this.value == this.defaultText) this.value = ''; })
		.focusout(function() { if (!this.value && this.defaultText) this.value = this.defaultText; });
});


// Collapsible and expandable page sections.
function initSections($sections) {
    $sections.each(function() {
        var $section = $(this);

        // To properly calculate section height child sections need to be
        // initialized first.
        var $childSections = $section.find('div.section');
        if ($childSections.length)
            initSections($childSections);

        if ($section.hasClass('section-static') || $section.data('initialized'))
            return;

        var $toggle = $('<p class="toggle"><a href="#">Toggle</a></p>').prependTo($section);
        var $content = $section.children('.section-content');
        var time = 1000; // Animation time in milliseconds.

        if (!$content.length)
            $content = $('<div class="section-content section-loading"></div>').appendTo($section);

        // Add small element, so that section's content won't cover the
        // expand/collapse button in top right corner.
        if (!$content.children(':first').is('ul.files') && !$content.hasClass('section-cases'))
            $content.prepend('<span class="padding">&nbsp;</span>');

        var contentH = function() { return $content.height() + parseInt($section.css('padding-top'), 10) * 2; };

        if (!$section.hasClass('section-expanded'))
            $content.css({marginTop: (-contentH()) + 'px'});
        else
            $section.addClass('section-active');
        $section.children('h2:first,h3:first').addClass('toggle').wrapInner('<a href="#"></a>');

        // Expand or collapse secton's content.
        $section.find('>.toggle a').click(function(e) {
            e.preventDefault();
            $section.toggleClass('section-active');
            var margin = $section.hasClass('section-active') ? 0 : -contentH();
            $content.stop(true).animate({marginTop: margin + 'px'}, time);
        });

        $section.data('initialized', true);
    });
}

initSections($('body>.content div.section'));


// Home page animated banner.
$('div.banner').each(function() {
    var $banner = $(this);
    var $imagesList = $banner.children('ul.images');
    var $images = $imagesList.children();
    var $linksList = $banner.find('>.navigation>ul.links');
    var $links = $linksList.children();
    var count = $images.length, current = 0, w = 892;

    var items = '';
    for (var i = 0; i < count; i++)
        items += '<li><a href="#">' + (i + 1) + '</a></li>';
    var $positionList = $('<ul class="position">' + items + '</ul>').appendTo($banner.children('.navigation'));
    $position = $positionList.children();

    $position.find('a').click(function(e) {
        e.stopPropagation();
        e.preventDefault();

        if (timer) {
            clearInterval(timer);
            timer = null;
        }

        animateTo($(this).parent().index());
    });

    $linksList.height($links.eq(current).outerHeight());
    $links.eq(current).addClass('active');
    $position.eq(current).addClass('active');

    $links.find('a').click(function(e) {
        e.stopPropagation();
    });

    $banner.click(function() {
        //location = $links.eq(current).find('a').attr('href');
    });

    var animateTo = function(i) {
        i = Math.mid(0, i, count - 1);
        if (i == current)
            return;
        current = i;

        $links.filter('.active').animate({opacity: 0}, 500, function() { $(this).removeClass('active'); });
        $links.eq(current).animate({opacity: 0}, 0).addClass('active').animate({opacity: 1}, 500, fixIEFade);
        $linksList.animate({height: $links.eq(current).outerHeight() + 'px'}, 500);

        $imagesList.stop(true).animate({left: (-w * current) + 'px'}, 500);
        $position.removeClass('active');
        $position.eq(current).addClass('active');
    };

    // Toggle items every 10 seconds.
    var timer = setInterval(function() {
        animateTo(current + 1 < count ? current + 1 : 0);
    }, 10000);
});


$('.show-more').hide();
$('a.show-more-toggle').click(function(e) {
    e.preventDefault();
    $(this).closest('.section').find('.show-more').toggle();
    $(this).remove();
});

$('.box-b').click(function() {
    location = '/' + $(this).find('a.button').attr('href');
});


$('.bookstore form.category select').change(function() {
    $(this).closest('form').submit();
});


$('ul.ajax-scroll a').each(function() {
    var $a = $(this);
    var $section = $('#' + $(this).hrefId());
    var loading = false, loaded = false;

    var loadContent = function() {
        if (loading || loaded)
            return;
        loading = true;
        $a.parent().siblings().children().removeClass('active');
        $a.addClass('active');

        setTimeout(function() {
            var url = $a.attr('href');
            url = url.substr(0, url.indexOf('#'));

            $.get(url, function(data) {
                var $content = $section.children('.section-content');
                $content.find('.padding').remove();

                /*var $clone = $content.clone().append(data).css({position: 'absolute', visiblility: 'hidden', width: '436px'}).removeClass('section-loading').appendTo($section);
                initPages();
                var h = $clone.height();
                $clone.remove();*/

                var $data = $(data);
                var $firstPage = $data.filter('div.page').addClass('page-1 page-active').data('page', 1);
                var $pagination = $data.filter('ul.pages');
                $content.append($firstPage).append($pagination).removeClass('section-loading');/*.animate({height: h + 'px'}, 500, function() {
                    $(this).css({'height': 'auto'});
                });*/

                $content.children('.clip-pages').height($content.find('.page-1').outerHeight());

                initPages();
                loading = false;
                loaded = true;
            });
        }, 500);
    };

    $section.find('.toggle a').click(loadContent);

    $a.click(function(e) {
        e.preventDefault();
        $.scrollTo($section[0], 500);
        if ($section.hasClass('section-active'))
            return;
        $section.find('.toggle a').first().click();
    });
});


$('a.top').live('click', function(e) {
    e.preventDefault();
    $.scrollTo(0, 500);
});



function initPages() {
	
	$('ul.pages').not('.alphabet').not('.paged').after('<div style="float: right;font-weight: bold;padding: 8px 0 0 0">Page&nbsp;</div><div style="clear: both"></div>').addClass('paged');
	
    $('ul.pages').each(function() {

        var $pages = $(this);

        if ($pages.hasClass('ajax-scroll') || $pages.hasClass('alphabet'))
            return;
        if ($pages.data('initialized'))
            return;
        var pagesVisible = 5, pagesCount = $pages.children('li').length;
        var currentPage = Math.mid(1, parseInt($pages.find('a.active').text(), 10), pagesCount);

        // Display only needed pagination items, not all of them.
        var showItems = function(page) {
            if (pagesCount + 1 <= pagesVisible)
                return;

            $ellipsisLeft.toggle(page > pagesVisible / 2 + 2);
            $ellipsisRight.toggle(page < pagesCount - pagesVisible / 2 - 1);

            var $items = $pages.children('li:not(.ellipsis)');
            $items.not('li:first').not('li:last').hide();

            // First item to show.
            var min = Math.min(pagesCount - pagesVisible, Math.max(0, page - pagesVisible / 2));
            // Last item to show.
            var max = Math.max(pagesVisible, Math.min(pagesCount, page + pagesVisible / 2));

            $items.slice(min, max).show();
        };

        if (pagesCount + 1 > pagesVisible) {
            $pages.children('li:gt(4)').not('li:last').hide();
            var $ellipsisLeft = $('<li class="ellipsis">...</li>').hide().insertAfter($pages.children('li:first'));
            var $ellipsisRight = $('<li class="ellipsis">...</li>').insertBefore($pages.children('li:last'));

            showItems(currentPage);
        }

        var $section = $pages.closest('.section');
        $section.find('div.page').wrapAll('<div class="clip clip-pages"></div>').first().addClass('page-' + currentPage + ' page-active').data('page', currentPage);

        var $loading = $('<p class="loading"><img src="images/loading.gif" alt="Loading"></p>').hide().appendTo($section.find('.clip-pages'));

        $pages.find('a').click(function(e) {
            e.preventDefault();

            var $a = $(this);
            $a.addClass('active').parent().siblings().children().removeClass('active');
            var page = parseInt($a.text(), 10);
            var $oldPage = $a.closest('.section').find('div.page:visible');
            var oldPage = $oldPage.data('page');

            showItems(page);

            var $page = $section.find('div.page-' + page);
            var oldDst = 456, newSrc = 456;

            if (oldPage < page)
                oldDst *= -1;
            else
                newSrc *= -1;

            var showPage = function($oldPage, $newPage) {
                $newPage.closest('.clip-pages').height($newPage.closest('.clip-pages').height());
                $oldPage.removeClass('page-active').stop(true).animate({left: oldDst + 'px'}, 500, function() { $(this).hide(); });
                $newPage.css({left: newSrc + 'px'}).show().stop(true).animate({left: 0}, 500, function() { $(this).addClass('page-active'); });
                $newPage.closest('.clip-pages').animate({height: $newPage.outerHeight() + 'px'}, 500, function() { $(this).css({'height': 'auto'}); });
            };

            if ($page.length)
                showPage($oldPage, $page);
            else {
                $loading.show();
                $.get($(this).attr('href'), function(data) {
                    $loading.hide();
                    var $newPage = $(data).addClass('page-' + page).data('page', page);
                    $newPage.prependTo($section.find('.clip-pages:first'));
                    initSections($newPage.find('.section'));
                    if ($a.hasClass('active'))
                        showPage($oldPage, $newPage);
                    else
                        $newPage.hide();
                });
            }
        });

        $pages.data('initialized', true);
    });
}

initPages();


// Persons thumbnails and details.
var personAnimation = false;
$('div.people ul.thumbs a').live('click', function(e) {
	if (true === personAnimation) {
		return false;
	}
	personAnimation = true;
	e.preventDefault();
    var $this = $(this);
    var $clip = $this.closest('.clip-pages');

    var thumbsPage = $this.closest('.page').data('page');
    var thumbNo = $this.parent().index() + 1;

    var $details = $clip.find('div.page-' + thumbsPage + '-' + thumbNo);
    var oldDst = -456, newSrc = 456;

    var showPage = function($oldPage, $newPage) {
        $newPage.closest('.clip-pages').height($newPage.closest('.clip-pages').height());
        $oldPage.removeClass('page-active').stop(true).animate({left: oldDst + 'px'}, 500, function() { $(this).hide(); });
        $newPage.css({left: newSrc + 'px'}).show().stop(true).animate({left: 0}, 500, function() { $(this).addClass('page-active'); });
        $newPage.closest('.clip-pages').animate({height: $newPage.outerHeight() + 'px'}, 500, function() { 
        	$(this).css({'height': 'auto'});
        	personAnimation = false;
    	});
    };

    $clip.closest('.section').find('ul.pages').css({'visibility': 'hidden'});

    $.get($(this).attr('href'), function(data) {
        var $newPage = $(data).addClass('page-' + thumbsPage + '-' + thumbNo).data('page', thumbsPage);
        $newPage.prependTo($clip);

        $newPage.find('.back a').click(function(e) {
            e.preventDefault();
            showPage($newPage, $this.closest('.page'));
            $clip.closest('.section').find('ul.pages').css({'visibility': 'visible'});
        });

        showPage($this.closest('.page'), $newPage);
    });
});


if ($.browser.msie && $.browser.version < 7) {
    $('ul.categories>li').hover(
        function() { $(this).addClass('hover'); },
        function() { $(this).removeClass('hover'); }
    );
    $('.home .box-b').hover(
        function() { $(this).addClass('box-b-hover'); },
        function() { $(this).removeClass('box-b-hover'); }
    );
}






























$("input#keywords").autocomplete({
	source: function(request, response) {
		$.ajax({
			url:		"find-an-answer/keywords-hint/",
			dataType:	"json",
			data: {
				chars: 		request.term
			},
			success: function(data) {
				var tags = $.map(data.tags, function(item) {
					return {
						label: item,
						value: item
					}
				})
				var aliases = $.map(data.aliases, function(item) {
					return {
						label: item + ' (related)',
						value: item
					}
				})
				response($.merge(tags, aliases));
			}
		})
	},
	minLength: 1,
	select: function(event, ui) {
		ACC_Search(undefined, ui.item.value);
		$('input#keywords').val(ui.item.value);
		return false;
	}
});

function ACC_SwitchClearButton()
{
	$('a#clear-keywords').parent().slideDown();
//	$('input#keywords').val('Enter your keywords to begin filtering your results');
}

function ACC_GetSelectedTags()
{
	var output = [];
	$.each($('form.keywords a.selected'), function(k, v) {
    	output[k] = $(v).text();
	});
	return output;
}

function ACC_addTag(tag, selected)
{
	var added = false;
	$('form.keywords a.tag').each(function(k) {
    	if (tag == $(this).text()) {
    		if (true === selected) {
    			$(this).addClass('selected');
    		}
    		added = true;
    	}
	});
	if (false === added) {
		$('form.keywords p.categories span').append('<a href="#" class="tag">' + tag + '</a>&nbsp;/ ');
		if (true === selected) {
			$('form.keywords a.tag:last').addClass('selected');
		}
	}
}

var accSearchAjax;
function ACC_Search(keywordsString, additionalTag, tagClick)
{
	$('span.error-messages').clearQueue().fadeOut(200);
	
	var postData = {};
	postData.tags = [];
	
	// tag from input field
	if (typeof tagClick == "undefined") {
		postData.input = true;
	} else {
		postData.tags = ACC_GetSelectedTags();
	}
	
	if (undefined != additionalTag) {
		postData.tags[postData.tags.length] = additionalTag;
	}
	if (undefined != accSearchAjax) {
		accSearchAjax.abort();
	}
	if (undefined != keywordsString) {
		postData.keywordsString = keywordsString;
	}
	
	$('input#keywords').attr('disabled', 'disabled').css('color', '#AAA').blur();
	$('form.keywords input.button').attr('disabled', 'disabled').hide();
	$('input#loading-icon').show();
	
	$('div#keywords-results').slideUp();
	
	accSearchAjax = $.ajax({
		dataType:   "json",
		url:        $('form.keywords').attr('action'),
	    cache:      false,
	    type:		'POST',
	    data: 		postData,
	    success:    function(data) {
			
			var selectTags = false;
			$('input#keywords').removeAttr('disabled').css('color', '#000');
			$('form.keywords input.button').removeAttr('disabled').show();
			$('input#loading-icon').hide();
		
			if (data.errors[1]) {
				$('form.keywords p.categories').slideUp();
				$('a#clear-keywords').parent().slideUp();
				$('span.error-messages').clearQueue().text(data.errors[1]).fadeIn(250).delay(10000).fadeOut(500);
			} else {
//				$('input#keywords').val('Enter your keywords to begin filtering your results');
				ACC_SwitchClearButton();
			}
			
			// Result from input field
			if (true === data.input) {
				
				$('form.keywords p.categories span').html('');
				
				// If more than 1 keyword do not show results, do not select tags
				if (data.tags.length == 1) {
					$('div#keywords-results').html(data.results);
					$('div#keywords-results').slideDown();
					initSections($('body>.content div.section'));
					initPages();
					selectTags = true;
				}
				
			} else {
				$('div#keywords-results').html(data.results);
				$('div#keywords-results').slideDown();
				initSections($('body>.content div.section'));
				initPages();
				selectTags = true;
			}
			
			$(data.tags).each(function(index) {
				ACC_addTag(this, selectTags);
			});
				
			if (data.tags.length) {
				$('form.keywords p.categories').slideDown();
			}
	    }
	});
}

$("input#keywords").keypress(function handleKeys(ev) {
    var keyCode = (ev.which) ? ev.which : ev.keyCode;
    if (13 === keyCode) {
    	ACC_Search($(this).val());
    	return false;
    }
});

$('form.keywords').submit(function()
{
	var keywords = jQuery.trim($(this).find('input#keywords').val());
	if (keywords.length > 0) {
		ACC_Search(keywords);
	}
	return false;
});

var pressedMoreButton = false;
$('form.keywords a.more').live('click', function()
{
	if (true === pressedMoreButton) {
		return false;
	}
	pressedMoreButton = true;
	
	var _this = $(this);
	_this.css('background', 'url(\'images/loading_small_orange.gif\')').css('width', '16px').css('height', '16px').die('click');
	
	$.ajax({
	    dataType:   "json",
	    url:        _this.attr('href'),
	    cache:      false,
	    type:		'GET',
	    success:    function(data) {
			pressedMoreButton = false;
	        $.each(data.elements, function(k, v) {
	        	ACC_addTag(v, false);
	    	});
	        if (false !== data.next) {
	        	_this.parent().append('<a href="' + data.next + '" class="more">More</a> ');
	        }
	        _this.remove();
	    }
	});
	return false;
});

$('a#clear-keywords').click(function()
{
	$('div#keywords-results').slideUp();
	$('form.keywords p.categories').slideUp(function() {
		$('form.keywords p.categories span').html('');
	});
	$('a#clear-keywords').parent().slideUp();
	$('input#keywords').val('Enter your keywords to begin filtering your results');
	return false;
});

$('form.keywords a.tag').live('click', function()
{
	if ($(this).hasClass('selected')) {
		$(this).removeClass('selected');
	} else {
		$('form.keywords a.tag').removeClass('selected');
		$(this).addClass('selected');
	}
	ACC_Search(undefined, undefined, true);
	return false;
});

if (typeof(_selected_news_id) != "undefined") {
	$.scrollTo($('h3#news-' + _selected_news_id), 1000);
	$('h3#news-' + _selected_news_id + ' a').click();
}

if (typeof(selected_keywords) != "undefined") {
	$.each(selected_keywords, function(k, keyword) {
		ACC_addTag(keyword, true);
	});
	ACC_Search();
}
if (window.location.hash) {
	hash = window.location.hash.substr(1);
	if (hash.length > 0) {
		$.scrollTo($('div#' + hash + '-anchor'), 500);
		if (!$('div#' + hash + '-anchor').hasClass('section-expanded')) {
			$('div#' + hash + '-anchor h2 a').click();
		}
	}
}
$('input#loading-icon').focus(function(){
	$(this).blur();
}).css('cursor', 'default');
if (typeof(slideTo) != "undefined") {
	$.scrollTo($('div#' + slideTo), 500, function() {
		$('p#subscribe-msg').slideDown(500);
	});
}

function detectBackToTop() {
	if ($(window).scrollTop() > 100) {
		$('a.top').show();
	} else {
		$('a.top').hide();
	}
}
$(window).scroll(detectBackToTop);
detectBackToTop();

function checkWhatYouDoTitle() {
	var $title = $('h1.what-you-do-title');
	if ($('h1.what-you-do-title span').width() > $title.width()) {
		$title.css('font-size', (parseInt($title.css('font-size')) - 1) + 'px');
		checkWhatYouDoTitle();
		return false;
	}
	return true;
}
$('h1.what-you-do-title').show();
checkWhatYouDoTitle();

$('a').click(function(){
	var href = $(this).attr('href');
	if (href.indexOf('#') > 0) {
		var hash = href.substr(href.indexOf('#') + 1);
		$.scrollTo($('div#' + hash + '-anchor'), 500);
		if (!$('div#' + hash + '-anchor').hasClass('section-expanded') && !$('div#' + hash + '-anchor').hasClass('section-active')) {
			$('div#' + hash + '-anchor h2 a').click();
		}
	}
});
$('a.target_blank').attr('target', '_blank');
$('span.error-messages').hide();
