(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.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'));
    },
    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);
        }
    },
    showLoginForm: function() {
        if (this.__loginFormHTML)
            this.showPopupMessage(this.__loginFormHTML);
    }
}




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);

