function showTimeinfo(labelYear, labelWeek, labelDay, year, week, day, timestamp)
{
	var currentTime = new Date(timestamp * 1000);

    var summertime = 0;
    var difference = currentTime.getTimezoneOffset() / 60 + 1 + summertime;
    var hours = currentTime.getHours() + difference;
	if (hours < 10) {
	    hours = '0' + hours;
	} else if (hours > 23) {
	    hours = hours - 24;
	}
	(currentTime.getMinutes() < 10) ? minutes = '0' + currentTime.getMinutes() : minutes = currentTime.getMinutes();
	(currentTime.getSeconds() < 10) ? seconds = '0' + currentTime.getSeconds() : seconds = currentTime.getSeconds();

	document.getElementById('timeinfo').innerHTML = labelYear + ' ' + year + ', ' + labelWeek + ' ' + week + ', ' + labelDay + ' ' + day + ' ' + hours + ':' + minutes + ':' + seconds;
	setTimeout("showTimeinfo('" + labelYear + "', '" + labelWeek + "', '" + labelDay + "', " + year + ", " + week + ", " + day + ", " + (timestamp + 1) + ")", 1000);
}

// scrolling
var scrollObj = false;
var timerObj = false;
var scrollTargetX = 0;
var scrollTargetY = 0;
var curTimerStep = 0;
function scrollDiv(target, direction, step)
{
	scrollObj = document.getElementById(target);
	scrollTimerEnd();
	if (direction == 'right') {
		scrollTargetX = Math.max(-scrollObj.offsetWidth + scrollObj.parentNode.offsetWidth, parseInt(scrollObj.style.left) - step);
		timerObj = setInterval("scrollTimer()", 50);
	} else if (direction == 'down') {
		scrollTargetY = Math.max(-scrollObj.offsetHeight + scrollObj.parentNode.offsetHeight, parseInt(scrollObj.style.top) - step);
		timerObj = setInterval("scrollTimer()", 50);
	} else if (direction == 'left') {
		scrollTargetX = Math.min(0, parseInt(scrollObj.style.left) + step);
		scrollTargetX -= ((scrollTargetX + step * 100) % step);
		timerObj = setInterval("scrollTimer()", 50);
	} else if (direction == 'up') {
		scrollTargetY = Math.min(0, parseInt(scrollObj.style.top) + step);
		scrollTargetY -= ((scrollTargetY + step * 100) % step);
		timerObj = setInterval("scrollTimer()", 50);
	}
	return false;
}
function scrollTimer()
{
	var curX = parseInt(scrollObj.style.left);
	var curY = parseInt(scrollObj.style.top);
	curX = (curX + scrollTargetX) / 2;
	curY = (curY + scrollTargetY) / 2;
	scrollObj.style.left = curX + 'px';
	scrollObj.style.top = curY + 'px';
	curTimerStep++;
	if (curTimerStep > 6) scrollTimerEnd();
}
function scrollTimerEnd()
{
	scrollObj.style.left = scrollTargetX + 'px';
	scrollObj.style.top = scrollTargetY + 'px';
	curTimerStep = 0;
	clearInterval(timerObj);
}

function redirect(target)
{
    window.location = target;
}

// internalTactics
function adjustTactic(section, id, direction, step, minPosition, maxPosition)
{
    var position = parseInt(document.getElementById(section + '_' + id + 'Bar').style.left);
    if (direction == 'left' && position - step >= minPosition) {
        document.getElementById(section + '_' + id + 'Bar').style.left = (position - step) + 'px';
        document.getElementById(section + '_' + id + 'Value').value    = parseInt(document.getElementById(section + '_' + id + 'Value').value) - step;
    } else if (direction == 'right' && position + step <= maxPosition) {
        document.getElementById(section + '_' + id + 'Bar').style.left = (position + step) + 'px';
        document.getElementById(section + '_' + id + 'Value').value    = parseInt(document.getElementById(section + '_' + id + 'Value').value) + step;
    }
    $('#' + section + '_' + id + 'Background').attr('title', (($('#' + section + '_' + id + 'Bar').position().left - minPosition) / (maxPosition - minPosition) * 100) + '%');
    $('#' + section + '_' + id + 'Bar').attr('title', (($('#' + section + '_' + id + 'Bar').position().left - minPosition) / (maxPosition - minPosition) * 100) + '%');
}

// collecting game
function collectTennisball(hash)
{
    redirect('index.php?ota=internalHome&subaction=collectPumpkin&hash=' + hash + '&check=' + $('#check').val());
}

function openLanguageSelection()
{
    $('#languageSelectionHidden').slideUp(
        400, function() {
            $('#languageSelectionVisible').slideDown(
                1000, function() {
                }
            );
        }
    );
}
function closeLanguageSelection()
{
    $('#languageSelectionVisible').slideUp(
        1000, function() {
            $('#languageSelectionHidden').slideDown(
                400, function() {
                }
            );
        }
    );
}

var entrylistMoving = false;
function scrollEntrylist(direction)
{
    if (entrylistMoving) {
        return;
    }
    entrylistMoving = true;
    if (direction == 'up') {
        if ($('#entrylistTable').position().top < 0) {
            $('#entrylistTable').animate({
                top: '+=240'
            }, 500, function() {
                entrylistMoving = false;
                $('#scrollDown').show();
                if ($('#entrylistTable').position().top >= -240) {
                    $('#scrollUp').hide();
                }
            });
        }
    } else {
        if ($('#entrylistTable').position().top > -2160) {
            $('#entrylistTable').animate({
                top: '-=240'
            }, 500, function() {
                entrylistMoving = false;
                $('#scrollUp').show();
                if ($('#entrylistTable').position().top <= -2160) {
                    $('#scrollDown').hide();
                }
            });
        }
    }
}

var visibleSubmenu = 'career';
var switchSubmenuActive = false;
function switchSubmenu(submenu)
{
    if (submenu != visibleSubmenu && !switchSubmenuActive) {
        switchSubmenuActive = true;
        $('#submenu_' + visibleSubmenu + '_container').slideUp(
            200,
            function() {
                $('#submenu_' + submenu + '_container').slideDown(
                    200,
                    function() {
                        visibleSubmenu = submenu;
                        switchSubmenuActive = false;
                    }
                );
            }
        );
    }
}
function setSubmenu(submenu)
{
    $('#submenu_career_container').hide();
    $('#submenu_finances_container').hide();
    $('#submenu_personal_container').hide();
    $('#submenu_statistics_container').hide();
    visibleSubmenu = submenu;
    $('#submenu_' + visibleSubmenu + '_container').show();
}

var preloadedImages = new Array();
function preloadImages(action, cacheVersion)
{
    // user profile
    var images = new Array('background_overview.jpg', 'background_description.jpg', 'background_skills.jpg', 'background_statistics.jpg', 'background_trophies.jpg', 'background_career.jpg', 'background_private.jpg', 'background_wall.jpg');
    for (j = 0; j < images.length; j++)
    {
        preloadedImages[j + 1]     = new Image();
        preloadedImages[j + 1].src = '/images/profile/user/' + images[j];
    }

    // action specific
    if (action == 'internalPayment') {
        var images = new Array('button_otdollar_hover.png', 'button_otdollar_active.png', 'button_supporter_hover.png', 'button_supporter_active.png');
    } else {
        var images = new Array();
    }
    for (i = 0; i < images.length; i++)
    {
        preloadedImages[i]     = new Image();
        preloadedImages[i].src = '/images/' + action + '/' + images[i] + '?v=' + cacheVersion;
    }
}

function openPayment(address)
{
    var payment = window.open(address.replace(/\+/g,"%2B"), "paymentglobal", "width=840,height=680,left=100,top=200");
    payment.focus();
}

function OTInfo(title, message)
{
    $('#dialog').attr('title', title);
    $('#dialog').html(message);
    $('#dialog').dialog();
}

function OTPumpkin2011(title, message)
{
    $('#dialog').attr('title', title);
    $('#dialog').html(message);
    $('#dialog').dialog({ width: 450, height: 700 });
}
function OTError(title, message)
{
    $('#dialog').attr('title', title);
    $('#dialog').html(message);
    $('#dialog').dialog();
}
function OTConfirm(title, message, callbackFunction)
{
    $('#dialog').attr('title', title);
    $('#dialog').html(message);
    $('#dialog').dialog({
        buttons: {
            Ok: function() {
                callbackFunction();
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });
}
function achievementUnlocked(id, name, image, description)
{
    var container = document.createElement('div');

    var content = '<div class="title">' + name + '</div>';
    content += '<div class="image" style="background-image: url(\'' + image + '\')"></div>';
    content += '<div class="description">' + description + '</div>';

    $(container).html(content);
    $('#achievementUnlockedContainer').append(container);

    $(container).dialog({
        width: 500,
        height: 300,
        resizable: false,
        buttons: {
            'OK': function() {
                xajax_markAchievementMessageShown(id);
                $(this).dialog('close');
            }
        },
        dialogClass: 'achievementUnlocked'
    });
}

var map = false;
var globalLatLng = false;
function initializeGoogleMaps()
{
    var minZoomLevel = 6;
    var maxZoomLevel = 10;
    var defaultZoomLevel = 9;

    if (GBrowserIsCompatible())
    {
        var tilelayers = [new GTileLayer(null, minZoomLevel, maxZoomLevel)];
        tilelayers[0].getTileUrl = function(coordinates, zoom) { return 'dyn_pics/tile.php?x=' + coordinates.x + '&y=' + coordinates.y + '&z=' + zoom; };

        var OTMap = new GMapType(tilelayers, new GMercatorProjection(12), "Onlinetennis");

        map = new GMap2($("map_canvas"));
        map.setCenter(new GLatLng(0, 0), defaultZoomLevel);

        var customUI = map.getDefaultUI();
        customUI.controls.scalecontrol = false;
        map.setUI(customUI);

        map.addMapType(OTMap);
        map.setMapType(OTMap);
        map.removeMapType(G_NORMAL_MAP);
        map.removeMapType(G_SATELLITE_MAP);
        map.removeMapType(G_HYBRID_MAP);
        map.removeMapType(G_PHYSICAL_MAP);

        GEvent.addListener(map, 'click', function(overlay, latlng)
        {
            if (overlay)
            {
                // ignore if we click on the info window
                return;
            }
            var fieldCoordinate = new GPoint();
            var fieldPoint = new GPoint();
            var currentProjection = G_NORMAL_MAP.getProjection();
            fieldPoint = currentProjection.fromLatLngToPixel(latlng, map.getZoom());
            globalLatLng = latlng;
            fieldCoordinate.x = Math.floor(fieldPoint.x / (256 / Math.pow(2, 12 - map.getZoom())));
            fieldCoordinate.y = Math.floor(fieldPoint.y / (256 / Math.pow(2, 12 - map.getZoom())));
            xajax_getFieldOptions(fieldCoordinate.x, fieldCoordinate.y);
        });
    }
}
function showCategoryConstructions(category)
{
    for (i = 0; i < $('category_' + category).parentNode.childNodes.length; i++)
    {
        $('category_' + category).parentNode.childNodes[i].hide();
    }
    $('category_' + category).show();
}
function selectConstruction(constructionID, price, currency, width, height)
{
    $('constructionPrice').innerHTML = price + ' ' + currency;
    $('constructionWidth').innerHTML = width;
    $('constructionHeight').innerHTML = height;
    $('constructionID').value = constructionID;
    for (i = 0; i < $('construction_image_' + constructionID).parentNode.childNodes.length; i++)
    {
        $('construction_image_' + constructionID).parentNode.childNodes[i].style.backgroundColor = '#ffffff';
    }
    $('construction_image_' + constructionID).style.backgroundColor = '#dddddd';
}
function resetSelectedConstruction(category)
{
    $('constructionPrice').innerHTML = '';
    $('constructionWidth').innerHTML = '';
    $('constructionHeight').innerHTML = '';
    $('constructionID').value = '';
    for (i = 0; i < $('category_' + category).childNodes.length; i++)
    {
        $('category_' + category).childNodes[i].style.backgroundColor = '#ffffff';
    }
}
function selectBrand(brandID)
{
    $('#selectBrandInfo').hide();
    $('#itemListHeaders').show();
    $('#itemList').show();
    $('#userItems_container').show();
    $('#itemList .item').hide();
    $('.brand_' + brandID).show();
    $('#selectedBrand').value = brandID;
}
function dropEquipmentItem(dragElement, dropElement)
{
    dropElement = $(dropElement);
    var tmp = dragElement.attr('id').split('_');
    if (tmp.length == 3) {
        tmp[0] = tmp[1];
        tmp[1] = tmp[2];
    }
    var dragType = tmp[0]; // something like "racquet"
    var dragID   = tmp[1]; // something like "11"

    var tmp = dropElement.attr('id').split('_');
    var dropEvent = tmp[0]; // something like "singles"
    var dropType  = tmp[1]; // something like "racquet"

    $('userItemsHint').hide();

    $(dropElement.attr('id') + '_price').html($('#' + dragType + '_' + dragID + '_price').val());
    $(dropElement.attr('id') + '_container').show();

    if (dropElement.children().size() > 0) { // there is already an item in this field
        dropElement.children(':first').remove();
    }

    // update database
    xajax_updateEquipment(dragType, dragID, dropElement.attr('id'));

    // put the element on the droppable
    var newNode = $(dragElement).clone();
    newNode.attr('id', dropEvent + '_' + dragType + '_' + dragID);
    newNode.children(':first').attr('id', newNode.attr('id') + '_amount');
    $(dropElement).append(newNode);
    $(dragElement).css( { left: '0px', top: '0px' } );
    $(newNode).css( { left: '0px', top: '0px', opacity: 1, zIndex: 1 } );
    $(newNode).draggable({ opacity: 0.5, revert: true });
}
function changeShowmatchSkills()
{
    if ($('#skillMin').val()  == '0' && $('#skillMax').val() == '0') {
        $('#opponent').attr('disabled', '');
    } else {
        $('#opponent').attr('disabled', 'disabled');
    }
}

function showTutorial(title, text)
{
    $('#tutorial').attr('title', title);
    $('#tutorial').html(text);
    $('#tutorial').dialog({
        width: 550,
        height: 310,
        resizable: false
    });
}
function hideTutorial()
{
    $('#tutorial').dialog('close');
}

/* browser-update.org */
var $buoop = {
    reminder: 24,
    newwindow: true
}
$buoop.ol = window.onload;
window.onload = function() {
    if ($buoop.ol) $buoop.ol();
    var e = document.createElement("script");
    e.setAttribute("type", "text/javascript");
    e.setAttribute("src", "http://browser-update.org/update.js");
    document.body.appendChild(e);
}

function createProfileLinks()
{
    $('.userProfile').fancybox(
    {
        'autoDimensions': false,
        'autoScale': false,
        'width': 800,
        'height': 600,
        'padding': 0,
        'hideOnOverlayClick': false
    });
    $('.doublesProfile').fancybox(
    {
        'autoDimensions': false,
        'autoScale': false,
        'width': 800,
        'height': 600,
        'padding': 0,
        'hideOnOverlayClick': false
    });
}

function showUserProfile(id)
{
    $.fancybox({
        'href': 'index.php?ota=profileUser&id=' + id,
        'autoDimensions': false,
        'autoScale': false,
        'width': 800,
        'height': 600,
        'padding': 0,
        'hideOnOverlayClick': false
    });
}

function showDoublesProfile(id)
{
    $.fancybox({
        'href': 'index.php?ota=profileDoubles&id=' + id,
        'autoDimensions': false,
        'autoScale': false,
        'width': 800,
        'height': 600,
        'padding': 0,
        'hideOnOverlayClick': false
    });
}

function showSkillInfo(id)
{
    $('.skillInfo').hide();
    $('#skillInfo' + id).show();
}

function createNotePadLink()
{
    $('#notepadLink').fancybox({
        'autoDimensions': false,
        'autoScale': false,
        'enableKeyboardNav': false,
        'width': 400,
        'height': 400,
        'padding': 16,
        'onClosed': function() {
            xajax_updateNotePad($('#notepad').val());
        }
    });
}

function toggleRankingHeadline(bigID, smallID)
{
    $('#' + bigID + 'Header').css('font-size', '14px');
    $('#' + bigID + 'Header').css('top', '4px');
    $('#' + bigID + 'Header').css('cursor', 'default');
    $('#' + bigID).show();
    $('#' + smallID + 'Header').css('font-size', '10px');
    $('#' + smallID + 'Header').css('top', '7px');
    $('#' + smallID + 'Header').css('cursor', 'pointer');
    $('#' + smallID).hide();
}

function initTooltip(link, tooltip)
{
    $(link).tooltip({
        bodyHandler: function() {
            return $(tooltip).html();
        }
    });
}

function sendShoutboxMessage(ota)
{
    xajax_postShoutboxMessage(
        $('#shoutboxMessage').val(),
        '{$selectedShoutboxChannel}',
        $('#firstShoutboxMessage').val(),
        ota
    );
    $('#shoutboxMessage').val('');
}

function initShoutboxRefresh(ota, refreshInterval, channel)
{
    setInterval(function() {
        xajax_refreshShoutbox(channel, $('#firstShoutboxMessage').val(), ota, 'firstShoutboxMessage');
    }, refreshInterval);
}

function initLivematchChatRefresh(ota, refreshInterval, channel)
{
    xajax_refreshLivematchesChat(channel, $('#livematch_first_message_id').val(), ota, 'livematch_first_message_id');
    setInterval(function() {
        xajax_refreshLivematchesChat(channel, $('#livematch_first_message_id').val(), ota, 'livematch_first_message_id');
    }, refreshInterval);
}

function initLivematchRefresh(matchType, matchId, refreshInterval)
{
    xajax_updateLivematch(matchType, matchId, $('#rallyId').val());
    setInterval(function() {
        xajax_updateLivematch(matchType, matchId, $('#rallyId').val());
    }, refreshInterval);
}

function initOtCupChatRefresh(ota, refreshInterval, channel)
{
    xajax_refreshOtCupChat(channel, $('#otcup_first_message_id').val(), ota, 'otcup_first_message_id');
    setInterval(function() {
        xajax_refreshOtCupChat(channel, $('#otcup_first_message_id').val(), ota, 'otcup_first_message_id');
    }, refreshInterval);
}

function addShoutboxMessage(id, messageString, listname)
{
    if ($('#sb_' + id).length == 0) {
        $('#' + listname).prepend(messageString);
        $('#' + listname).css("top", $('#' + listname).position().top - $("#sb_" + id).height() + "px");
        $('#' + listname).animate({top: 0}, 100);
    }
}

function openNews(id)
{
    if ($('#' + id).css('display') == 'none') {
        $('.newsBody').each(
            function (index, e) {
                if ($(e).css('display') != 'none') {
                    $(e).slideUp();
                }
            }
        );
        $('#' + id).slideDown();
    }
}

function switchAchievementCategory(id)
{
    $('.achievementContent .category').hide();
    $('#achievementCategory' + id).show();
    $('.achievementMenu').removeClass('selected');
    $('#achievementMenu' + id).addClass('selected');
}

function updateHeadhunterPrice()
{
    console.log($('#headhunterType').val());
    var price = $('#headhunter_' + $('#headhunterType').val()).val() * $('#headhunterSkill').val();
    price = Math.round(parseInt(price) * 1.1);
    $('#headhunterPrice').html(price.toString().replace(new RegExp("(^\\d{"+(price.toString().length%3||-1)+"})(?=\\d{3})"),"$1"+'.').replace(/(\d{3})(?=\d)/g,"$1"+'.'));
}

function toggleShowmatchesHeadToHead(opponentId, userId)
{
    if ($('#opponent_showmatches_' + opponentId).html() == '') {
        $('#opponent_' + opponentId + '_link').html('[-]');
        xajax_getHeadToHeadShowmatchesInformation(opponentId, userId);
    } else {
        $('#opponent_showmatches_' + opponentId).html('');
        $('#opponent_' + opponentId + '_link').html('[+]');
    }
}

function toggleSinglesHeadToHead(opponentId, userId)
{
    if ($('#opponent_singles_' + opponentId).html() == '') {
        $('#opponent_' + opponentId + '_link').html('[-]');
        xajax_getHeadToHeadInformation(opponentId, userId);
    } else {
        $('#opponent_singles_' + opponentId).html('');
        $('#opponent_' + opponentId + '_link').html('[+]');
    }
}

