﻿function _resize() {
    var $h = 0;
    try {
        var _h = parseInt($("#ResultsDataList").css('height').replace("px", ""));
        $h += _h
    } catch (e) { }
    try {
        var _h = parseInt($("#goodsTop").css('height').replace("px", ""));
        $h += _h
    } catch (e) { }    
    try {
        var _h = parseInt($("#goodsTopSimilar").css('height').replace("px", ""));
        $h += _h
    } catch (e) { }
    try {
        var _h = parseInt($("#goodsBottom").css('height').replace("px", ""));
        $h += _h
    } catch (e) { }
    try {
        var _h = parseInt($(".sgt_col").css('height').replace("px", ""));
        $h += _h + 50
    } catch (e) { }
    if ($h < 100) $h = 250;
    $("#borderL").height($h);
}



/*
*Постороение ссылки на поиск
*/
function WebSearch(query) {
    return "http://yottos.ru/Search?" + query;
}

function ShowHideSuggest() {
    if (!$ShowHideSuggest) return;
    var $_h = $leftSuggest * 28 + "px";
    var h = $("#divWebSuggest").css("height");
    if (h == $_h) {
        $("#divWebSuggest").css("height", "105px");
        $("#imgDown").show();
        $("#imgUp").hide();
    } else {
        $("#divWebSuggest").css("height", $_h);
        $("#imgDown").hide();
        $("#imgUp").show();
    }    
}
function ShowHideYourRequest() {
    //alert($ShowHideYourRequest);
    //if (!$ShowHideYourRequest) return;
    var $_h = $yourSuggest * 28 + "px";
    var h = $("#divYourSuggest").css("height");
    if (h == $_h) {
        $("#divYourSuggest").css("height", "105px");
        $("#img1").show();
        $("#img2").hide();
    } else {
        $("#divYourSuggest").css("height", $_h);
        $("#img1").hide();
        $("#img2").show();
    }
}
function getClientWidth() {
    return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientWidth : document.body.clientWidth;
}
function buildSearchUrl(sender) {
    function getSearchUrl(href) {
        var r = /yottos\.(com\.ua|ru|com)/;
        var domain = window.location.host.match(r);
        var host = domain ? ('http://' + domain[0] + '/') : 'http://yottos.ru/';
        var lang = domain ? domain[1] : 'ru';
        var link = '';
        var txtControl = document.getElementById("searchString") ||
                         document.getElementById("QueryTextBox") ||
                         document.getElementById("ctl00_SearchString1_QueryTextBox") ||
                         document.getElementById("ctl00_QueryTextBox") || 
                         document.getElementById("SearchString_QueryTextBox");
        if (!txtControl || !txtControl.value) return href;
        var query = txtControl.value.replace(/[:;]/g, '');
        
        switch (lang) {
            case 'com.ua':
                link = (href.match('news\.yottos\.') && ("http://news.yottos.com.ua/Поиск?" + query)) ||
                       (href.match('rynok\.yottos\.') && ("http://rynok.yottos.com.ua/поиск/" + query)) ||
                       (href.match('catalog\.yottos\.') && ("http://catalog.yottos.com.ua/yottos-каталог/Поиск/" + query)) ||
                       (href.match('zero\.yottos\.') && ("http://zero.yottos.com.ua/Zero.aspx?q=" + query)) ||
                       ("http://yottos.com.ua/Результат?" + query);
                break;
            case 'com':
                link = (href.match('news\.yottos\.') && ("http://news.yottos.com/Поиск?" + query)) ||
                       (href.match('rynok\.yottos\.') && ("http://rynok.yottos.com/поиск/" + query)) ||
                       (href.match('catalog\.yottos\.') && ("http://catalog.yottos.com/yottos-каталог/Поиск/" + query)) ||
                       (href.match('zero\.yottos\.') && ("http://zero.yottos.com/Zero.aspx?q=" + query)) ||
                       ("http://yottos.com/Результат?" + query);
                break;
            case 'ru':
            default:
                link = (href.match('news\.yottos\.') && ("http://news.yottos.ru/Поиск?" + query)) ||
                       (href.match('rynok\.yottos\.') && ("http://rynok.yottos.ru/поиск/" + query)) ||
                       (href.match('catalog\.yottos\.') && ("http://catalog.yottos.ru/yottos-каталог/Поиск/" + query)) ||
                       (href.match('zero\.yottos\.') && ("http://zero.yottos.ru/Zero.aspx?q=" + query)) ||
                       ("http://yottos.ru/Результат?" + query);
                break;
        }
        return query ? link : (link.match(/^http:\/\/[^\/]*\//)[0] || link);           // Если запрос пустой, возвращает ссылку на домен
    }

    sender.href = getSearchUrl(sender.href);
    return true;
}





/*




var webSearchPrefix = "/Результат?";
var zeroSearchPrefix = "Zero.aspx?q=";
var newsSearchPrefix = "/AllNews.aspx?q=";
var catalogSearchPrefix = "/CatalogSearch.aspx?q=";
var rynokSearchPrefix = "/AllResult.aspx?q=";

function buildSearchQuery_Transformed(hyperLink, searchPerfix) {
    var newUrl = 'http://' + hyperLink.href.match(/:\/\/(.[^\/]+)/)[1];
    var searchText = "";
    var searchTextBox = document.form1.QueryTextBox;    
    if (searchTextBox == null) searchTextBox = document.getElementById("ctl00_SearchString1_QueryTextBox");
    if (searchTextBox == null) searchTextBox = document.aspnetForm.ctl00_QueryTextBox;
    if (searchTextBox != null) searchText = escape(searchTextBox.value).replace(";", "");
    if (searchText != "") newUrl += (searchPerfix + searchText);
    else if (searchPerfix == zeroSearchPrefix) newUrl += "Zero/О_Zero";
    hyperLink.href = newUrl;
    return 1;
}

*/







function ShowSnow() {
    if (document.createElement('canvas').getContext) {
        if (document.readyState === 'complete')
            snow();
        else
            window.addEventListener('DOMContentLoaded', snow, false);
    }
    else {
        return;
    }

    var deg = Math.PI / 180;
    var maxflakes = 20; var flakes = []; var scrollspeed = 64; var snowspeed = 500;
    var canvas, sky;
    var snowingTimer;
    var invalidateMeasure = false;

    var strokes = ["#6cf", "#9cf", "#99f", "#ccf", "#66f", "#3cf"];

    function rand(n) {
        return Math.floor(n * Math.random());
    }

    function snow() {
        canvas = document.createElement('canvas');
        canvas.style.position = 'fixed';
        canvas.style.top = '0px';
        canvas.style.left = '0px';
        canvas.style.zIndex = '-10';

        document.body.insertBefore(canvas, document.body.firstChild);
        sky = canvas.getContext('2d');

        ResetCanvas();

        snowingTimer = setInterval(createSnowflake, snowspeed);
        setInterval(moveSnowflakes, scrollspeed);
        window.addEventListener('resize', ResetCanvas, false);
    }

    // Сброс размеров Canvas 
    function ResetCanvas() {
        invalidateMeasure = true;
        canvas.width = document.body.offsetWidth;
        canvas.height = window.innerHeight;
    }

    // Отрисовка кривой Коха 
    function leg(n, len) {
        sky.save();       // Сохраняем текущую трансформацию 
        if (n == 0) {      // Нерекурсивный случай - отрисовываем линию 
            sky.lineTo(len, 0);
        }
        else {
            sky.scale(1 / 3, 1 / 3);  // Уменьшаем масштаб в 3 раза 
            leg(n - 1, len); sky.rotate(60 * deg);
            leg(n - 1, len); sky.rotate(-120 * deg);
            leg(n - 1, len); sky.rotate(60 * deg); leg(n - 1, len);
        }
        sky.restore();      // Восстанавливаем трансформацию 
        sky.translate(len, 0); // переходим в конец ребра 
    }

    // Отрисовка снежинки Коха 
    function drawFlake(x, y, angle, len, n, stroke, fill) {
        sky.save(); sky.strokeStyle = stroke;
        sky.fillStyle = fill;
        sky.beginPath();
        sky.translate(x, y);
        sky.moveTo(0, 0); sky.rotate(angle);
        leg(n, len);
        sky.rotate(-120 * deg);
        leg(n, len); sky.rotate(-120 * deg);
        leg(n, len); sky.closePath();
        sky.fill();
        sky.stroke();
        sky.restore();
    }

    // Создание пула снежинок 
    function createSnowflake() {
        var order = 2 + rand(2);
        var size = 10 * order + rand(10);
        var x = rand(document.body.offsetWidth);
        var y = window.pageYOffset;
        var stroke = strokes[rand(strokes.length)];

        flakes.push({ x: x, y: y, vx: 0, vy: 3 + rand(3), angle: 0, size: size, order: order, stroke: stroke, fill: 'transparent' });

        if (flakes.length > maxflakes) clearInterval(snowingTimer);
    }

    // Перемещение снежинок 
    function moveSnowflakes() {
        sky.clearRect(0, 0, canvas.width, canvas.height);

        var maxy = canvas.height;

        for (var i = 0; i < flakes.length; i++) {
            var flake = flakes[i];

            flake.y += flake.vy;
            flake.x += flake.vx;

            if (flake.y > maxy) flake.y = 0;
            if (invalidateMeasure) {
                flake.x = rand(canvas.width);
            }

            drawFlake(flake.x, flake.y, flake.angle, flake.size, flake.order, flake.stroke, flake.fill);

            // Иногда меняем боковой ветер 
            if (rand(4) == 1) flake.vx += (rand(11) - 5) / 10;
            if (flake.vx > 2) flake.vx = 2;
            if (flake.vx < -2) flake.vx = -2;
            if (rand(3) == 1) flake.angle = (rand(13) - 6) / 271;
        }
        if (invalidateMeasure) invalidateMeasure = false;
    }
};

/*
*
*/
if (typeof Util == "undefined" || !Util) {
    var Util = {};
}

Util.startTick = function (p_when, p_scope, p_fn, p_data) {
    p_when = p_when || 0;
    p_scope = p_scope || {};
    var fn = p_fn, data = p_data, f, r;

    if (typeof p_fn == "string") {
        fn = p_scope[p_fn];
    }

    if (!fn) {
        throw new TypeError("method undefined");
    }

    if (Object.prototype.toString.apply(data) != "[object Array]") {
        data = [data];
    }

    f = function () {
        fn.apply(p_scope, data);
    };

    r = setInterval(f, p_when);

    return (
   {
       cancel: function () {
           clearInterval(r);
       }
   });
};

/**
* Return a random integer value between low and high values
*/
Util.randomInt = function randomInt(low, high) {
    return Math.floor(Math.random() * (high - low + 1) + low);
};
var Matrix = {};

(function () {
    var context = null,
      HEIGHT = 0,
      WIDTH = 0,
      CHARACTER_X = 50,
      CHARACTER_Y = 58;

    Matrix.Main = function () {
        this.MAX_LINES = 16;
        this.MIN_LINE_LENGTH = 8;
        this.MAX_LINE_LENGTH = 32;
        this.images = {};
        this.arrImages = [];
        this.lines = [];
    };

    Matrix.Main.prototype =
   {
       init: function () {
           var scope = this;
           document.addEventListener("DOMContentLoaded", function () {
               scope.onReady.apply(scope, arguments)
           }, false);
       },

       onReady: function () {
           document.removeEventListener("DOMContentLoaded", this.onReady, false);

           var canvas = document.getElementById("canvas1");
           context = canvas.getContext("2d");
           HEIGHT = canvas.height;
           WIDTH = canvas.width = document.width;

           this.images =
         {
             green: document.getElementById("imgGreen"),
             white: document.getElementById("imgWhite")
         };

           this.arrImages = [this.images.green, this.images.white];

           Util.startTick(30, this, this.onTick);
       },

       onTick: function () {
           var i, ii, j, jj,
            line, chr, chrLen, y,
            xScale, yScale, ySpacing,
            arrImageLen = this.arrImages.length - 1;

           if (this.lines.length < this.MAX_LINES) {
               this.lines.push(this.newLine());
           }

           context.fillStyle = "rgba(255,255,255,0.5)";
           context.fillRect(0, -50, WIDTH, HEIGHT + 50);           
           for (var i = 0, ii = this.lines.length; i < ii; i++) {
               line = this.lines[i];
               xScale = CHARACTER_X * line.scale;
               yScale = CHARACTER_Y * line.scale;
               ySpacing = 0;
               chrLen = line.characters.length;
               line.yOffset += line.ySpeed;

               if (chrLen < Math.floor(line.yOffset / yScale) && chrLen < line.len) {
                   line.characters.push(this.newCharacter());
               }

               // context.save();

               for (j = 0, jj = chrLen; j < jj; j++) {
                   chr = line.characters[j];
                   y = line.yStart + line.yOffset - ySpacing;
                   ySpacing += yScale;                   
                   context.drawImage(this.arrImages[chr.image], chr.x, chr.y, CHARACTER_X, CHARACTER_Y, line.xStart, y, xScale, yScale);

                   if (chr.dynamic || j == 0) {
                       if (chr.dynamicWait++ > 10) {
                           line.characters[j] = this.newCharacter();
                           line.characters[j].image = 1;
                           line.characters[j].dynamic = true;
                           line.characters[j].dynamicWait = 0;
                       }
                   }

                   if (j == line.len - 1 && y > HEIGHT) {
                       this.lines[i] = this.newLine();
                   }
               }

               // context.restore();
           }
       },

       newLine: function () {
           var line =
         {
             xStart: Util.randomInt(0, WIDTH),
             yStart: Util.randomInt(0, HEIGHT / 8) - 200,
             yOffset: 0,
             scale: Util.randomInt(2, 10) / 10.0,
             len: Util.randomInt(this.MIN_LINE_LENGTH, this.MAX_LINE_LENGTH),
             characters: []
         };
           line.ySpeed = line.scale * 10 + Util.randomInt(0, 5);
           return line;
       },

       newCharacter: function () {
           var chr = Util.randomInt(0, 55);
           return (
         {
             image: 0,
             x: (chr % 10) * CHARACTER_X,
             y: (Math.floor(chr / 10) * CHARACTER_Y),
             dynamic: Util.randomInt(0, 10) == 0,
             dynamicWait: 0
         });
       }
   };
})();



function validate(obj) {
    if ($(obj).val().indexOf("снег") >= 0) {
        ShowSnow();
    }
    if ($(obj).val().indexOf("матрица") >= 0) {
        var matrix = new Matrix.Main();
        matrix.init();        
    }
}
