﻿var StringFormat = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/\{(\d+)\}/g, function(m, i) {
        return args[i];
    });
}

var GetOffset = function(elem) {
    if (elem.getBoundingClientRect) {
        return GetOffsetRect(elem);
    } else {
        return GetOffsetSum(elem);
    }
}

var GetOffsetSum = function(elem) {
    var top = 0, left = 0;
    while (elem) {
        top = top + parseInt(elem.offsetTop);
        left = left + parseInt(elem.offsetLeft);
        elem = elem.offsetParent;
    }

    return { top: top, left: left };
}

var GetOffsetRect = function(elem) {
    var box = elem.getBoundingClientRect();
    var body = document.body;
    var docElem = document.documentElement;
    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
    var clientTop = docElem.clientTop || body.clientTop || 0;
    var clientLeft = docElem.clientLeft || body.clientLeft || 0;
    var top = box.top + scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;

    return { top: Math.round(top), left: Math.round(left) };
}

var CurrentOpenedArticle;


$(document).ready(function() {
    var els = $('a.for_tooltips');
    var positionEnum = { LEFT: 0, RIGHT: 1, TOP: 2, BOTTOM: 3, CENTER: 4 };
    function IsGuid(src) {
        var startIndex = src.lastIndexOf('/') + 1;
        var count = src.lastIndexOf('.gif') - startIndex;
        var name = src.substr(startIndex, count);
        if (name == 'small_quest') {
            return true;
        } else if (name == 'small_star') {
            return false;
        }
    }

    function ViewPopupArticle(element, Name, link, Announce, Links, Image) {
        var closeBlock = '<ul class="drop_cyrcle_close"><li><a class="this_close" href="javascript:void(0);">закрыть</a></li></ul>';
        var htm = '<div class="drop_block" style="display:none;">';
        htm += '<div class="drop_article_block">';
        htm += '<div class="shadow"></div>';
        htm += '<div class="corner"></div>';
        htm += '<div class="pad_block">';
        htm += '<ul class="icons_list">';
        htm += '<li class="star border"><span>статьи на тему</span></li>';
        htm += '</ul>';
        if (Image != "" && Image != null) {
            htm += "<img width=\"242\" src=\"" + Image + "\"/>";
        }
        htm += '<h4 style="border-bottom:1px solid #B5CEEA;margin-bottom:4px;"><a href="' + link + '" title="' + Name + '"> ' + Name + '</a></h4>';
		htm += '<p style="border:none;"><a style="color:black;" href="' + link + '" title="">' + Announce + '</a></p>';
        
        /*htm += "<ul class=\"list\">";

        for (var i = 0; i < Links.length; i++) {
            htm += '<li><a href="' + Links[i].Link + '">' + Links[i].Name + '</a><p><a href="' + Links[i].Link + '" title="">' + (Links[i].Announce == null ? '' : Links[i].Announce) + '</a></p></li>';
        }

        htm += "</ul>";*/
        htm += "</div>";
        htm += closeBlock;
        htm += "</div>";
        htm += "</div>";
        $('body').append(htm);
        var tmp = $('body').find('.drop_block');
        var block = $(tmp[tmp.length - 1]);

        var coords = CalculateBlockPosition(element, block);
        if (coords.positionY == positionEnum.TOP) {
            block.find('div.corner').attr('class', 'corner_bot');
            block.addClass('bot');
            block.find('ul.drop_cyrcle_close').remove();
            $(closeBlock).insertAfter(block.find('div.corner_bot'));
        }
        block.css('top', coords.y).css('left', coords.x).css('display', 'block');
        var close = block.find('a.this_close');
        $(close).click(function() {
            block.remove();
            CurrentOpenedArticle = 0;
        });
    }

    function ViewPopupGuide(title, text, link, element) {
        var htm = '<div class="drop_block_2" style="display:none;">';
        htm += "<div class=\"drop_article_block drop_editor_block\">";
        htm += "<div class=\"shadow\"/>";
        htm += "<div class=\"corner\"/>";
        htm += "<div class=\"pad_block\">";
        htm += "<ul class=\"icons_list\">";
        htm += "<li class=\"question border\"><a href=\"javascript:void();\">словарь</a></li>";
        htm += "</ul>";
        htm += '<h4><a href="' + link + '" title="' + title + '">' + title + '</a></h4>';
        htm += '<p><a href="' + link + '" title="' + title + '">' + text + '</a></p>';
        htm += "</div>";
        htm += "</div>";
        htm += "</div>";

        $('body').append(htm);
        var tmp = $('body').find('.drop_block_2');
        var block = $(tmp[tmp.length - 1]);

        var coords = CalculateBlockPosition($(element), block);
        if (coords.positionY == positionEnum.TOP) {
            block.find('div.corner').attr('class', 'corner_bot');
            block.addClass('bot');
        }
        block.css('top', coords.y).css('left', coords.x).css('display', 'block');
        return block;
    }

    function CalculateBlockPosition(el, block) {
        var coords = GetOffset(el[0]);
        var elInfo = { x: coords.left, y: coords.top, height: el.height(), width: el.width() };
        var bWidth = block.width();
        var bHeight = block.height();
        var wHeight = $(window).height();
        var wWidth = $(window).width();
        var currentPosition = {};
        currentPosition.HasBottomSpace = ((elInfo.y + elInfo.height + bHeight) - $(window).scrollTop() < wHeight);
        currentPosition.HasTopSpace = (elInfo.y - $(window).scrollTop() - bHeight > 0);
        currentPosition.HasLeftSpace = (elInfo.x - bWidth > 0);
        currentPosition.HasRightSpace = (elInfo.x + elInfo.width + bWidth < wWidth);
        var answer = { x: (elInfo.x + elInfo.width), y: (elInfo.y + elInfo.height), positionX: positionEnum.RIGHT, positionY: positionEnum.BOTTOM };

        if (currentPosition.HasBottomSpace) {
            answer.y = (elInfo.y + elInfo.height);
            answer.positionY = positionEnum.BOTTOM;
            /***<onlyFor4living>***/
            answer.x = (elInfo.x + elInfo.width);
            answer.positionX = positionEnum.RIGHT;
            /***</onlyFor4living>***/
        } else if (currentPosition.HasTopSpace) {
            answer.y = (elInfo.y - bHeight - elInfo.height);
            answer.positionY = positionEnum.TOP;
            /***<onlyFor4living>***/
            answer.x = (elInfo.x - bWidth - elInfo.width - 10);
            answer.positionX = positionEnum.LEFT;
            /***<onlyFor4living>***/
        }
        /***<onlyFor4living>***/
        /*if (currentPosition.HasLeftSpace) {
        answer.x = (elInfo.x - bWidth - elInfo.width);
        answer.positionX = positionEnum.LEFT;
        } else if (currentPosition.HasRightSpace) {
        answer.x = (elInfo.x + elInfo.width);
        answer.positionX = positionEnum.RIGHT;
        }*/
        /***</onlyFor4living>***/
        return answer;
    }

    var guideBlockIsMouseOvered = false;

    $(els).hover(function() {
        var el1 = $(this).children("img.element");
        var first = el1[0];
        if (IsGuid($(first).attr('src'))) {
            var id = $(first).attr('rel');
            var closeGuideBlock = function(block) {
                setTimeout(function() {
                    if (guideBlockIsMouseOvered == false) {
                        $('body').find('.drop_block_2').remove();
                    } else if (guideBlockIsMouseOvered == true) {
                        closeGuideBlock(block);
                    }
                }, 1500);
            }
            function DescrOk(/*index,*/ data) {
		
                $('body').find('.drop_block_2').remove();
                var block = ViewPopupGuide(data.Name, data.Text, data.Link, first);
                block.hover(function() { guideBlockIsMouseOvered = true; }, function() { guideBlockIsMouseOvered = false; });
                closeGuideBlock(block);
            }
            //ServiceProxy.GetGuidById(parseInt(id), DescrOk);
$.getJSON("http://www.4living.ru/handlers/AjaxHandler.ashx", 
{ command: "guidbyid", guide: id }, 
function(data){
   DescrOk(data);
});
        }
    });

    var articles = $(els).find('img.element');
    articles.click(function() {
        if (!IsGuid($(this).attr('src'))) {
            var cur = $(this);
            if ($(this).parent().find('div').length == 0) {
                var id = $(this).attr('rel');
                if (id != CurrentOpenedArticle) {
                    CurrentOpenedArticle = id;
                    function DescrOk(data) {
                        ViewPopupArticle(cur, data.Name, data.Link, (data.Announce == null ? "" : data.Announce), data.Links, data.Image);
                    }
                    var title = $('span#section_id').attr('title');
                    var index = title.indexOf(':');
                    if (index > -1) { title = title.substr(0, index); }
                    //ServiceProxy.GetArticleById(parseInt(id), title, DescrOk);
			$.getJSON("http://www.4living.ru/handlers/AjaxHandler.ashx", { command: "artbyid", id: id, curid:title }, function(data){
   DescrOk(data);
});
                }
            }
        }

    });
});
