var statsRequest = null;
var statsCache = [];

function zebra(){
	 $(".sortable").tablesorter({
        widgets: ['zebra']
    });
}
/*function StatsTooltip(params) {

    function makeRequest(params, targetElement) {

        function initTooltip(targetElement) {
            var tooltipContainer = $('#statsTooltip');
            if (!tooltipContainer.size()) {
                // creating container
                tooltipContainer = $('<div>').attr('id', 'statsTooltip');
                $('.general-container').append(tooltipContainer);
            }
            tooltipContainer.hide();
            var img = $('<img>').attr('src', '/images/ajax-loader-big.gif');
            tooltipContainer.empty();
            tooltipContainer.append(img);
            var position = $(targetElement).position();
            tooltipContainer.css('top', position.top + 3).css('left', position.left - 220).show();
        }

        function fillTooltip(resultObject, targetElement) {

            var tooltipContainer = $('#statsTooltip');
            var ul = $('<ul>').addClass('stats_tooltip_list');

            if (!(resultObject instanceof Array)) {
                $.each(resultObject['item'], function(num, item) {
                    var text = item.ourTeam + ' ' + item.score + ' ' + item.againstTeam;
                    var a = $('<a>').attr('href', '/calendar/game/' + item.game_id + '/').text(text);
                    $('<li>').append(a).appendTo(ul);
                });
            } 

            var position = $(targetElement).position();
            tooltipContainer.empty().append(ul).css('top', position.top + 3).css('left', position.left - 220);

        }

        function getCache(params) {
            var hash = params.competitionID + '_' + params.teamID + '_' + params.stat_type;
            if (typeof (statsCache[hash]) == 'undefined') {
                return false;
            } else {
                return statsCache[hash];
            }
        }

        function setCache(params, data) {
            var hash = params.competitionID + '_' + params.teamID + '_' + params.stat_type;
            statsCache[hash] = data;
        }

        if (statsRequest != null) {
            statsRequest.abort();
        }
        statsRequest = null;
        initTooltip(targetElement);

        var cache = getCache(params);
        if (cache) {
            fillTooltip(cache, targetElement);
        } else {
            statsRequest = $.getJSON("/api/stat/team_games/",params,function(resultObject, textStatus){
                if (textStatus == 'success') {
                    setCache(params, resultObject);
                    fillTooltip(resultObject, targetElement);
                }
            });
        }

    }

    function linkOver() {
        makeRequest({
            'competitionID': $(this).parents('.stats').attr('competitionIDs'),
            'teamID': $(this).parents('tr').attr('teamID'),
            'stat_type': params.stat_type
        }, $(this));
    }

    function linkOut() {

    }

    var config = {
        sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
        interval: 200, // number = milliseconds for onMouseOver polling interval
        over: linkOver, // function = onMouseOver callback (REQUIRED)
        out: linkOut,
        timeout: 1000  // number = milliseconds delay before onMouseOut
    };


    var link = $("<a>").attr('href', '#');
    var elements = $(params.selector).wrapInner(link).find('a').click(function(e) {
        e.preventDefault();
    }).end();
    elements = $.grep(elements, function(n, i){
        return $(n).text() != '0';
    });

    $(elements).find('a').hoverIntent( config );

    $('.bottomTab').mouseleave(function(e) {
        if ($(e.relatedTarget).attr('id') != 'statsTooltip') {
            $('#statsTooltip').hide();
        }
    });

}*/

$.tablesorter.addWidget({
    id: "numFirstColumn",
    format: function(table) {
        $('tr', table).each(function(i, item) {
            $(item).find('td:first').text(i);
        });
    }
});

var objectTranslate = function() {
    var re = /\/\/en\./g;
    var domain = window.location.href.match(re);
    if (domain != null && domain.length > 0) {
		eval("var smartReplace = {"+$('#dictionary').html()+"}");
		google.language.translate({text: smartTranslit(document.title, smartReplace), type: 'text'}, 'ru', 'en', function(result) {
			if (result.translation) {
				document.title = result.translation;
			}
		});
		$('.translate').each(function() {
			var _this = $(this),
				text = _this.html();
			text = smartTranslit(text, smartReplace);
			$(this).html(text);
			$(this).translate('ru', 'en',
				{
					complete: function() {
						_this.css('visibility', 'visible');
						doCufon();
					}
				}
			);
		});
		$(".translate[title!=''], .translate *[title!='']").each(function() {
			var _this = $(this);
			google.language.translate({text: $(this).attr('title'), type: 'text'}, 'ru', 'en', function(result) {
				if (result.translation) {
					_this.attr('title', result.translation);
				}
			});
		});
    }
    else $('.translate').css('visibility', 'visible');
};

var smartTranslit = function(text, smartReplace) {
	var	key,
		i,
		re = '/',
		smartRe = [],
		newKey,
		index,
		cases = undefined;

	for (key in smartReplace)
	{
		re += key+'|';
		index = key.indexOf('(')
		if (index > 0)
		{
			newKey = key.substring(0, index);
			cases = key.substr(index+3).slice(0,-1).split('|');
		}
		else
		{
			newKey = key;
		}
		if (cases && cases.length > 0)
		{
			i = 0;
			while(i < cases.length)
			{
				smartRe.push({'resultCase' : newKey+cases[i], 'result' : smartReplace[key]});
				i++;
			}
		}
	}
	re = re.slice(0,-1)+'/g';
	function transliterate(str)
	{
		var i = 0;
		while(i < smartRe.length)
		{
			if (smartRe[i].resultCase == str) return smartRe[i].result;
			i++;
		}
		return translit(str);
	}
	return eval("text.replace("+re+", transliterate)");
}

var objectTranslit = function() {
    var re = /\/\/en\./g;
    var domain = window.location.href.match(re);
    $('.translit').each(function() {
		if (domain != null && domain.length > 0) this.innerHTML = translit(this.innerHTML);
    	$(this).css('visibility', 'visible');
	});
};

var translit = function(text) {
	var ru2en = {"А":"A", "Б":"B", "В":"V", "Г":"G", "Д":"D", "Е":"E", "Ё":"Yo", "Ж":"Zh", "З":"Z", "И":"I", "Й":"Y", "К":"K", "Л":"L", "М":"M", "Н":"N", "О":"O", "П":"P", "Р":"R", "С":"S", "Т":"T", "У":"U", "Ф":"F", "Х":"H", "Ц":"Ts", "Ч":"Ch", "Ш":"Sh", "Щ":"Tsh", "Ъ":"", "Ы":"Y", "Ь":"'", "Э":"E", "Ю":"Yu", "Я":"Ya", "а":"a", "б":"b", "в":"v", "г":"g", "д":"d", "е":"e", "ё":"yo", "ж":"zh", "з":"z", "и":"i", "й":"y", "к":"k", "л":"l", "м":"m", "н":"n", "о":"o", "п":"p", "р":"r", "с":"s", "т":"t", "у":"u", "ф":"f", "х":"h", "ц":"ts", "ч":"ch", "ш":"sh", "щ":"tsh", "ъ":"", "ы":"y", "ь":"'", "э":"e", "ю":"yu", "я":"ya"},
		ru2enRE = /(?:А|Б|В|Г|Д|Е|Ё|Ж|З|И|Й|К|Л|М|Н|О|П|Р|С|Т|У|Ф|Х|Ц|Ч|Ш|Щ|Ъ|Ы|Ь|Э|Ю|Я|а|б|в|г|д|е|ё|ж|з|и|й|к|л|м|н|о|п|р|с|т|у|ф|х|ц|ч|ш|щ|ъ|ы|ь|э|ю|я)/g;

	function transliterate(str) {
		return ru2en[str];
	}
	return text.replace(ru2enRE, transliterate);
}

var doCufon = function() {
    Cufon.replace(['div.content>h1:first-child'], {
        fontFamily: 'Politica',
        fontSize: '33px',
        color: '#A3A4A6'
    });
    Cufon.now();
};

var replaceQuotes = function() {
    var re = /\/\/en\./g;
    var domain = window.location.href.match(re);
    if (domain != null && domain.length > 0)
    {
        $(".content-container p, .content > div[class!='guestbook']:contains('\"'), .random-product *").each(function() {
    		var _this = $(this);
    		var text = _this.html();
    		$(this).html(text.replace(/(?:«|»)/g, '\"'));
    	});
    	return;
    }

    $(".content-container p, .content > div[class!='guestbook']:contains('\"'), .random-product *").each(function() {
		var _this = $(this);
		var text = _this.html();
		var re = /([^=])\"([^<>\"=]+)\"([ !\.,\?\:<\)]|$)/g;
		text.replace(/&quot;/g, '\"');
		$(this).html(text.replace(re, '$1&laquo;$2&raquo;$3'));
	});
};

$(document).ready(function()
{
	/*Опросы*/

	// передаем опции в  ajaxSubmit
	jQuery('#pollForm').submit(function() {
		var options = {
	  	target: ".pollBlock",
		url: "/api/poll/",
		pollForm:function(){
			$('#pollForm').hide();
			$('.pollBlock').html('<img src="/images/ajax-loader-big.gif"/>');
		},
		success: function() {

	  }
	};
		$("#pollForm").ajaxSubmit(options);
		 return false;
	});
	
	/*Пагинг в архиве опросов*/
	/*$('.poll-paging a').click(function() {
      var year = $(this).attr('year');
      $.get('.', {
        year : year
      }, function(data) {
        $('.content').html(data);
      }, 'html');
      return false;
    });*/
	/*/Пагинг в архиве опросов*/

    $(".sortable").tablesorter({
        widgets: ['zebra']
    });

    // <Materials text toggler in materials list>
    $('ul.text_list .text').hide();
    $('ul.text_list a').click(function(e) {
        e.preventDefault();
        $(this).parent().find('.text').toggle('slow');
    })


    // <search>
    var already_focused = false;
    $('#search_block input').focus(function() {
        if (!already_focused) {
            $(this).val('');
        }
        already_focused = true;
    });

    $('#search_block a').click(function(e) {
        e.preventDefault();
        $(this).parent().find('input').val('');
    });
    // </search>

    // <stats table tooltips>
   /* StatsTooltip( {
        selector: '.stats_fixtures_list tr:has(td) td:nth-child(3)',
        stat_type: "ALL"
    });

    StatsTooltip( {
        selector: '.stats_fixtures_list tr:has(td) td:nth-child(4)',
        stat_type: "W"
    });

    StatsTooltip( {
        selector: '.stats_fixtures_list tr:has(td) td:nth-child(5)',
        stat_type: "WO"
    });

    StatsTooltip( {
        selector: '.stats_fixtures_list tr:has(td) td:nth-child(6)',
        stat_type: "WB"
    });

    StatsTooltip( {
        selector: '.stats_fixtures_list tr:has(td) td:nth-child(7)',
        stat_type: "LB"
    });

    StatsTooltip( {
        selector: '.stats_fixtures_list tr:has(td) td:nth-child(8)',
        stat_type: "LO"
    });

    StatsTooltip( {
        selector: '.stats_fixtures_list tr:has(td) td:nth-child(9)',
        stat_type: "L"
    });*/

    // </stats table tooltips>

    $('.navbar-main ul li:nth-child(6)').addClass('starsHere');

    var undefined;
    var tmr;

    $('.navbar-main li').mouseover(function()
    {
        if (tmr != undefined) {
            clearTimeout(tmr);
            tmr = undefined;
        }
        $('.navbar-main li.active').removeClass('active');
        $('.navbar-main .l, .navbar-main .r').removeClass('on');
        $('.navbar-main .nextActive').removeClass('nextActive');
        var currentOver = $(this);
        currentOver.addClass('active').prev().addClass('nextActive');
        if (currentOver.hasClass('last'))
            currentOver.parent().next().addClass('on');
        else if (currentOver.prev().length == 0)
            currentOver.parent().prev().addClass('on');
    }).mouseout(function()
    {
        $(this).removeClass('active').prev().removeClass('nextActive');
        $('.navbar-main .l, .navbar-main .r').removeClass('on');
        tmr = window.setTimeout(function()
        {
            $('.navbar-main .current').eq(0).trigger('mouseover');
        }, 300);
    }).filter('.active').prev().addClass('nextActive');

    $('.newsItem').mouseover(function()
    {
        $('#newsImage').attr('src', $(this).attr('imageUrl')).attr('alt', $(this).attr('title'));
    }).eq(0).trigger('mouseover');

    $('table:not([class~=nostripe]) tr:nth-child(odd)').addClass('tr-bg');

    setTabs();

    $('.login-box input, #annoyingWindow input').focus(function(){
        $(this).prev('label').css('opacity', this.value.length > 0 ? '0' : '0.5');
    }).blur(function(){
        $(this).prev('label').css('opacity', this.value.length > 0 ? '0' : '1');
    }).keyup(function(){
        $(this).prev('label').css('opacity', this.value.length > 0 ? '0' : '1');
    }).each(function(){
        if (this.value.length > 0)
            $(this).prev('label').css('opacity', '0');
    });

	$("#pool-archive-list a.pool-archive-link").click(function(){
		var $_this = $(this);
		
        if($_this.data('poll'))
        	$("#pool-archive-poll-" + $_this.attr('pid')).slideToggle();  
        else
        {
        	$.get($_this.attr('href'), function(data){
        		$_this.data('poll', data).after('<div class="hidden pool-archive-poll" id="pool-archive-poll-' + $_this.attr('pid') + '">' + data + '</div>');
        		$("#pool-archive-poll-" + $_this.attr('pid')).slideToggle();
        		objectTranslate();
        	    objectTranslit();
        	}, 'html' );   
        }
        return false;
	});

	replaceQuotes();
	objectTranslate();
    objectTranslit();
    doCufon();

	$('.poll-button').click(function(){polls_click($(this))});
});

/**
 Common functions
 Accessible everywhere
 */

function styleFileInput(selector)
{
    var wrap =
    $('<div class="fileWrapper"><div class="fakeButton"></div><div class="blocker"></div></div>')
    .append($('<div class="fileName"><img src="/images/transparent.gif"/><span></span></div>').css({
        display: 'none'
    }));
    var fileInput = $(selector)
    .attr('value', '')
    .css({
        position: 'absolute',
        width: 'auto',
        'float': 'none',
        'padding': 0,
        width: '219px',
        fontSize: '14px'
    })
    .addClass('customFile')
    .change(function()
    {
        var file = $(this).attr('value');
        var RegExExt = /.*\.(.*)/;
        if (file.match(/\//))
            file = file.replace(/.*\/(.*)/, "$1");
        if (file.match(/\\/))
            file = file.replace(/.*\\(.*)/, "$1");
        var ext = file.replace(RegExExt, "$1");

        var img = '';
        if (ext) {
            switch (ext.toLowerCase()) {
                case 'jpg':
                case 'jpeg':
                case 'png':
                case 'gif':
                    img = 'chk_on.png';
                    break;
                default:
                    img = 'chk_off.png';
                    break;
            }
        }
        $(this).parent().children('.fileName').children('img').css({
            background: 'url(/images/' + img + ')'
        }).parent().children('span').text(file).parent().show();
    });
    $(selector).after(wrap);
    wrap.children('.fakeButton').before(fileInput);
}

function setCookie(name, value, expires, path, domain, secure)
{
    var curCookie = name + "=" + value +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

function getCookie(name)
{
    var prefix = name + "=";
    var cookieStartIndex = document.cookie.indexOf(prefix);
    if (cookieStartIndex == -1)
        return null;
    var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
    if (cookieEndIndex == -1)
        cookieEndIndex = document.cookie.length;
    return decodeURIComponent(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

function deleteCookie(name)
{
    document.cookie = name + "=; expires=Fri, 31 Dec 1979 23:59:59 GMT;";
}
Array.prototype.inArray = function(item)
{
    for (var i = 0, l = this.length; i < l; i++) {
        if (this[i] == item) {
            return true;
        }
    }
    return false;
}

function setTabs()
{
    $('.bottomTabs a').click(function()
    {
        $(this).parent('div').parent('li').siblings().removeClass('current');
        $(this).parent('div').parent('li').addClass('current');
        var id = $(this).attr('sectionId');
        $('.bottomTab').hide();
        $('#content' + id).show();
        $('#content' + id + ' .message').removeClass('hidden');
        return false;
    }).eq(0).trigger('click');

    if (location.href.indexOf('?') > -1) {
        var url = location.href.substr(location.href.indexOf('?') + 1).split('&');
        var tab, param;
        for (var i = 0; i < url.length; i++) {
            param = url[i].split('=');
            if (param[0] == 'tab')
                tab = param[1];
        }
    }

    if (tab) {
        $('.bottomTabs a').each(function()
        {
            var _this = $(this);
            var tabAttr = _this.attr('order') ? 'Auto' + _this.attr('order') : _this.attr('sectionId');
            if (tabAttr == tab)
                _this.trigger('click');
        })
    }
}


