
//=====Open external links in new window/tab      ****DISABLED*****
/*$(document).ready(function(){

	jQuery("a[href^=\'http:\']").not("[href*=\'" + window.location.host + "\']").not("[target]").attr("target", "_blank");
});*/
//=====END


//==========SEARCH START==========
$(document).ready(function() {
        preload([
                "/images/search_bot.png",
                "/images/search_bot_withoutlast.png",
                "/images/search_bot_over.png",
                "/images/search_top.png",
                "/images/search_top_over.png",
                "/images/search_backg.png"
        ]);

        $("#AutoComplite").click(function(event){
                 event.stopPropagation();
        });

        $("body").click(function(){
                $("#AutoComplite").fadeOut(200);
        });
        $("[placeholder]").focus(function() {
                var input = $(this);
                if (input.val() == input.attr("placeholder")) {
                  input.val("");
                  input.removeClass("placeholder");
                }
              }).blur(function() {
                var input = $(this);
                if (input.val() == "") {
                  input.addClass("placeholder");
                  input.val(input.attr("placeholder"));
                }
              }).blur();

});
var sTimeout;
function searchSuggest(sstring) {
        $("div#AutoComplite").fadeOut(200);
        if (sTimeout != null){ window.clearTimeout(sTimeout); }
        if (sstring.length > 2) {
                sTimeout = window.setTimeout("suggestRequest(\"" + sstring + "\");", 600);
        }
}

var searchFinished = false;
var searchLoaddingTimeoutFinished = false;

function suggestRequest(sstring) {
        $(".searchForm #searchLoading").css("visibility", "visible");
        searchLoaddingTimeoutFinished = false;
        searchFinished = false;
        window.setTimeout(function() {
                if (searchFinished)  {
                        $(".searchForm #searchLoading").css("visibility", "hidden");
                } else {
                        searchLoaddingTimeoutFinished = true;
                }
        }, 500);

        $.get("/skins/esquire/special/search/ajaxsearch.php", {ss: sstring}, function(data) {
                if (data != "0") {
                        $("div#AutoComplite").fadeOut(200);
                        $("div#AutoComplite div.repy").html(data);
                        if ($("#AutoComplite ul li.l").length <= 0) {
                                $("#AutoComplite").addClass("withOutLast");
                        } else {
                                $("#AutoComplite").removeClass("withOutLast");
                        }
                        $("#AutoComplite ul li.l").hover(
                                function() {
                                        $("#AutoComplite").attr("class", "over");
                                },
                                function() {
                                        $("#AutoComplite").attr("class", "");
                                }
                        );
                        $("#AutoComplite ul li.f").hover(
                                function() {
                                        $("#AutoComplite .in").css("background", "url(/images/search_top_over.png) 0 0 no-repeat");
                                },
                                function() {
                                        $("#AutoComplite .in").css("background", "url(/images/search_top.png) 0 0 no-repeat");
                                }
                        );
                        if ($("#AutoComplite ul li.l").length > 0) {
                                $("#AutoComplite").click(function(event){
                                        window.location.replace($("#AutoComplite ul li.l").children("a").attr("href"));
                                });
                        }
                        $("#AutoComplite .in").click(function(event){
                                event.stopPropagation();
                        });
                        $("#AutoComplite ul li").click(function(event){
                                window.location.replace($(this).children("a").attr("href"));
                                event.stopPropagation();
                        });

                        $("div#AutoComplite").fadeIn(300);

                } else {
                        $("div#AutoComplite").fadeOut(200);
                }

                if (searchLoaddingTimeoutFinished) {
                        $(".searchForm #searchLoading").css("visibility", "hidden");
                }
                searchFinished = true;
        });
}
//==========SEARCH FINISH==========



//====WHERE2GO START=====
var where2GoInProgress = false;
$(document).ready(function() {
    if(typeof(where2GoCount) !== 'undefined') {
        $(".where2go .container").height($(".where2go .inner").height());
	var itemWidth = 202 + 19;
	$(".where2go .button.next").click(function(){
	    if (!$(this).hasClass("inactive") && !where2GoInProgress) {
		where2GoCurrent++;
                where2GoInProgress = true;
		$(".where2go .inner").animate({left: "-="+itemWidth}, 400, 'swing', function() {
                    where2GoInProgress = false;
                    if (where2GoCurrent + 1 >= where2GoCount) {
                        $(".where2go .button.next").addClass("inactive");
                    }
                });
		$(".where2go .button.prev").removeClass("inactive");
	    }
	});
	$(".where2go .button.prev").click(function(){
	    if (!$(this).hasClass("inactive") && !where2GoInProgress) {
		where2GoCurrent--;
                where2GoInProgress = true;
		$(".where2go .inner").animate({left: "+="+itemWidth}, 400, 'swing', function() {
                    where2GoInProgress = false;
                    if (where2GoCurrent <= 0) {
                        $(".where2go .button.prev").addClass("inactive");
                    }
                });
		$(".where2go .button.next").removeClass("inactive");
	    }
	});
        $(".where2go").bind("mousewheel", function(event, delta){

            if (where2GoInProgress) {
                event.preventDefault();
            } else {
                if (delta < 0) {
                    var button = $(".where2go .button.next");
                } else {
                    var button = $(".where2go .button.prev");
                }
                button.click();
                if (!button.hasClass("inactive")) {
                    event.preventDefault();
                }
            }
        })

    }
});
//====WHERE2GO FINISH=====


//====SHARE-BOX START=====
$(document).ready(function(){
    if ($(".share-button").length > 0) {
        preload([
            '/images/social-share-button-on.png?1',
            '/images/share-menu-top.png',
            '/images/share-menu-bottom.png']);
        $(".share-button").toggle(function(){
            initGoooglePlus()
            $(".share-button").addClass("active");
            $(".share-menu").show();
            $("body").one("click", function(){
                $(".share-button").removeClass("active");
                $(".share-menu").hide();
            });
        }, function() {
            $('body').click()
        });
        
        $(".share-menu").click(function(event){
            event.stopPropagation();
        });
    }
});
function openShareLink(link, width, height) {
    if (width === undefined) {
        width = 640;
    }
    if (height === undefined) {
        height = 480;
    }
    window.open(link,"mywindow","width="+width+",height="+height+",toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no");
}
var googlePlusInited = false;
function initGoooglePlus() {
    if (!googlePlusInited) {
         googlePlusInited = true;
        $("#google-plus-one-icon").hide();
        window.___gcfg = {lang: "ru"};

        (function() {
            var po = document.createElement("script"); po.type = "text/javascript"; po.async = true;
            po.src = "https://apis.google.com/js/plusone.js";
            var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(po, s);
        })();
    }
}
//======SHARE-BOX FINISH=========



//=======NUMBERS WIDGET START========
$(document).ready(function(){
    var number = $(".nw-box");
    if (number.length > 0) {
        setTimeout(function() {
            number.html(formatNumbers(number.html(), "&nbsp;"));
            resizeNumber(number, $(".numbers-widget"));
        }, 300);

        function resizeNumber(numberDiv, allDiv) {
            var maxHeight = 120;
            var maxWidth = 210;
            var width = 1;
            var height = 1;
            var fontSize = 10;
            var prevFontSize = fontSize;
            while (width < maxWidth && height < maxHeight && fontSize < 500) {
                prevFontSize = fontSize;
                fontSize = fontSize*1.1;
                numberDiv.css({"font-size": fontSize + "px", "word-spacing": -0.1*fontSize + "px"});
                width = numberDiv.width();
                height = numberDiv.height();
            }

            numberDiv.css({"font-size": prevFontSize});
            allDiv.css({visibility: "visible"});
        }
    }
});
//=======NUMBERS WIDGET FINISH=======


//==========FANSY BOX START=========
jQuery(document).ready(function() {
    jQuery("a[class=search_results_preview]").fancybox({
            "zoomSpeedIn"			: 300,
            "zoomSpeedOut"			: 300,
            "overlayShow"			: false,
            "frameWidth"			: 480,
            "frameHeight"			: 320,
            "hideOnContentClick"	: false,
            "showTitle"				: false
    });

    jQuery("a[class=fancybox-cover]").fancybox({
            "zoomSpeedIn"			: 300,
            "zoomSpeedOut"			: 300,
            "overlayShow"			: true,
            "padding"				: 0,
            "overlayOpacity"		: 0.7,
            "overlayColor"			: "#000",
            "outerClass"			: "Fancybox-cover",
            "showTitle"				: false
    });

    jQuery("a[class=fancybox-nobg]").fancybox({
            "zoomSpeedIn"			: 300,
            "zoomSpeedOut"			: 300,
            "overlayShow"			: true,
            "padding"				: 0,
            "overlayOpacity"		: 0,
            "overlayColor"			: "#000",
            "outerClass"			: "Fancybox-nobg",
            "showTitle"				: false
    });

    jQuery("a[class=fancybox]").fancybox({
            "zoomSpeedIn"			: 300,
            "zoomSpeedOut"			: 300,
            "overlayShow"			: true,
            "padding"				: 0,
            "overlayOpacity"		: 0.7,
            "overlayColor"			: "#FFF",
            "showTitle"				: false,
            "imageScale"            : false,
            "centerOnScroll"        : false
    }).hover(function() {
        
        var img = $(this).find('img')
        if (img.length > 0) {
            img = img.first()
        } else {
            return
        }
        var position = img.position()
        var shift = Math.ceil(Math.min(img.width(), img.height())*0.04)
        var lens = $('<img/>')
            .attr('src', '/images/fancybox-hover-lens.png')
            .css({
                position: 'absolute',
                left: position.left + img.width() - 33 - shift + 'px',
                top: position.top + img.height() - 33 - shift +'px'
            })

        
        $(this)
            .data('zoom-button', lens)
            .append(lens)
    }, function() {
        $(this).data('zoom-button').remove()
    })
});

//======FANSY BOX FINISH======



//======FOOTNOTE START========

$(document).ready(function() {
    var fading = false;
    $('.footnote').mouseenter(function() {
        if (fading) {
            return;
        }
        var text = $(this).find('.note').html();
        var position = $(this).offset();
        $(this).addClass('active');
        var footnote = $('<div class="footnote-bar" style="left:'+(position.left-19)+'px; top:'+(position.top-17)+'px;">'+text+'</div>').appendTo($('body'));
        footnote.fadeIn(100);
        var self = $(this);
        footnote.mouseleave(function() {
            fading = true;
            footnote.fadeOut(100, function() {
                fading = false;
                self.removeClass('active');
                footnote.remove();
            });
        });
    });
});
//======FOOTNOTE FINISH=======



//=======ZEBRISER START=======
$.fn.zebrise = function() { 
    $(this).each(function(n, zebra) {
        var m = 0;
        $(zebra).children().each(function (n, row) {
            if (!$(row).hasClass('zebrise-skip')) {
                if (m % 2 == 0) {
                    $(row).addClass('zebrised');
                }
                m++;
            }
        });
    });
}
$(document).ready(function() {
    $('.zebrise').zebrise();
});
//=======ZEBRISER FINISH=======


//=======MAP TOOLTIPS START====
$(document).ready(function(){
    var maps = $('.tooltipsMap');
    if (maps.length > 0) {
        maps.each(function() {
            $(this).data('tooltip', $('<div class="map-tooltip"><div class="triangle"></div><div class="title"></div><div class="text"></div></div>').appendTo('body'));
        });
        var areas = $('.tooltipsMap area');
        areas.hover(function(){
            $(this).parent('.tooltipsMap').data('userTryed', true);
            showTooltip($(this));
        }, function() {
            hideTooltip($(this));
        });
        function showTooltip(elem) {
            var coords = elem.attr('coords').split(',');
            var imgPosition = $('img[usemap=#' + elem.parent().attr('name') + ']').offset();
            var toolPosition = {
                x: imgPosition.left + parseInt(coords[0]) - parseInt(coords[2]),
                y: imgPosition.top + parseInt(coords[1]) + parseInt(coords[2])
            };
            var tooltip = elem.parent('.tooltipsMap').data('tooltip');
            
            if (elem.data('title')) {
                tooltip.find('.title')
                    .html(elem.data('title'))
                    .show();
            } else {
                tooltip.find('.title').hide()
            }
            tooltip.find('.text').html(elem.data('text'))
            tooltip
                .css({left: toolPosition.x, top: toolPosition.y})
                .slideDown(70);
        }
        function hideTooltip(elem) {
            elem.parent('.tooltipsMap').data('tooltip').hide();
        }
    
        //autostart
        $('.tooltipsMap.autostart').each(function() {
            var map = $(this);
            map.data('currentArea', false);
            var areas = map.find('area');
            setTimeout(function() {showAutoTooltip(map, areas);}, 300);
            var period = setInterval(function() {
                if (!map.data('userTryed')) {
                    showAutoTooltip(map, areas);
                } else {
                    clearInterval(period);
                }
            }, 2000);
        })
    
        function showAutoTooltip(map, areas) {
            if (map.data('currentArea') !== false) {
                hideTooltip($(areas[map.data('currentArea')]));
            }
            if (map.data('currentArea') === false || areas.length <= map.data('currentArea') + 1) {
                map.data('currentArea', 0);
            } else {
                map.data('currentArea', map.data('currentArea') + 1);
            }
            showTooltip($(areas[map.data('currentArea')]));
        }
    }
});
//=======MAP TOOLTIPS FINISH====




//=========EXPANDER START========

$(document).ready(function() {
    $('.expander.show').click(function() {
        var self = $(this);
        if (self.data('expanderurl')) {
            var container = self.next('.expander').find('.ajax-data');
            if (container.length > 0) {
                container.addClass('ajaxloader');
                $.get(self.data('expanderurl'), function(data) {
                    container.html(data);
                    container.removeClass('ajaxloader');
                });
            }
            self.data('expanderurl', false);
        }
        
        self.next('.expander').slideDown(300);
        self.hide();
    });
    $('.expander .hide').click(function() {
        var div = $(this).parents('.expander');
        div.slideUp(300, function() {
           div.prev('.expander.show').show(); 
        });

    });
});

//=========EXPANDER FINISH========



//=========POTD WIDGET START======
function potdWidgetArrowClick(arrow) {
    var widget = arrow.parents('.potd-widget')
    if (widget.hasClass('loading')) {
        return;
    }
    widget.addClass('loading');
    $.get('/ajax/potd-widget.php', {'item-id': arrow.data('itemid')}, function(data){
        $(data).find('img').imgpreload(function() {
            widget.removeClass('loading');
            widget.html(data);
            initCount();// FOR A/B TEST
        }, 2000);

    });
}
//=========POTD WIDGET FINISH======
