﻿function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

var tooltip = null;
var ajaxhandler = "/handlers/AjaxHandler.ashx";
var Obj = {
    start: function () {
        Obj.setol();
        Obj.cleardict();
        Obj.h1hack();
        Obj.slide();
        Obj.bluetextsize();
        Obj.accordion();
        Obj.objects();
        Obj.visitreg();
        Obj.equalslists();
        if ($('#SearchButton') && $('#SearchButton').length > 0) {
            Obj.search();

        }
        Obj.rating();
		Obj.runFourteen();
    },
    objects: function (element) {
        tooltip = $("#for-tooltip div[class=tooltip]");
        var Elements = $('div.One, div.Two, div.Three, div.Four, div.Five, div.Six,div.Seven , div.Eight, div.Nine, div.Ten, div.Eleven, div.Twelve'); //
        $(Elements).each(function (index, element) {
            var cssClass = $(element).attr("class");
            switch (cssClass) {
                case "One":
                    Obj.run(element, 13, 68, "TinyImage", "BigImageW495", false, false, 2);
                    break;
                case "Two":
                    Obj.run(element, 0, 0, "", "MiddleImage", false, false, 2);
                    break;
                case "Three":
                    Obj.run(element, 0, 0, "", "TinyImage", false, false, 1);
                    break;
                case "Four":
                    Obj.run(element, 13, 120, "TinyImgWH108", "BigImageW495", false, false, 2);
                    break;
                case "Five":
                    Obj.run(element, 13, 68, "TinyImage", "BigImgW425H328", true, false, 2);
                    break;
                case "Six":
                    Obj.run(element, 13, 120, "TinyImgWH108", "TinyImgWH108", false, true, 2);
                    break;
                case "Seven":
                    Obj.run(element, 13, 68, "TinyImage", "VerticalImage", true, false, 2);
                    break;
                case "Eight":
                    Obj.run(element, 13, 68, "TinyImage", "VertImgBig", true, false, 2);
                    break;
                case "Nine":
                    Obj.run(element, 12, 120, "TinyImgWH108", "SquareImage", false, false, 2);
                    break;
                case "Ten":
                    Obj.run(element, 0, 120, "TinyImgWH108", "SquareImage", true, false, 1);
                    break;
                case "Eleven":
                    Obj.run(element, 13, 85, "TinyImg82", "BigImageW495", false, false, 1);
                    break;
                case "Twelve":
                    Obj.run(element, 0, 0, "BigImageW495", "BigImageW495", false, false, 1);
                    break;
            }
        });
    },
    universalmini: function (element) {
        var images = $(element).find('img');
        $(images).each(function (ind, img) {
            $(img).attr("title", "");
            Obj.tooltip_fn(img, $(this).attr("alt"));
        });
    },
    setuprating: function (knopka) {

        var id = $(knopka).attr("rel");

        $(knopka).click(function () {
            $.get(ajaxhandler, { command: "rating", userid: id }, function (data) {
                alert("Спасибо, Ваш голос принят");
            });
            var val = "";
            if ($.cookie('rating') && $.cookie('rating').length > 0) {
                val = $.cookie('rating');
            }
            val = val.length > 0 ? val + ";" + id : id;
            $.cookie("rating", val, { expires: 30, path: "/" });
            $(knopka).addClass("not");
            $(knopka).unbind('click');
        });

    },
    rating: function () {
        var knopka = $("#workraiting");
        var id = $(knopka).attr("rel");
        if ($.cookie('rating')) {
            var cur = $.cookie('rating');
            var els = cur.split(";");
            var alreadyext = false;
            if (els.length > 0) {
                for (var i = 0; i < els.length; i++) {
                    if (els[i] == id) {
                        alreadyext = true;
                        $(knopka).addClass("not");
                    }
                }
            }
            if (alreadyext == false) {
                Obj.setuprating(knopka);
            }
        }
        else {
            Obj.setuprating(knopka);
        }
    },
	runFourteen: function(){
		var Elements = $('div.Fourteen'); //
			$(Elements).each(function (index, element) 
			{
				var all_width_plus = 0;
				var els = $(element).find('div[class^=img_block]');
				var subels = $(element).find('div[class^=img_scroll]');
				var right_button = $(element).find('a.horizontal_link');
				var window_width = $(els).width() + 0;
				var all_width = l * all_width_plus;
				$(right_button).click(function () { Obj.scrollclick(subels, window_width, all_width, false, all_width_plus); });
			}
	},
    run: function (element, windows_width_plus, all_width_plus, thumb, big, vertical, nobigimg, bigbutton) {

        var big_img = $(element).find('div.loading, div.clear_none, div.float_right');
        var lnk = $(element).find("a.defaultlink");
        var blue = $(element).find('p.blue_text, p.blue, div.blue_text, div.blu_blu_txt').not(".mar_left");
        var els = $(element).find('div[class^=img_block]');
        var subels = $(element).find('div[class^=img_scroll]');
        var right_button = $(element).find('a.horizontal_link, a.vertical_link');
        var href = $($(lnk)[0]).attr("href");
        var loader = $(big_img).find('table');
        var images_link = $(subels).children('a');
        var images = $(images_link).find('img');
        var window_width = (vertical == true ? $(els).height() : $(els).width()) + windows_width_plus;


        var l = $(element).hasClass("Seven") || $(element).hasClass("Eight") ? $(images_link).children("img").not(".odd").length : images_link.length;
        var all_width = l * all_width_plus;

        var curAlt = $(blue[0]).find("span").html();
        if ($(element).hasClass("Two")) {
            curAlt = $($(element).find("p.blue_text")[0]).html();
        }
        if ($(element).hasClass("Three")) {
            curAlt = $($(element).find("span.align_right")[0]).html();
        }
        loader.css('opacity', 0);
        if (window_width < all_width && $(element).hasClass("Eleven") != true) {
            if (vertical == true) $(subels).height(all_width);
            else $(subels).width(all_width);
        }
        $(right_button).click(function () { Obj.scrollclick(subels, window_width, all_width, vertical, all_width_plus); });
        ///////////////
        Obj.wraptext($(element).hasClass("Three") ? $(element).find("span.align_right") : $(blue[0]).find("span"), href);
        $(big_img).click(function () {

            var bg = $(big_img).css("background-image");

            Obj.openbigimg(bg.substring(4, (bg.length - 1)).replace(big, "OriginalImage"), curAlt, href);

        });
        $(images).each(function (ind, img) {
            $(img).attr("title", "");
            $(img).click(function () {
                Obj.thumbclick(img, loader, big_img, blue, thumb, big, curAlt, nobigimg, href, bigbutton);
            });
            Obj.tooltip_fn(img, $(this).attr("alt"));
        });
        Obj.tooltip_fn(big_img, curAlt);
    },
    wraptext: function (intext, href) {
        if (href != null && href != '' && href != undefined) {
            //var intext = $(element).find("span");
			
            var newintext = document.createElement('a');
            $(newintext).attr('href', href).attr("target", "_blank"); //.attr("rel", "nofollow");
            $(intext).wrap(newintext);
            //$(newintext).wrap(document.createElement("noindex"));
        }

    },
    scrollclick: function (subels, window_width, all_width, vertical, onewidth) {

        var left = parseInt($(subels).css(vertical ? 'top' : 'left').replace("px", ""));
        var temp_left = (left - window_width) + all_width;
        var newleft = left;
        if (temp_left > 0) {
            if (temp_left >= onewidth) newleft = left - onewidth;
            else newleft = -(all_width - window_width);
        }
        else newleft = 0;
        if (vertical) $(subels).animate({ top: newleft }, 1000);
        else $(subels).animate({ left: newleft }, 1000);
    },
    cleardict: function () {
        $("img.element").attr("title", "");
    },
    openlink: function (href) {
        if (href != null && href != '' && href != undefined) {
            window.open(href);
            return false;
        }

    },
    openbigimg: function (imgurl, text, href) {
        var img = new Image();
        var url = imgurl.replace(/"/ig, '');

        $(img).load(function () {


            var w = $(img)[0].width;
            var h = $(img)[0].height;
            var ww = $(window).width();
            var hw = $(window).height() - 40; //для подписи
            if ((w + 20) > ww && (h + 20) > hw) {
                var k = 1;
                var one = (w + 20) / ww;
                var two = (h + 20) / hw;
                if (one > two) {

                    k = w / (ww - 20);
                    w = ww - 20;
                    h = Math.floor(h / k);
                } else {
                    k = h / (hw - 20);
                    h = hw - 20;
                    w = Math.floor(w / k);
                }

            }
            else if ((w + 20) > ww) {
                k = w / (ww - 20);
                w = ww - 20;
                h = Math.floor(h / k);
            }
            else if ((h + 20) > hw) {
                k = h / (hw - 20);
                h = hw - 20;
                w = Math.floor(w / k);
            }

            $("#bimg").attr("src", "").attr("src", url).css('width', w + "px").css('height', h + "px");

            if (href != null && href != '' && href != undefined) {
                var a = document.createElement("a");
                var a2 = document.createElement("a");
                /*if (href.indexOf("360.ru") != -1) {
                    text = text + '<img class="img360" src="/files/img/button130.jpg" />'; 
                }*/
                $("#announce").html($(a).html(text).attr("href", href).attr("target", "_blank"));

            }
            else {
                var span = document.createElement("span");
                $("#announce").html($(span).html(text));
            }
            $("#facebox").css('width', (w + 20) + 'px');
            var trigger = $("#facebox").overlay({
                expose: {
                    color: '#000',
                    loadSpeed: 200,
                    opacity: 0.5
                },
                closeOnClick: true,
                api: true
            });
            trigger.load();
            $("#bimg").click(function () { trigger.close(); });
        }).error(function () { }).attr("src", url);

    },
    thumbclick: function (img, loader, big_img, blue, thumb, big, curAlt, nobigimg, href, bigbutton) {
        var path = $(img).attr('src').replace(thumb, big);
        var imgid = nobigimg ? new String($(img).attr('src')).replace('/files/cache/images/', '').replace(('_' + big_img + '.jpg'), '').split('_')[2] : $(img).attr('rev');
        var img_new = new Image();
        var tempcurAlt = curAlt;
        $.getJSON(ajaxhandler, { command: "imgdescr", imageid: imgid }, function (data) {
            DescrOk(data);
        });
        function DescrOk(data) {
            var temptext = data.Announce;
            tempcurAlt = $(img).attr('alt');

            if (nobigimg == false) {
                $(img_new).load(function () {
                    Obj.loadimage(img_new, loader, big_img, path, blue);
                }).error(function () { alert("Error Load") }).attr('src', path);
                Obj.tooltip_fn(big_img, tempcurAlt);
                $(big_img).unbind("click");
                $(big_img).click(function () {

                    Obj.openbigimg(path.replace(big, "OriginalImage"), tempcurAlt, href);

                });
            }
            temptext += ' <span>';
            if (href != null && href != '' && href != undefined && href.indexOf("360.ru") != -1) {
                /*if (bigbutton == 1) {
                    temptext += ('<img src="/files/img/button190.jpg" />');
                }
                else if (bigbutton == 2) {
                    temptext += ('<img src="/files/img/button130.jpg" />');
                }*/
            }
            temptext += (' ' + tempcurAlt + '</span>');

            var h = data.Link;
            $(blue).html(temptext);
            Obj.wraptext(blue, h);

            if (data.Link == null) href = '';
            else href = data.Link;
            if (nobigimg) {
                Obj.openbigimg(path.replace(big, "OriginalImage"), tempcurAlt, href);
            };
        }
    },
    loadimage: function (img_new, loader, big_img, path, blue, resize) {
        var h = $(img_new)[0].height;
        $(big_img).css('background-image', 'none');

        if (path.indexOf("BigImageW495", 0) < 0) {
            $(big_img).css('background-image', 'url(' + path + ')')
        } else {
            $(big_img).animate({ height: h }, 1000, function () {
                $(big_img).css('background-image', 'url(' + path + ')')
            });
        }
    },
    setol: function () {
        var oll = $("#content ol li");
        $(oll).each(function () { $(this).html("<span>" + $(this).text() + "</span>") });
    },
    tooltip_fn: function (element, text) {



        $(element).hover(
	            function (e) {
	                if (text != null && text != '' && text != undefined && text.indexOf("/files/cache/images", 0) < 0) {
	                    var myregexp = /<\/?[a-z][a-z0-9]*[^<>]*>/ig;
	                    var nt = text.replace(myregexp, "");


	                    $(tooltip).text(nt).show();
	                    $(element).mousemove(
	                        function (e) {
	                            var mouseX = e.pageX;
	                            var mouseY = e.pageY;
	                            $(tooltip).css({ 'top': mouseY + 3 + "px", 'left': mouseX + 3 + "px" });
	                        });

	                } else { $(tooltip).hide(); }
	            },
	            function () {
	                $(tooltip).hide();
	            }
	        );

    },
    slide: function () {
        var items = $("div.Slide, div.uni_block");
        $(items).each(function (index, element) {

            var els1 = $(element).find('ul.icons_list li.question a');

            $(els1).click(function (el) {
                var block = $(element).find('ul.wordbook');
                $(block).slideToggle('slow');

            });
            var els2 = $(element).find('li.star a');

            $(els2).click(function (el) {
                var block = $(element).find('div.forHide');
                $(block).slideToggle('slow');
            });
        });
    },
    accordion: function () {
        $(".main_menu a.togLink").click(function () {
            var div = $(this).next("div.togdiv");
            if ($(div).css('display') == 'block') {
                $(div).hide();
            }
            else if ($(div).css('display') == 'none')
                $(div).slideDown(800);
            var uncles = $(this).parent().siblings("li.togLi");
            $(uncles).find("div.togdiv").hide();
        });
    },
    bluetextsize: function () {
        var sizes = $('#font > a');
        var txt_block = $('#content');
        $(sizes).each(function (index, size) {
            $(size).click(function () {
                $(txt_block).find('p:not(.blue):not(.blue_text)').animate({ fontSize: ($(this).attr('rev')) }, 1000);
            });
        });
    },
    search: function () {
        var but = $('#SearchButton');
        var box = $('#SearchText');
        var text = $('#yousearch');
        var full_count = $('#fullcounsearch');
        var for_search = $('#for_search_res');
        var result = $('#search_res');
        var container = $('#details_search_result');
        var current = $('#current_search');
        var searchtxt = "";
        if (box.attr('value') != null && box.attr('value') != '') {
            Obj.searchGo(searchtxt, box, result, for_search, current, full_count, text);
        }
        $(but).click(function () {
            $(container).empty();
            Obj.searchGo(searchtxt, box, result, for_search, current, full_count, text);
        });

        $(box).keydown(function (event) {
            if (event.keyCode == 13) {
                $('form').submit(function () { return false; });
            }
        });
    },
    searchGo: function (searchtxt, box, result, for_search, current, full_count, text) {
        searchtxt = $(box).attr('value');
        if (searchtxt != '') {
            $(result).empty();
            $(for_search).show();
            var currType = $(current).attr('rel');
            $.getJSON(ajaxhandler, { command: "searchcount", search: searchtxt, current: currType }, function (data) {
                SucceededCallback(data);
            });
        }
        function SucceededCallback(dataList) {
            $(text).text(searchtxt);
            var f = 0;

            $(for_search).hide();
            var res_links = "";

            for (var i = 0; i < dataList.length; i++) {
                f = f + parseInt(dataList[i].Result);
                res_links += dataList[i].Link;
            }
            $(full_count).text(f);
            $(result).html(res_links);
        }
        function ErrorCallback(error) {
            alert(error.get_message());
        }
    },
    visitreg: function () {
        var id = $('#section_id').attr("title");
        var ids = id.split(':');
        var new_value = undefined;
        var returnString = '';

        if ($.cookie('visit')) {
            var cur = $.cookie('visit');
            var els = cur.split(';');
            for (var i = 0; i < els.length; i++) {
                var new_item = '';
                var cur_el = els[i].split(':');
                var IsAlreadyEx = false;
                for (var j = 0; j < ids.length; j++) {
                    if (ids[j] == cur_el[0]) {
                        if (cur_el[1] == "n") {
                            returnString += cur_el[0] + ':0;'; //Вторичный заход;
                        }
                        else {
                            var temp_date = new Date() - new Date(cur_el[1] + ":" + cur_el[2] + ":" + cur_el[3]);
                            if (temp_date > 900000) {
                                returnString += cur_el[0] + ':0;'; //Вторичный заход;
                            }
                        }
                        new_item = cur_el[0] + ":" + new Date();
                        IsAlreadyEx = true;
                    }
                }
                if (cur_el[1] != "n") {
                    var t_date = new Date() - new Date(cur_el[1] + ":" + cur_el[2] + ":" + cur_el[3]);
                    if (t_date < 900000) {
                        if (IsAlreadyEx == false) {
                            new_item = els[i];
                        }
                    }
                    else {
                        if (IsAlreadyEx == false) { new_item = cur_el[0] + ":n"; }
                    }
                }
                else {
                    if (IsAlreadyEx == false) { new_item = els[i]; }
                }
                if (new_value == undefined) { new_value = new_item; }
                else { new_value = new_value + ";" + new_item; }
            }
            for (var j = 0; j < ids.length; j++) {
                var isEx = false;
                for (var i = 0; i < els.length; i++) {
                    if (els[i].split(":")[0] == ids[j]) { isEx = true; }
                }
                if (isEx == false) {
                    returnString += ids[j] + ':1;'; //первичный заход;
                    if (new_value == undefined) { new_value = ids[j] + ":" + new Date(); }
                    else { new_value = new_value + ";" + ids[j] + ":" + new Date(); }
                }
            }
        }
        else {
            for (var q = 0; q < ids.length; q++) {
                if (new_value == undefined) { new_value = ids[q] + ":" + new Date(); }
                else { new_value = new_value + ";" + ids[q] + ":" + new Date(); }
                returnString += ids[q] + ':1;';
            }
        }
        $.cookie("visit", null);
        $.cookie("visit", new_value, { expires: 7, path: "/" });
        $.getJSON(ajaxhandler, { command: "visit", id: returnString });
    },
    h1hack: function () {
        var h1_w = $("h1.light_blue");
        $(h1_w).after("<div class=\"clear\"></div>")
    },
    equalslists: function () {
        var items = $("ul.list_results");
        if ($(items).length > 1) {
            var One = items[0];
            var Two = items[1];
            var OneEls = $(One).find("li");
            var TwoEls = $(Two).find("li");
            var colvo = Math.min($(OneEls).length, $(TwoEls).length);
            for (var i = 0; i < colvo; i++) {
                var el1 = $(OneEls)[i];
                var el2 = $(TwoEls)[i];
                var w = Math.max($(el1).height(), $(el2).height());
                $(el1).height(w);
                $(el2).height(w);
            }
        }
    }
}
$(document).ready(Obj.start);
