(function($) {
if (navigator.userAgent.match(/MSIE\s+(\d+)/)) {
    window.__IE = true;
    window.__IE_Version = RegExp.$1;
}

var __OLD_IE = window.__OLD_IE = ((window.__IE) && (window.__IE_Version<7));

var __EFFECTS_ENABLED = window.__EFFECTS_ENABLED = !__OLD_IE;

var __SETTINGS = window.__SETTINGS = {
    bgRedrawInterval: 300,
    linkHideText: '&larr;&nbsp;Скрыть',
    slideDuration: 500,
    popupShowDuration: 200,
    accordeonDuration: 200,
    videoFadeDuration: 500,
    promoAnimationDuration: 2000,
    promoWaitingDuration: 10000,
    productLineWaitingTime: 50,
    productLineAnimateDuration: 500,
    galleryLinkFadeTimeout: 200,
    galleryImageFadeTimeout: 200,
    galleryLinkFadeValue: .75
};

$(document).ready(function() {
    window.$canvas = $('#canvas');
    var __page = window.__page = new PageObject();
    __page.preload();
    __page.startup();
    window.eStore = new __EStore();
});

var PageObject = function($canvas) {}

PageObject.prototype = {
    preload: function() {
        this.location = window.location.toString();
        var loaderImage = window.__loaderImage = new Image();
        loaderImage.src = '/i/loader.gif';
    },
    startup: function() {
        this.drawBackground();
        this.drawRounds();
        this.setupVisualEffects();
        this.setupPromos();
        var lForm = document.getElementById('login-form');
        if (lForm) {
            this.__loginFormHTML = lForm.innerHTML;
            $(lForm).remove();
        }
        switch (window.__pageClassName) {
            case 'prod-list':
                this.setupProdList();
                break;
            case 'product':
                this.setupProdPage();
                break;
            case 'gallery':
                this.setupGallery();
                break;
            case 'story':
                this.setupStoryPage();
                break;
            case 'story-form':
                this.setupStoryForm();
                break;
        }
        __setupReviewForm();
    },
    drawRounds: function(ctx) {
        if (!ctx) ctx = '#center'
        $(ctx+' .round').wrapInner($el('div').addClass('inner')).prepend($el('div').addClass('r').html('<ins class="lt"></ins><ins class="rt"></ins><ins class="lb"></ins><ins class="rb"></ins><em class="t"></em><em class="b"></em><i class="l"></i><i class="r"></i>'));
        $(ctx+' .i-round').wrapInner($el('div').addClass('i-rb')).prepend($el('ins').addClass('lt')).prepend($el('ins').addClass('rt')).prepend($el('ins').addClass('lb')).prepend($el('ins').addClass('rb'));
    },
    setupVisualEffects: function() {
        for (var i=0; i<window._menuHoverImages.length; i++) {
            var izz = new Image();
            izz.src = window._menuHoverImages[i];
        }
        $('#menu li').each(function(i) {
            var _hoverImgSrc = window._menuHoverImages[i];
            var _img = this.getElementsByTagName('img')[0];
            var _imgSrc = _img.src;
            if (__OLD_IE) {
                if (_img.style.filter.match(/src="(.*?)"/))
                    _imgSrc = RegExp.$1;
                $(this).hover(function() { _img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + _hoverImgSrc  + '", sizingMethod="image")'; }, function() { _img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + _imgSrc  + '", sizingMethod="image")'; });
            } else {
                $(this).hover(function() { _img.src = _hoverImgSrc; }, function() { _img.src = _imgSrc });
            }
        });
        $('#side-bar ul.menu li').dropDownMenu();
        $('ul.accordeon').accordeon();
    },
    setupProdList: function() {
        $('#center .block-group').each(function() {
            var li = $('li div.i', this);
            var h = 0;
            li.each(function() { if (this.scrollHeight > h) h = this.scrollHeight; });
            $(li).height(h);
        });
    },
    setupProdPage: function() {
        var $center = $('#center');
        $center.find('.prod-line').each(function(i) {
            var style = $(this.parentNode).hasClass('related') ? 'related' : 'normal'
            this.__object = new ProductLine(this, style);
        });
        $center.find('a.smart').each(function() {
            this.__smartLinkObject = new SmartLink(this);
        });
    },
    setupGallery: function() {
        var $center = $('#center');
        $center.find('.gallery').gallery();
    },
    setupStoryPage: function() {
        var $center = $('#center');
        $center.find('.spages-line').each(function(i) {
            this.__object = new ProductLine(this, 'normal' , 'страницы');
        });
        $center.find('ul.photo-list a').click(function() { var pp = new PopupPicture({ src: this.href }); pp.load(true); return false; });
    },
    setupStoryForm: function() {
        var f = document.getElementById('__story-form');
        if (f)
            f.__object = new StoryForm(f);
    },
    setupPromos: function() {
        var self = this;
        this.promos = new Array();
        this.promoDurations = new Array();
        this.curPromo = 0;
        $('#cloud li').each(function() {
            var time = parseInt($(this).find('ins').html())*1000;
            $(this).find('ins').remove();
            self.promos.push({ html: this.innerHTML, duration: time });
        });
        $('#cloud ul').remove();
        if (this.promos.length > 0) {
            this.$promoPlace = $('<div class="o" />');
            $('#cloud').append(this.$promoPlace);
            this.showNextPromo();
        }
    },
    showNextPromo: function(oldPromo) {
        var self = this;
        var h = this.$promoPlace.height();
        this.$promoPlace.append(
            $('<div class="c" />')
                .html(this.promos[this.curPromo].html)
                .attr('__time', self.promos[self.curPromo].duration)
                .css({ top: h, display: 'block' })
                .animate({ top: 0 }, __SETTINGS.promoAnimationDuration, 'swing',
                         function() {
                            var p = this;
                            window.setTimeout(function() { self.showNextPromo(p); }, $(this).attr('__time') );
                         }
                        )
        );
        if (oldPromo) {
            $(oldPromo).animate({ top: -h }, __SETTINGS.promoAnimationDuration, 'swing',
                                function() {
                                    $(this).remove();
                                }
                               );
        }
        this.curPromo++;
        if (this.curPromo >= this.promos.length) this.curPromo = 0;
    },
    drawBackground: function() {
        if (!__OLD_IE) {
            $('#bg .el').each(function(i) {
                var $this = $(this);
                if ($this.css('background-image').match(/^url\((.*)\)$/)) {
                    var src = (RegExp.$1).replace(/^\W+/, '').replace(/\W+$/, '');
                    $this.append($('<img src="'+src+'"/>').width('100%').height($this.height()));
                }
            });
        }

        if (jQuery.browser.opera) {
            var h = $canvas.height();
            $o = $('#bg div.o');
            window.setInterval(function() {
                h = $canvas.height();
                $o.find('b, p').each(function() { this.style.height = (h-this.offsetTop-180)+'px'; });
            }, __SETTINGS.bgRedrawInterval);
        }
    },
    submitAgeChange: function(ageSelect) {
        ageSelect.form.method = 'GET';
        $(ageSelect.form).find('div.questions').remove();
        ageSelect.form.submit();
    },
    showPopupMessage: function(innerHTML) {
        $canvas.disableLayer(true);
        var $layer = this.$layer = $el('div').addClass('popup-message').html('<div><div class="sb"></div><div class="sbl"></div><div class="s"></div><div class="st"></div><div class="o"><ins></ins></div></div>')
                        .css({top: document.documentElement.clientHeight/2+(document.documentElement.scrollTop || document.body.scrollTop)-50});
        $canvas.append($layer);
        window.closePopup = function() {
            if ((__EFFECTS_ENABLED) && (!window.__IE)) $layer.fadeOut(__SETTINGS.popupShowDuration, function() { $(this).remove(); $canvas.enableLayer(); });
            else $layer.remove(); $canvas.enableLayer();
            window.closePopup = null;
            return false;
        }
        var $d = $el('div').addClass('i').html('<div>'+innerHTML+'</div>');
        if (__EFFECTS_ENABLED) $d.css({opacity: 0});
        var $o = $layer.find('div.o').append($d);
        $layer.find('div.c,img').click(function() { self.hidePopupPicture(); });
        if ($canvas._disableLayer) { $canvas._disableLayer.click(function() { closePopup(); }); }
        var w = $o.outerWidth();
        var h = $o.outerHeight();
        if (__EFFECTS_ENABLED) {
            $layer.expandAnimation(w, h, __SETTINGS.popupShowDuration, 'swing', function() { $d.animate({opacity: 1}, __SETTINGS.popupShowDuration); });
        } else {
            $layer.css({ width: w, marginLeft: -w/2, height: h, marginTop: -h/2 });
        }
    },
    showLoginForm: function() {
        if (this.__loginFormHTML)
            this.showPopupMessage(this.__loginFormHTML);
    }
}


var ProductLine = function(object, style, title) {
    this.object = object;
    this.style = style || 'normal';
    this.windowSize = (this.style == 'normal') ? 4 : 5;
    this.lineTitle = title || 'товары';
    this.$object = $(object);
    this.setup();
}
ProductLine.prototype = {
    setup: function() {
        var self = this;
        var width = 100/this.windowSize;
        this.ul = this.object.getElementsByTagName('ul')[0];
        this.$items = this.$object.find('li');
        this.length = this.$items.length;
        if (this.length == 0) return;
        this.scrollPosition = 0;
        this.doScroll = function() {
            if (self.scrollTimeout) window.clearTimeout(self.scrollTimeout);
            self.checkButtons();
            self.updateInfoLine();
            self.scrollTimeout = window.setTimeout(function() { self.scroll() }, __SETTINGS.productLineWaitingTime);
        }
        if (this.style == 'related') {
            this.$object.find('img').each(function() {
                var w = this.width; var h = this.height;
                this.width = 0.8 * w;
                this.height = 0.8 * h;
            });
        }
        var widthS = 100/this.length;
        var height = 0;
        if (this.activeIndex == undefined) this.activeIndex = -1;
        this.$items.each(function(i) {
            if (this.scrollHeight > height) height = this.scrollHeight;
            if ((!self.activeIndex > -1) && (this.className.match(/active/))) self.activeIndex = i;
        });
        this.itemHeight = height;
        var sleft = (this.length < this.windowSize) ? (width*(this.windowSize-this.length)/2)+'%' : '0px';
        $(this.ul).wrapInner($el('div').css({ position: 'absolute', width: (width*this.length)+'%', left: sleft, top: 0 }));
        this.$items.each(function(i) {
            this.style.width = widthS+'%'
            if (this.clientWidth == 0) this.style.overflow = 'visible';
            this.style.left = widthS*i+'%';
        });
        this.$scrollOuter = $(this.ul).find('div').eq(0);
        $(this.ul).css( { height: height });
        if (this.length > this.windowSize) {
            this.scrollable = true;
            this.$leftBtn = $el('div').addClass('arr-left')
                             .mousedown(function() { self.scroll(-1); return false; });
            this.$rightBtn = $el('div').addClass('arr-right')
                              .mousedown(function() { self.scroll(1); return false; });
            this.$object.append(this.$leftBtn);
            this.$object.append(this.$rightBtn);
            if ((this.style == 'normal') || (this.style == 'gallery')) {
                this.$infoLine = $el('div').addClass('info-line').prependTo(this.$object);
            }
            if (this.style != 'gallery') this.updateEnv();
        }
    },
    updateEnv: function() {
        this.moveToActive();
        this.updateInfoLine();
        this.checkButtons();
    },
    scroll: function(direction) {
        var self = this;
        if ((!this.scrollDirection) && (!direction)) return;
        if (direction) this.scrollDirection = direction;
        var sPos = this.scrollPosition + this.scrollDirection * this.windowSize;
        if (sPos < 0) sPos = 0;
        if (sPos + this.windowSize > this.length) sPos = this.length - this.windowSize;
        if ((sPos >= 0) && (sPos+this.windowSize <= this.length)) {
            $(document).one('mouseup', function() { self.stopScroll(); });
            this.scrollPosition = sPos;
            var left = Math.round(-this.scrollPosition*this.$scrollOuter.width()/this.length);
            this.$scrollOuter.animate({ left: left },
                                      __SETTINGS.productLineAnimateDuration,
                                       'swing',
                                      this.doScroll
                                     );
        }
    },
    stopScroll: function() {
        this.scrollDirection = 0;
        window.clearTimeout(this.scrollTimeout);
        delete this.scrollTimeout;

    },
    updateInfoLine: function() {
        if (this.$infoLine) this.$infoLine.html(this.lineTitle+' с '+(this.scrollPosition+1)+' по '+(this.scrollPosition+this.windowSize)+' из '+this.length);

    },
    checkButtons: function() {
        if (this.scrollPosition < 1)
            this.$leftBtn.addClass('disabled');
        else
            this.$leftBtn.removeClass('disabled');
        if (this.scrollPosition+this.windowSize+1 > this.length)
            this.$rightBtn.addClass('disabled');
        else
            this.$rightBtn.removeClass('disabled');
    },
    moveToActive: function() {
        if (this.activeIndex > 0) {
            this.scrollPosition = this.activeIndex;
            if (this.scrollPosition > this.length-this.windowSize) this.scrollPosition = this.length-this.windowSize;
            this.$scrollOuter.css({ left: Math.round(-this.scrollPosition*this.$scrollOuter.width()/this.length) });
        }
    }
}

var __smartLinks = new Array();

var SmartLink = function(link) {
    this.state = 0;
    this.link = link;
    this.links = __smartLinks;
    this.href = link.href;
    this.setup();
}
SmartLink.prototype = {
    setup: function() {
        var self = this;
        var ai = this.href.indexOf('#');
        if (ai > -1) {
            this.anchor = this.href.substring(ai+1, this.href.length);
            this.url = this.href.substr(0, ai);
        }
        else this.anchor = 'error';
        this.links[this.anchor] = this;
        $(this.link).click(function() { return self.click(); });
        if (this.href == __page.location) this.click();
    },
    click: function() {
        if (this.anchor == 'full') {
            if (!this.state) {
                this.link._oldCaption = this.link.innerHTML;
                this.link.innerHTML = 'скрыть подробное описание';
            } else {
                this.link.innerHTML = this.link._oldCaption;
            }
            this.state = !this.state;
            $('#center .full-content').slideToggle(__SETTINGS.slideDuration);
            return false;
        } else if (this.anchor == 'reviews') {
            if ((this.links['full']) && (!this.links['full'].state)) this.links['full'].click();
            $canvas.showLoaderLogo($(this.link));
            this.doRequest( { 'href': this.url, 'context': 'reviews' });
            return false;
        } else if (this.anchor.match(/^(video|picture)(\d+)$/)) {
            var type = RegExp.$1;
            var id = RegExp.$2;
            this.loadedObjectId = id;
            $canvas.showLoaderLogo($(this.link));
            this.doRequest( { '_action': 'product_special', '_get': type, 'id': id } );
            return false;
        }
        return true;
    },
    doRequest: function(params) {
        var self = this;
        $.post('/ajax/', params, function(data) { self.parseAjaxResponse(data); }, 'xml');
    },
    parseAjaxResponse: function(data) {
        var esp = true;
        var rl = data.getElementsByTagName('remove_link')[0];
        if (rl) this.link.style.display = 'none';
        var invideo = data.getElementsByTagName('invideo')[0];
        if (invideo) {
            this.toggleVideo(invideo.getAttribute('src'));
        }
        var image = data.getElementsByTagName('image')[0];
        if (image) {
            esp = false;
            var popupPicture = new PopupPicture(image);
            popupPicture.onImageLoad = function() {
                $canvas.hideLoaderLogo();
            }
            popupPicture.load(true);
        }
        var html = data.getElementsByTagName('html');
        for (var i=0; i<html.length; i++) {
            var context = html[i].getAttribute('context');
            if (context) {
                var contextDOM = document.getElementById(context);
                if (contextDOM) {
                    contextDOM.style.display = 'none';
                    contextDOM.innerHTML = _getTextContent(html[i]);
                    $(contextDOM).slideDown(__SETTINGS.slideDuration);
                }
            }
        }
        var script = data.getElementsByTagName('script');
        for (var i=0; i<script.length; i++) eval(_getTextContent(script[i]));
        if (esp) $canvas.hideLoaderLogo();
    },
    toggleVideo: function(src) {
        var container = this.link;
        while ((container = container.parentNode) && (!container.className.match(/round/)));
        if (container) {
            var photoCTX = $(container).find('div.photo').get(0);
            if (photoCTX) {
                if (jQuery.isFunction(window.hideVideo)) window.hideVideo();
                var videoCTX = document.createElement('div');
                videoCTX.id = '__videoCTX'+this.loadedObjectId;
                photoCTX.appendChild(videoCTX);
                var spanObject = document.createElement('span'); spanObject.id = this.loadedObjectId+'_flashvideo';
                videoCTX.appendChild(spanObject);
                swfobject.embedSWF("/i/f/mplayer.swf", this.loadedObjectId+'_flashvideo', "240", "180", "8.0.0", "", {'clip':src}, {'wmode':'opaque'}, {});
                if (__EFFECTS_ENABLED) {
                    $(videoCTX.parentNode).find('img').animate({opacity: 0}, __SETTINGS.videoFadeDuration);
                    $(videoCTX).fadeIn(__SETTINGS.videoFadeDuration);
                } else {
                    $(videoCTX.parentNode).find('img').css('visibility', 'hidden');
                    videoCTX.style.display = 'block';
                }
                window.hideVideo = function() {
                    if (__EFFECTS_ENABLED) {
                        $(photoCTX).find('img').animate({opacity: 1}, __SETTINGS.videoFadeDuration);
                        $(videoCTX).fadeOut(__SETTINGS.videoFadeDuration, function() { photoCTX.removeChild(videoCTX); });
                    } else {
                        photoCTX.removeChild(videoCTX);
                        $(photoCTX).find('img').css('visibility', 'visible');
                    }
                    window.hideVideo = null;
                }

            }
        }
    }
};

var PopupPicture = function(data) {
    this.data = data;
    this.loaded = false;
}
PopupPicture.prototype = {
    load: function(showAfterLoad) {
        var self = this;
        this.parseData();
        this.image = new Image();
        this.image.onload = function() {
            self.loaded = true;
            if (jQuery.isFunction(self.onImageLoad)) {
                self.onImageLoad();
            }
            if (showAfterLoad) self.show();
        }
        this.image.src = this.src;
    },
    parseData: function() {
        var attrs = this.data.attributes;
        if (attrs) {
            for (var i=0; i<attrs.length; i++)
                this[attrs[i].name] = attrs[i].value;
            var comment = this.data.getElementsByTagName('comment')[0];
            if (comment)
                this.commentHTML = _getTextContent(comment);
        } else if (this.data.src) {
            this.src = this.data.src;
            this.commentHTML = this.data.comment || '';
        }
    },
    show: function() {
        var self = this;
        if (!this.loaded) {
            this.load(true);
            return;
        }
        $canvas.disableLayer();
        var $layer = this.$layer = $el('div').addClass('popup-picture').html('<div><div class="c"></div><div class="s"></div><div class="sbl"></div><div class="sb"></div><div class="o"><ins></ins></div></div>')
                        .css({top: document.documentElement.clientHeight/2+(document.documentElement.scrollTop || document.body.scrollTop)-50});
        $canvas.append($layer);
        var $d = $el('div').addClass('i').append(this.image).append('<p>'+this.commentHTML+'</p>');
        if (__EFFECTS_ENABLED) $d.css({opacity: 0});
        var $o = $layer.find('div.o').append($d).css({width: this.image.width+2});
        $layer.find('div.c,img').click(function() { self.close(); });
        var w = $o.outerWidth();
        var h = $o.outerHeight();
        if (__EFFECTS_ENABLED)
            $layer.expandAnimation(w, h, __SETTINGS.popupShowDuration, 'swing', function() { $d.animate({opacity: 1}, __SETTINGS.popupShowDuration); });
        else
            $layer.css({ width: w, marginLeft: -w/2, height: h, marginTop: -h/2 });
    },
    close: function() {
        if (__EFFECTS_ENABLED)
            this.$layer.fadeOut(__SETTINGS.popupShowDuration, function() { $(this).remove(); $canvas.enableLayer(); });
        else
            this.$layer.remove(); $canvas.enableLayer();
        delete this.$layer;
    }
}

var _showPopuptPicture = window.showPopupPicture = function(link) {
    var _popup = new PopupPicture({ 'src': link.href });
    _popup.onImageLoad = function() {
        $canvas.hideLoaderLogo();
    }
    $canvas.showLoaderLogo($(link));
    _popup.load(true);
    return false;
}

var __setupReviewForm = window.setupReviewForm = function() {
    var f = document.getElementById('Sreview-form');
    if (f)
        f.__object = new ReviewForm(f);
}

var ReviewForm = function(form) {
    this.form = form;
    this.$form = $(form);
    this.setup();
}

ReviewForm.prototype = {
    setup: function() {
        var self = this;
        this.$form.find('div.sub-form div.btn').each(function(i) {
            if (i == 0) self.showSubForm(i);
            $(this).click(function() { self.showSubForm(i); });
        });
        this.form.onsubmit = function() {
            return self.onSubmit();
        }
    },
    onSubmit: function() {
        var retVal = true;
        if (this.form['person'].value == '') {
            this.$form.find('div.attr-person').addClass('error');
            retVal = false;
        } else {
            this.$form.find('div.attr-person').removeClass('error');
        }
        if (this.form['content'].value == '') {
            this.$form.find('div.attr-content').addClass('error');
            retVal = false;
        } else {
            this.$form.find('div.attr-content').removeClass('error');
        }
        if (this.form['__captcha_answer'].value == '') {
            this.$form.find('div.captcha').addClass('error');
            retVal = false;
        } else  {
            this.$form.find('div.captcha').removeClass('error');
        }
        if (retVal) {
            this.form['__BACK'].value = window.location.toString();
        }
        return retVal;
    },
    showSubForm: function(i) {
        this.$form.find('div.sub-form div.abtn').toggleClass('abtn');
        if (this.visibleSubFormN != i) {
            if (this.visibleSubFormN != undefined) {
                this.$form.find('div.sub-form div.up-area').eq(this.visibleSubFormN).hide();
            }
            this.$form.find('div.sub-form div.up-area').eq(i).show();
            this.$form.find('div.sub-form div.btn').eq(i).addClass('abtn');
            this.visibleSubFormN = i;
        } else {
            this.$form.find('div.sub-form div.up-area').eq(i).hide();
            this.visibleSubFormN = undefined;
        }

    }
}

var StoryForm = function(form) {
    this.form = form;
    this.$form = $(form);
    this.setup();
}
StoryForm.prototype = {
    setup: function() {
        var self = this;
        this.$form.find('div.sub-form div.btn').click(function() { self.addFile(); });
        this.form.onsubmit = function() {
            return self.onSubmit();
        }
        this.rFields = new Array();
        this.$form.find('label').each(function() {
            if (this.getElementsByTagName('span')[0]) {
                var fieldName = this.getAttribute('for');
                self.rFields.push(this.parentNode.getElementsByTagName('input')[0].name);
            }
        });
        this.count = 0;
    },
    onSubmit: function() {
        var retVal = true;
        for (var i=0; i<this.rFields.length; i++) {
            if (this.form[this.rFields[i]].value == '') {
                this.$form.find('div.attr-'+this.rFields[i]).addClass('error');
                retVal = false;
            } else {
                this.$form.find('div.attr-'+this.rFields[i]).removeClass('error');
            }
        }
        return retVal;
    },
    addFile: function() {
        if ((!this.form['__upload_file'+this.count]) || (this.form['__upload_file'+this.count].value)) {
            this.count++;
            var labelCaption = 'Фото/видеофайл';
            var inputName = '__upload_file'+this.count;
            $('#__story-form-files').append('<div class="p file attr-photo"><label>'+labelCaption+'</label><div class="f-input"><input type="file" value="" name="'+inputName+'"/></div></div>');
        }
    }
}



var Gallery = function(object) {
    this.object = object;
}
Gallery.prototype = {
    setup: function() {
        var self = this;
        this.__lineObject = new ProductLine(this.object, 'gallery', 'фотографии');
        this.$object = $(this.object);
        this.$container = $(document.createElement('div')).addClass('image').insertAfter(this.$object);
        var itemHeight = this.__lineObject.itemHeight;
        var loc = window.location.toString();
        var rIndex = loc.indexOf('#');
        var loadedImgUrl;
        if (rIndex > 0) loadedImgUrl = loc.substring(rIndex+1, loc.length);
        this.__lineObject.activeIndex = 0;
        this.$object.find('a')
            .click(function() { self.showImage(this); return false; })
            .hover(function() { $(this).fadeTo(__SETTINGS.galleryLinkFadeTimeout, 1); }, function() { if (this != self.activeLink) $(this).fadeTo(__SETTINGS.galleryLinkFadeTimeout, __SETTINGS.galleryLinkFadeValue) })
            .each(function(i) {

                var img = this.getElementsByTagName('img')[0];
                var top = Math.floor((itemHeight - img.height)/2);
                var href = this.href.replace('http://'+this.hostname, '');
                this.href = '#' + href;
                if (href == loadedImgUrl) self.__lineObject.activeIndex = i;
                $(this).css( { width: img.width, height: img.height, top: top });
            })
            .css( { opacity: __SETTINGS.galleryLinkFadeValue } );
        this.__lineObject.updateEnv();
        this.showImage(this.$object.find('a').get(this.__lineObject.activeIndex));
    },
    showImage: function(link) {
        var self = this;
        if (link) {
            var src = link.href.replace(/^.*#/,'');
            if ((this.curImageDOM) && (this.curImageDOM.src == src)) return;
            var image = new Image();
            image._comment = link.parentNode.getElementsByTagName('div')[0];
            image.onload = function() {
                if (self.activeLink) $(self.activeLink).fadeTo(__SETTINGS.galleryLinkFadeTimeout, __SETTINGS.galleryLinkFadeValue);
                self.activeLink = link;
                $(self.activeLink).fadeTo(__SETTINGS.galleryLinkFadeTimeout, 1);
                self._swapImages(this);
            }
            image.src = src;
        }
    },
    _swapImages: function(newImageDOM) {
        var self = this;
        this.$container.find('div.comment').remove();
        if (this.curImageDOM)
            $(this.curImageDOM).fadeOut(__SETTINGS.galleryImageFadeTimeout, function() { $(this).remove(); } );
        this.$container.animate({ height: newImageDOM.height }, __SETTINGS.galleryImageFadeTimeout);
        var w = newImageDOM.width
        $(newImageDOM)
            .css({ 'margin-left': -Math.floor(w/2) })
            .hide()
            .appendTo(this.$container)
            .fadeIn(__SETTINGS.galleryImageFadeTimeout,
                    function() {
                        if ((newImageDOM._comment) && (newImageDOM._comment.innerHTML)) {
                            var $comment = $(document.createElement('div')).addClass('comment');
                            $comment
                                .append($(document.createElement('ins')))
                                .append($(document.createElement('div')).html(newImageDOM._comment.innerHTML))
                                .css({ 'width': w, 'margin-left': -Math.floor(w/2) })
                                .appendTo(self.$container);
                            $comment.height($comment.get(0).scrollHeight);
                        }
                    }
                   );
        this.curImageDOM = newImageDOM;
    }
}


jQuery.fn.extend({
    disableLayer: function(isSoft) {
        if (!this._disableLayer) {
            if ((__OLD_IE) && (!isSoft)) {
                this._disableLayer = $el('iframe').addClass('disable-layer').css({ height: this.height() }).appendTo(this);
            } else {
                this._disableLayer = $el('div').addClass('disable-layer').css({ height: this.height() }).appendTo(this);            }
        }
    },
    enableLayer: function() {
        if (this._disableLayer) {
            this._disableLayer.remove();
            this._disableLayer = null;
        }
    },
    showLoaderLogo: function($c) {
        var offset = $c.offset();
        if (!this.children('div.loader-logo').length)
            this.append($('<div class="loader-logo" />').css({ top: offset.top, left: offset.left+($c.width()/2) }));
    },
    hideLoaderLogo: function() {
        this.children('div.loader-logo').remove();
    },
    accordeon: function() {
        var $acc = this;
        $acc.find('h3>a').click(function() {
            var li = this.parentNode;
            while ((li = li.parentNode) && (li.tagName.toLowerCase() != 'li'));
            if (!$(li).hasClass('open')) {
                $acc.find('li.open ul').slideUp(__SETTINGS.accordeonDuration, function() { $(this.parentNode).removeClass('open'); });
                $(li).find('ul').slideDown(__SETTINGS.accordeonDuration, function() { $(this.parentNode).addClass('open'); });
            }
        });
    },
    expandAnimation: function(w, h, duration, easing, callback) {
        this.animate({ width: w, marginLeft: -w/2 }, duration, easing,
           function() {
                $(this).animate({  height: h, marginTop: -h/2 }, duration, easing, callback);
           });
    },
    gallery: function() {
        this.each(function() {
            this.__gallery = new Gallery(this);
            this.__gallery.setup();
        });
    },
    dropDownMenu: function() {
        this.each(function() {
            var $this = $(this);
            var $submenu = $('ul', this);
            if ($submenu.length) {
                var shown = false;
                var delayTimer = null;
                var $popup = $el('div')
                    .addClass('popup-menu')
                    .append($submenu)
                    .append($el('ins'))
                    .append($el('ins').addClass('t'))
                    .append($el('ins').addClass('b'))
                    .css({ display: 'none' })
                    .appendTo($canvas);
                $([$this.get(0), $popup.get(0)]).mouseover(function() {
                    if (delayTimer) window.clearTimeout(delayTimer);
                    if (!shown) {
                        var pos = $this.offset();
                        pos.left += $this.width() + 10;
                        pos.top -= 5;
                        shown = true;
                        $popup.css({ left: pos.left, top: pos.top, display: 'block' });
                        if (__OLD_IE) {
                            $('ins:first', $popup).css({ height: $popup.height()-32 });
                        }
                    } else {
                        return false;
                    }
                    return true;
                }).mouseout(function() {
                    if (delayTimer) clearTimeout(delayTimer);
                    delayTimer = window.setTimeout(function() {
                        delayTimer = null;
                        $popup.css({ display: 'none' });
                        shown = false;
                    }, 100);
                    return false;
                });
            }
        });
    }
});

window.showSeminarOrderForm = function(seminarId) {
    var loc = window.location.toString();
    loc = loc.replace(/#.*/, '');
    window.location = loc + '#order' + seminarId;
    $('#seminar-order-form' + seminarId).show();
}
window.checkSeminarOrderForm = function() {
    var loc = window.location.toString();
    if (loc.match(/#order(\d+)/)) {
        var id = RegExp.$1;
        $('#seminar-order-form' + id).show();
        var $cnt = $('#seminar-order-form' + id);
        if ($cnt.length) {
            var f = $('form', $cnt).get(0);
            if ((f) && (f.id != 'assist-payform')) {
                f.addParticipantsCount = $('input[name=participant]').length;
                calcFromSeminarOrder(f);
            }
        }
    }
}
window.addParticipantToSeminarOrder = function(el) {
    var $form = $(el).parents('form').eq(0);
    var f = $form.get(0);
    var $pblock = $('.additional-participants', $form);
    if (!f.addParticipantsCount)
        f.addParticipantsCount = 0;
    f.addParticipantsCount ++;
    $el('div')
        .addClass('p')
        .addClass('a-part')
        .html('<label>Ф.И.О. участника</label><div class="i-round"><ins class="rb"></ins><ins class="lb"></ins><ins class="rt"></ins><ins class="lt"></ins><div class="i-rb"><input type="text" name="participant" /></div></div>')
        .append(
            $el('span')
            .addClass('btn min-btn')
            .click(function() { removeParticipantFromSeminarOrder(this) })
        )
        .insertBefore($pblock);
    calcFromSeminarOrder(f);
}

window.removeParticipantFromSeminarOrder = function(el) {
    var $form = $(el).parents('form').eq(0);
    var f = $form.get(0);
    f.addParticipantsCount --;
    $(el.parentNode).remove();
    calcFromSeminarOrder(f);
}

function calcFromSeminarOrder(form) {
    var aName = (form.addParticipantsCount) ? 'price_discount' : 'price';
    if (form[aName]) {
        var cost = form[aName].value * (form.addParticipantsCount + 1);
        cost = cost.toString();
        var $s = $('.seminar-cost>span', form);
        $('span', $s).remove();
        var html = '';
        var i = 0;
        while (i < cost.length) {
            var k = ((i == 0) && (cost.length % 3 > 0)) ? (cost.length % 3) : 3;
            html += '<span>' + cost.substr(i, k) + '</span>';
            i += k;
        }
        $s.prepend(html);
    }
}

var _submitForm = window.submitForm = function(ctxx) {
    var form = ctxx;
    while ((form =form.parentNode) && (form.tagName.toLowerCase() != 'form'));
    if (jQuery.isFunction(form.onsubmit)) {
        if (form.onsubmit()) return form.submit();
    } else {
        return form.submit();
    }
    return false;
}
var _resetForm = window.resetForm = function(ctxx) {
    var form = ctxx;
    while ((form =form.parentNode) && (form.tagName.toLowerCase() != 'form'));
    form.reset();
    return false;
}

var _showSimplePopup = window.showSimplePopup = function(url, width, height) {
    if (width>screen.width-100) width = screen.width-100;
    if (height>screen.height-100) height = screen.height-100;
    var posX = Math.floor((screen.width-width)/2);
    var posY = Math.floor((screen.height-height)/2);
    var popupWindow = window.open(url, '__NPPST_POPUP_WINDOW', 'dependent=yes,height='+height+',width='+width+',innerHeight='+height+',innerWidth='+width+',location=no,menubar=no,screenX='+posX+',screenY='+posY+',toolbar=no,scrollbars=yes');
    popupWindow.focus();
    return false;
}

var _getTextContent = window._getTextContent = function(xmlElement) {
    if (xmlElement.text != undefined) return xmlElement.text;
    else if (xmlElement.textContent != undefined) return xmlElement.textContent;
    else if (xmlElement.firstChild != undefined) return xmlElement.firstChild.nodeValue;
}
$().ajaxError(function(event, request, settings) { alert('Some errors with ajax loader\nResponse: \n'+request.status+'\n'+request.responseText); });

var $el = window.$el = function(tagName) {
    return $(document.createElement(tagName));
}

})(jQuery);
