var priceId = 'lt50';

function changeCountry (id)
{
    if (id == 2)
    {
        link   	   = ruLink['link'];
        linkText   = ruLink['linkText'];
    }
    else
    {
        link   	   = '';
        linkText   = '';
    }
    
    var linkTr;
    
    if (link.length && linkText.length)
    {
        document.getElementById('downloadPage').style.display = 'none';
        linkTr = document.getElementById('downloadPageLink');
        linkTr.style.display = '';
        linkTr.getElementsByTagName('p').item(0).innerHTML = '<a target="blank" href="' + link + '">' + linkText + '</a>';
    }
    else
    {
        document.getElementById('downloadPage').style.display = '';
        document.getElementById('downloadPageLink').style.display = 'none';
    }
    
}


function intMask (elem)
{
    elem.value = elem.value.replace(/\D/, '');
    refreshOrderForm();
}

function signIntMask (elem)
{
    elem.value = elem.value.replace(/(^[^-0-9]|(?!^)[^0-9])/, '');
}

function printForm (elem)
{
    var addElem = document.getElementById('add');
    var addValue = 0;
    if (!addElem.disabled)
    {
        addValue = parseInt(addElem.value);
        if (isNaN(addValue)) addValue = 0;
    }
    var totalUsers = addValue;
    if (totalUsers)
    {
        printWindow = window.open(elem.action + '?print&addChk=1&price_id=' + document.getElementById('price_id').value + (addElem.disabled ? '' : '&add=' + encodeURI(addElem.value)));
    }
    return false;
}

function confirmDel()
{
    if (confirm('Удалить?'))
    {
        return true;
    }
    return false;
}

function printOrder ()
{
    if (!priceId)
    {
        alert('Выберите количество учеников в школе');
        return;
    }
    if (!userLoggedin)
    {
        if (confirm('Для покупки необходимо авторизоваться.\nПерейти к авторизации?'))
        {
            window.location.href = '/login/';
        }
    }
    else if (!allInfo)
    {
        if (confirm('Для покупки необходимо заполнить всю информацию в своем профиле.\nПерейти к правке профиля сейчас?'))
        {
            window.location.href = '/pcabinet/profile/';
        }
    }
    else
    {
        var vars = '&priceId=' + priceId;
        countTotalPrice();
        $('#price input:checked').each(function(){
            if ($(this).attr('id') in prices[priceId]){
                vars += '&' + $(this).attr('id') + '=' + $(this).val();
            }
        });
        open('/buy/?print' + vars);
    }
}

function printSupportOrder ()
{
    if (!priceId)
    {
        alert('Выберите количество учеников в школе');
        return;
    }
    if (!userLoggedin)
    {
        if (confirm('Для покупки необходимо авторизоваться.\nПерейти к авторизации?'))
        {
            window.location.href = '/login/';
        }
    }
    else if (!allInfo)
    {
        if (confirm('Для покупки необходимо заполнить всю информацию в своем профиле.\nПерейти к правке профиля сейчас?'))
        {
            window.location.href = '/pcabinet/profile/';
        }
    }
    else
    {
        var vars = '&priceId=' + priceId + '&support=1';
        open('/buy/?print' + vars);
    }
}

function setcookie(name, value, expires, path, domain, secure)
{
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
 
    expires instanceof Date ? expires = expires.toGMTString() : typeof(expires) == 'number' && (expires = (new Date(+(new Date) + expires * 1e3)).toGMTString());
    var r = [name + "=" + escape(value)], s, i;
    for(i in s = {
        expires: expires,
        path: path,
        domain: domain
    }){
        s[i] && r.push(i + "=" + s[i]);
    }
    return secure && r.push("secure"), document.cookie = r.join(";"), true;
}

function changeSubprice(id)
{
    priceId = id;
    if (!priceId)
    {
        for (var first in prices) break;
        for (var i in prices[first]) {
            if (document.getElementById(i + 'Price'))
            {
                document.getElementById(i + 'Price').innerHTML = '';
            }
        }
    }
    else
    {
        for (var i in prices[id]){
            if (document.getElementById(i + 'Price'))
            {
                document.getElementById(i + 'Price').innerHTML = prices[id][i];
            }
        }
    }
    countTotalPrice();
}

function countTotalPrice()
{
    if (!priceId)
    {
        totalPrice = '';
        $('#subprice').css('border', '1px solid red');
    }
    else
    {
        $('#subprice').css('border', '');
        var totalPrice = parseInt(prices[priceId]['base']);

        $('#price input[type=checkbox]').each(function(){
            if ($(this).attr('id') in prices[priceId])
            {
                if ($(this).attr('checked')) {
                    totalPrice += parseInt(prices[priceId][$(this).attr('id')]);
                    $('#' + $(this).attr('id') + 'Price').css('text-decoration', 'none');
                }
                else
                {
                    $('#' + $(this).attr('id') + 'Price').css('text-decoration', 'line-through');
                }
            }
        });
    }
    $('#totalPrice').html(totalPrice);
}

$(document).ready(function() {
    $("a[href*=.jpg],a[href*=.gif],a[href*=.jpeg],a[href*=.png],a[href*=.bmp]").fancybox();
    $('#price input').change(function(elem){
        if ($(this).attr('id') == 'raspGenerator' && $(this).attr('checked'))
        {
            $('#raspEditor').attr('checked', 'checked');
        }
        else if ($(this).attr('id') == 'raspEditor' && !$(this).attr('checked'))
        {
            $('#raspGenerator').attr('checked', '');
        }
        countTotalPrice();
    });
    if ($('#price').length){
        changeSubprice($('#subprice').val());
    }
    $('#supportforum a[href^=#]').each(function(){
        // Узаываю полные пути, т. к. из-за тега <base> якоря указывают на главную страницу.
        var path = window.location.path == undefined ? window.location.pathname : window.location.path;
        $(this).attr('href', path + window.location.search + $(this).attr('href'));
    });
});
