var site_root = '/';





/// OLD --------------
function MM_findObj(n, d){ //v4.01
    var p, i, x;
    if (!d) 
        d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) 
        x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++) 
        x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) 
        x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) 
        x = d.getElementById(n);
    return x;
}


function MM_showHideLayers(){ //v6.0
    var i, p, v, obj, args = MM_showHideLayers.arguments;
    for (i = 0; i < (args.length - 2); i += 3) 
        if ((obj = MM_findObj(args[i])) != null) {
            v = args[i + 2];
            if (obj.style) {
                obj = obj.style;
                v = (v == 'show') ? 'block' : (v == 'hide') ? 'none' : v;
            }
            obj.display = v;
        }
}

function MM_openBrWindow(theURL, winName, features){ //v2.0
    window.open(theURL, winName, features);
}


/*
 originally written by paul sowden <paul@idontsmoke.co.uk> | http://idontsmoke.co.uk
 modified and localized by alexander shurkayev <alshur@narod.ru> | http://htmlcoder.visions.ru
 */
window.onerror = null;

tooltip = {

    /* НАЧАЛО НАСТРОЕК */
    
    attr_name: "tooltip", // наименование создаваемого tooltip'ого атрибута
    blank_text: "(откроется в новом окне)", // текст для ссылок с target="_blank"
    newline_entity: "", // укажите пустую строку (""), если не хотите использовать в tooltip'ах многострочность; ежели хотите, то укажите тот символ или символы, которые будут заменяться на перевод строки
    max_width: 600, // максимальная ширина tooltip'а в пикселах; обнулите это значение, если ширина должна быть нелимитирована
    delay: 0, // задержка при показе tooltip'а в миллисекундах
    /* КОНЕЦ НАСТРОЕК */
    
    t: document.createElement("DIV"),
    c: null,
    g: false,
    
    m: function(e){
        if (tooltip.g) {
            oCanvas = document.getElementsByTagName((document.compatMode && document.compatMode == "CSS1Compat") ? "HTML" : "BODY")[0];
            x = window.event ? event.clientX + 5 + oCanvas.scrollLeft : e.pageX;
            y = window.event ? event.clientY + 5 + oCanvas.scrollTop : e.pageY;
            tooltip.a(x, y);
        }
    },
    
    d: function(){
        tooltip.t.setAttribute("id", "tooltip");
        //tooltip.t.style.filter = "alpha(opacity=85)"; // buggy in ie5.0
        document.body.appendChild(tooltip.t);
        a = document.all ? document.all : document.getElementsByTagName("*");
        aLength = a.length;
        for (var i = 0; i < aLength; i++) {
        
            //if (a[i].tagName == "A" || a[i].tagName == "BUTTON" || (a[i].tagName == "INPUT" && (a[i].type == "submit" || a[i].type == "button" || a[i].type == "reset"))) a[i].onclick = self.focus;
            
            if (!a[i]) 
                continue;
            
            if (a[i].className == "nav" || a[i].className == "navtable") 
                continue;
            
            tooltip_title = a[i].getAttribute("title");
            tooltip_alt = a[i].getAttribute("alt");
            tooltip_blank = a[i].getAttribute("target") && a[i].getAttribute("target") == "_blank" && tooltip.blank_text;
            if (tooltip_title || tooltip_blank) {
                a[i].setAttribute(tooltip.attr_name, tooltip_blank ? (tooltip_title ? tooltip_title + " " + tooltip.blank_text : tooltip.blank_text) : tooltip_title);
                if (a[i].getAttribute(tooltip.attr_name)) {
                    a[i].removeAttribute("title");
                    if (tooltip_alt && a[i].complete) 
                        a[i].removeAttribute("alt");
                    tooltip.l(a[i], "mouseover", tooltip.s);
                    tooltip.l(a[i], "mouseout", tooltip.h);
                }
            }
            else 
                if (tooltip_alt && a[i].complete) {
                    a[i].setAttribute(tooltip.attr_name, tooltip_alt);
                    if (a[i].getAttribute(tooltip.attr_name)) {
                        a[i].removeAttribute("alt");
                        tooltip.l(a[i], "mouseover", tooltip.s);
                        tooltip.l(a[i], "mouseout", tooltip.h);
                    }
                }
            if (!a[i].getAttribute(tooltip.attr_name) && tooltip_blank) {
                //
            }
        }
        document.onmousemove = tooltip.m;
        window.onscroll = tooltip.h;
        tooltip.a(-99, -99);
    },
    
    s: function(e){
        d = window.event ? window.event.srcElement : e.target;
        if (!d.getAttribute(tooltip.attr_name)) 
            return;
        s = d.getAttribute(tooltip.attr_name);
        if (tooltip.newline_entity) {
            s = s.replace(/\&/g, "&amp;");
            s = s.replace(/\</g, "&lt;");
            s = s.replace(/\>/g, "&gt;");
            s = s.replace(eval("/" + tooltip.newline_entity + "/g"), "<br />");
            tooltip.t.innerHTML = s;
        }
        else {
            if (tooltip.t.firstChild) 
                tooltip.t.removeChild(tooltip.t.firstChild);
            tooltip.t.appendChild(document.createTextNode(s));
            //tooltip.t.innerText = s;
        }
        tooltip.c = setTimeout("tooltip.t.style.visibility = 'visible';", tooltip.delay);
        tooltip.g = true;
    },
    
    h: function(e){
        tooltip.t.style.visibility = "hidden";
        if (!tooltip.newline_entity && tooltip.t.firstChild) 
            tooltip.t.removeChild(tooltip.t.firstChild);
        clearTimeout(tooltip.c);
        tooltip.g = false;
        tooltip.a(-99, -99);
    },
    
    l: function(o, e, a){
        if (o.addEventListener) 
            o.addEventListener(e, a, false); // was true--Opera 7b workaround!
        else 
            if (o.attachEvent) 
                o.attachEvent("on" + e, a);
            else 
                return null;
    },
    
    a: function(x, y){
        oCanvas = document.getElementsByTagName((document.compatMode && document.compatMode == "CSS1Compat") ? "HTML" : "BODY")[0];
        
        w_width = oCanvas.clientWidth ? oCanvas.clientWidth + oCanvas.scrollLeft : window.innerWidth + window.pageXOffset;
        w_height = window.innerHeight ? window.innerHeight + window.pageYOffset : oCanvas.clientHeight + oCanvas.scrollTop; // should be vice verca since Opera 7 is crazy!
        tooltip.t.style.width = ((tooltip.max_width) && (tooltip.t.offsetWidth > tooltip.max_width)) ? tooltip.max_width + "px" : "auto";
        
        t_width = tooltip.t.offsetWidth;
        t_height = tooltip.t.offsetHeight;
        
        tooltip.t.style.left = x + 8 + "px";
        tooltip.t.style.top = y + 8 + "px";
        
        if (x + t_width > w_width) 
            tooltip.t.style.left = w_width - t_width + "px";
        if (y + t_height > w_height) 
            tooltip.t.style.top = w_height - t_height + "px";
    }
}
/*
var root = window.addEventListener || window.attachEvent ? window : document.addEventListener ? document : null;
if (root) {
    if (root.addEventListener) 
        root.addEventListener("load", tooltip.d, false);
    else 
        if (root.attachEvent) 
            root.attachEvent("onload", tooltip.d);
}
*/

/// /OLD ----------------




function OnError(i1, i2, i3){
    alert("Javascript error: " + i1 + "\n\n Url: " + i2 + "\n Line: " + i3 + "\n");
    //return false;
}

//window.onerror = OnError;


function setClass(obj, cl, mode){
    var c = obj.className || "";
    var mask = new RegExp("(^| )" + cl + "($| )", "gi");
    if (mode == "?") 
        mode = !c.match(mask);
    c = mode ? (c.match(mask) ? c : (c + " " + cl)) : c.replace(mask, " ");
    obj.className = c.replace(/ +/g, " ").replace(/(^ *| *$)/g, "");
}

var currentAlbum;
function showAlbum(a){
    if (currentAlbum) {
        setClass(currentAlbum, 'gallery_visible', false);
        //currentAlbum == null;
    }
    if (currentAlbum == a.parentNode.parentNode) {
        currentAlbum = null;
    }
    else {
        setClass(a.parentNode.parentNode, 'gallery_visible', '?');
        currentAlbum = a.parentNode.parentNode;
    }
    return false;
}


/* функция проверяет поля формы на заполненность, добавляет запись для защиты от спама, добавляет названия полей в POST
 пример:
 <form action="test.php" onsubmit="return checkFormEx(this)" method="post" validateMode="full" makeLabels="true">
 <input name="n" title="Имя"  />
 </form>
 */
function formChecker(form){
    this._form = form;
    this._validateMode = form.getAttribute('validator')
    // добавляем проверку от спама
    this.appendInput(form, 'hidden', 'hookEx', 'true');
}

/* функция добавляет к концу форму элемент INPUT с заданными парпаметрами */
formChecker.prototype.appendInput = function(parent, type, name, value){
    var element = document.createElement('INPUT');
    element.type = type;
    element.name = name;
    element.value = value;
    parent.appendChild(element);
}

formChecker.prototype.inputValidator = function(form, input){
    if (input.tagName == 'SELECT') 
        return true;
    var mode = input.getAttribute('validator');
    //if (mode == null) mode = this._validateMode;
    if (mode == null) 
        mode = form.validateMode;
    if (mode == 'none') 
        return true;
    //alert(this._form.validateMode);
    
    var label = input.getAttribute("tooltip");//input.title;
    if (!label) 
        label = input.name;
    
    if (mode == 'full' && label != '' && input.value == '') {
        alert("Вы должны заполнить поле '" + label + "'.");
        //alert("Your must fill '" + label + "'.");
        input.focus();
        return false;
    }
    return true;
}

formChecker.prototype.isLabelExists = function(label_name){
    for (var ii = 0; ii < this._form.childNodes.length; ii++) {
        var cc = this._form.childNodes[ii];
        if (!cc.tagName || cc.tagName != 'INPUT' && cc.tagName != 'TEXTAREA') 
            continue;
        if (cc.name == label_name) 
            return true;
    }
    return false;
}

formChecker.prototype.check = function(formItem){
    //alert(formItem);
    for (var i = 0; i < formItem.childNodes.length; i++) {
        var c = formItem.childNodes[i];
        if (c.tagName && (c.tagName == 'INPUT' || c.tagName == 'TEXTAREA' || c.tagName == 'SELECT')) {
            // валидатор полей в действии :)
            if (this.inputValidator(this._form, c) == false) 
                return false;
            if (c.getAttribute("tooltip")/*title*/ > '') {
                var label_name = 'labels[' + c.name + ']';
                // ищем, есть ли label для этого поля? если label'а нет - добавляем его
                if (!this.isLabelExists(label_name)) 
                    this.appendInput(this._form, 'hidden', label_name, c.getAttribute("tooltip")/*title*/);
            }
        }
        else {
            // обязательно делаем рекурсию для вложенных элементов
            if (this.check(c) == false) 
                return false;
        }
    }
    return true;
}


function checkFormEx(form){
    var c = new formChecker(form);
    return c.check(form);
}


function showBlock(block_id){
    var block = document.getElementById(block_id);
    if (block.style.display == 'block') {
        block.style.display = 'none';
    }
    else {
        block.style.display = 'block';
    }
}

var currentcity = 0;
function showDistrictsFrom(city){
    if (city == 0) {
        var i = document.getElementById('city').options.selectedIndex;
        city = document.getElementById('city').options[i].value;
    }
    var el = document.getElementById('district' + city);
    el.style.display = 'inline';
    if (currentcity > 0) {
        document.getElementById('district' + currentcity).style.display = 'none';
    }
    currentcity = city;
}

function setHtml(block_id, html){
    var block = document.getElementById(block_id);
    block.innerHTML = html;
}


function checkField(name, label, fullText){
    if (name == '' || label == '') 
        return true;
    var current = '';
    for (var i = 0; i < document.getElementsByName(name).length; i++) {
        current = document.getElementsByName(name).item(i);
        if (current.tagName == 'input') 
            break;
    }
    
    if (current == '') {
        alert("Error: can't find input - " + name);
        return false;
    }
    if (current.value == '') {
        current.focus();
        if (fullText) 
            alert(label);
        else 
            alert('Пожалуйста заполните поле "' + label + '"');
        return false;
    }
    return true;
}

function getE(elementId){
    return document.getElementById(elementId);
}

function checkForm(formName){
    if (formName == 'basket') {
        if (checkField('n', 'Имя') == false) 
            return false;
        if (checkField('e', 'E-mail') == false) 
            return false;
        if (checkField('c', 'Город') == false) 
            return false;
        if (checkField('a', 'Адрес') == false) 
            return false;
        if (checkField('p', 'Телефон') == false) 
            return false;
        return true;
    }
    else 
        alert('Error: function checkForm - wrong form name "' + formName + '"');
    
    return false;
}

function imgWin(img, s, file){
    if (typeof(file) == 'undefined') 
        var file = 'preview.htm';
    var scr = '';
    if (s == '' || typeof(s) == 'undefined') {
        scr = '/misc/' + file;
    }
    else {
        scr = s + 'misc/' + file;
    }
    
    var x = screen.width / 2 - 400 / 2;
    var y = screen.height / 2 - 300 / 2;
    var wn = window.open(scr + '?' + escape(img), 'win', 'resizable,width=400,height=300,top=' + y + ',left=' + x + ',screenX=' + x + ',screenY=' + y + ',status=0');
    wn.focus();
    return false;
}

function imgWin2(id, idx, file){
    if (typeof(file) == 'undefined') 
        var file = 'preview.php';
    scr = site_root + 'misc/' + file;
    
    var x = screen.width / 2 - 400 / 2;
    var y = screen.height / 2 - 300 / 2;
    var wn = window.open(scr + '?id=' + id + '&idx=' + idx, 'win', 'resizable,width=400,height=300,top=' + y + ',left=' + x + ',screenX=' + x + ',screenY=' + y + ',status=0');
    wn.focus();
    return false;
}

function isInteger(val){
    if (!val) 
        return false;
    var string = "1234567890";
    
    for (var i = 0; i < val.length; i++) {
        if (string.indexOf(val.charAt(i)) == -1) 
            return false;
    }
    return true;
}





function clickImg(el){
    var element = document.getElementById('bigPicture');
    return imgWin(fullPictures[currentIndex]);
}




var currentIndex = 1;
function loadPicture(index){
    var element = document.getElementById('bigPicture');
    var previewElement = document.getElementById('preview_' + currentIndex);
    var previewNewElement = document.getElementById('preview_' + index);
    var url = bigPictures[index];
    var href = element.parentNode;
    
    if (!url) {
        url = '/images/skin/no_foto.png';
    }
    
    href.href = url;
    element.src = url;
    currentIndex = index;
    
    if (!previewElement) 
        return;
    if (!previewNewElement) 
        return;
    previewElement.className = 'i';
    previewNewElement.className = 'i selected';
}




/*
 if (flashVersion >= 8) {
 var f = new Flash('trees');
 f.setSWF('misc/trees.swf', '660px', '305px');
 f.setParam('flashVars', 'dataXml=misc/trees.xml');
 f.setParam('wmode', 'transparent');
 f.setParam('quality', 'high');
 f.inHtml('<div id="treesContainer">|||</div>');
 f.display();
 }
 */
var flashVersion = 0;
var isOpera = Boolean(window["opera"]);
var isIE = (navigator.userAgent.indexOf("MSIE") != -1) && !isOpera;

function Flash(name){
    this._swf = '';
    this._params = new Array();
    this._attributes = new Array();
    this._spliter = '|||';
    this._htmlBefore = '';
    this._htmlAfter = '';
    if (name) {
        if (isIE) 
            this.setAttribute('id', name);
        else 
            this.setAttribute('name', name);
    }
}

Flash.prototype.setSWF = function(_swf, _width, _height){
    this._swf = _swf;
    this.setAttribute('width', _width);
    this.setAttribute('height', _height);
}

Flash.prototype.setParam = function(paramName, paramValue){
    this._params[this._params.length] = paramName + this._spliter + paramValue;
}

Flash.prototype.setAttribute = function(attributeName, attributeValue){
    this._attributes[this._attributes.length] = attributeName + this._spliter + attributeValue;
}

Flash.prototype.getAttributeFromArray = function(arr){
    var attributes = '';
    var attribute = '';
    for (var i = 0; i < arr.length; i++) {
        attribute = arr[i].split(this._spliter);
        attributes += attribute[0] + '="' + attribute[1] + '" ';
    }
    return attributes;
}

/* указывает html обвертку для flash */
Flash.prototype.inHtml = function(html){
    var parts = html.split(this._spliter);
    this._htmlBefore = parts[0];
    this._htmlAfter = parts[1];
}

Flash.prototype.display = function(alertTxt){
    var attributes = this.getAttributeFromArray(this._attributes);
    var params = this.getAttributeFromArray(this._params);
    
    var _txt = this._htmlBefore;
    _txt += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ' + attributes + '>\n';
    _txt += '<param name="movie" value="' + this._swf + '" />\n'
    _txt += '<param name="quality" value="high" />\n';
    _txt += '<param name="menu" value="false" />\n';
    
    var _param = '';
    var i = 0;
    for (var i = 0; i < this._params.length; i++) {
        _param = this._params[i].split('|||');
        _txt += '\t<param name="' + _param[0] + '" value="' + _param[1] + '" />\n';
    }
    
    _txt += '<embed menu="false" ' + attributes + ' src="' + this._swf + '" ' + params + ' quality="high" type="application/x-shockwave-flash"></embed>\n';
    _txt += '</object>\n';
    _txt += this._htmlAfter;
    if (alertTxt) 
        alert(_txt);
    document.write(_txt);
}

function getSWF(name){
    if (isOpera) 
        return document[name];
    return isIE ? window[name] : document[name][1];
}

/* GetFlashVersion - must be last function in file */
function GetFlashVersion(){
    try {
        var ie = 0;
        var fz = 0;
        var n = navigator;
        
        if (n.platform == 'Win32' && !window.opera && n.appName != 'Netscape') {
            ie = 1;
            for (var i = 3; i < 10; i++) {
                if (eval('new ActiveXObject("ShockwaveFlash.ShockwaveFlash.' + i + '")')) 
                    flashVersion = i;
            }
        }
        
        if (ie == 0 && n.plugins) {
            for (var i = 0; i < n.plugins.length; i++) {
                if (n.plugins[i].name.indexOf('Flash') > -1) {
                    fz = parseInt(n.plugins[i].description.charAt(16));
                    if (fz > flashVersion) 
                        flashVersion = fz;
                }
            }
        }
    } 
    catch (e) {
    }
}

GetFlashVersion();





























var last_shown_block = null;

function show_hide_block(eList){
    eList.className = eList.className ? "" : "active";
    var eTR = eList;
    while (eTR.nodeName != "TR") {
        eTR = eTR.parentNode
    }
    var cell_0 = cell(eTR, 0);
    var cell_1 = cell(eTR, 1);
    var cell_2 = cell(eTR, 2);
    
    cell_0.className = cell_0.className ? "" : "l";
    cell_0.style.backgroundPosition = cell_0.className ? eList.offsetWidth + 5 + "px 0.9em" : "";
    cell_1.className = cell_1.className ? "" : "l";
    
    var eUL = cell_2;
    while (eUL.nodeName != "UL") {
        if (!eUL.firstChild) 
            return;
        eUL = eUL.firstChild.nodeName != "#text" ? eUL.firstChild : eUL.childNodes[1]
    }
    eUL.className = eUL.className ? "" : "active";
    
    if (last_shown_block && last_shown_block !== eList) 
        show_hide_block(last_shown_block)
    last_shown_block = last_shown_block ? null : eList;
    
}


function cell(row, celnum){
    var i = 0;
    for (var cell = row.firstChild; cell != null; cell = cell.nextSibling) 
        if (cell.nodeType == 1) {
            if (celnum == i) 
                return cell;
            i++;
        }
}
