var today = new Date();
var months = new Array('января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря');
var curDate = today.getDate();
var curMonth = today.getMonth();
var curYear = today.getFullYear();

/* AUXILIARY FUNCTIONS */

function addEventHandler(oTarget, sEventName, oHandler){
    if(typeof(oTarget.addEventListener) != 'undefined'){
        oTarget.addEventListener(sEventName, oHandler, false);
    }else{
        oTarget.attachEvent('on' + sEventName, oHandler);
    }
}

function setCookie(sName, sValue, iHours){
  var oDate = new Date();
  if(typeof(iHours) == "undefined"){
    iHours = 1;
  }
  oDate.setHours(oDate.getHours() + iHours);
  delCookie(sName);
  document.cookie = sName + "=" + escape(sValue) + "; path=/; expires="+oDate.toGMTString();
}

function delCookie(sName) {
    if(getCookie(sName)){
        document.cookie = sName + "=" + "; path=/ ;expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

function getCookie(sName){
    var aCookie = document.cookie.split("; ");
    var value = "";
    for(var i = 0; i < aCookie.length; i++){
      var aCrumb = aCookie[i].split("=");
      if(sName == aCrumb[0]){
          if(typeof(aCrumb[1]) == 'undefined'){
            value = null;
          }else{
              value = unescape(aCrumb[1]);
          }
          return value;
      }
    }
    return null;
} 

function jumpTo(url){
    document.location.href = url;
}

function checkSendMessage(obj){
    if(obj.name.value == ""){
        alert('Введите Фамилию и Имя');
        obj.name.focus();
        return false;
    }
    if(obj.email.value == ""){
        alert('Заполните Ваш адрес электронной почты или номер телефона');
        obj.email.focus();
        return false;
    }
    if(obj.message.value == ""){
        alert('Напишите нам что-нибудь');
        obj.message.focus();
        return false;
    }
    return true;
}

function checkOrderForm(obj){
    if(typeof(obj.form_session_id) == 'undefined' || obj.form_session_id.value == ''){
        alert('Не удалось проверить сессию, которая необходима для отправки данных.\nПожалуйста, включите JavaScript, Cookie и перегрузите эту страницу.');
        return false;
    }
    if(obj.load_date.value == ""){
        alert('Укажите дату выполнения заявки');
        obj.load_date.focus();
        return false;
    }
    if(obj.cargo_name.value == ""){
        alert('Выберите наименование груза');
        obj.cargo_name.focus();
        return false;
    }
    if(obj.cargo_weight.value == ""){
        alert('Укажите общий вес груза');
        obj.cargo_weight.focus();
        return false;
    }
    if(obj.cargo_volume.value == ""){
        alert('Укажите общий объем груза');
        obj.cargo_volume.focus();
        return false;
    }
    if(obj.cargo_length.value == ""){
        alert('Укажите длину груза');
        obj.cargo_length.focus();
        return false;
    }
    if(obj.cargo_width.value == ""){
        alert('Укажите ширину груза');
        obj.cargo_width.focus();
        return false;
    }
    if(obj.cargo_height.value == ""){
        alert('Укажите высоту груза');
        obj.cargo_height.focus();
        return false;
    }
    if(obj.region.value == ""){
        alert('Укажите регион перевозки');
        return false;
    }
    if(obj.load_city.value == ""){
        alert('Укажите город загрузки');
        obj.load_city.focus();
        return false;
    }
    if(obj.unload_city.value == ""){
        alert('Укажите город разгрузки');
        obj.unload_city.focus();
        return false;
    }
    if(obj.city.value == ""){
        alert('Укажите город, в котором находится заказчик');
        obj.city.focus();
        return false;
    }
    if(obj.org.value.length < 3){
        alert('Укажите наименование заказчика');
        obj.org.focus();
        return false;
    }
    if(obj.phone_country.value == "" || obj.phone_code.value == "" || obj.phone.value == ""){
        alert('Укажите телефон');
        obj.phone.focus();
        return false;
    }
    if(obj.name.value == ""){
        alert('Укажите контактное лицо');
        obj.name.focus();
        return false;
    }
    if(obj.email.value == ""){
        alert('Укажите e-mail для уведомления');
        obj.email.focus();
        return false;
    }
    return true;
}

var prevActPic = 1;
function changeBigImage(id, psrc){
    if(document["bigpic"])
        document["bigpic"].src = psrc;
    if(document['smpic'+prevActPic])
        document['smpic'+prevActPic].style.border='1px solid #6DAEE1';
    if(document['smpic'+id]){
        document['smpic'+id].style.border='1px solid #F26522';
        prevActPic = id;
    }
}

function showImage(src, picWidth, picHeight, picTitle){
    var width = parseInt(picWidth)+37;
    if(width > 1000)
        width = 1000;
    var height = parseInt(picHeight)+60;
    if(height > 700)
        height = 700;
    var x = (window.screen.width-width)/2;
    var y = (window.screen.height-height)/2;
    if(x < 0) x = 0;
    if(y < 0) y = 0;
    if(typeof(picTitle) == 'undefined'){
        picTitle = '';
    }
    window.open('/image/?src='+src+'&width='+picWidth+'&height='+picHeight+'&title='+escape(picTitle), 'image', 'width='+width+',height='+height+',left='+x+',top='+y+', menubar=no, scrollbars=yes, status=no, resizable=yes');
}

//
// Calculate cargo transport cost
//

var comCargo = Array();
/* Tyumen */
comCargo[0] = Array();
comCargo[0][0] = new Array(4.8, 970);
comCargo[0][1] = new Array(3.55, 745);
comCargo[0][2] = new Array(2.95, 650);
comCargo[0][3] = new Array(2.6, 610);
comCargo[0][4] = new Array(2.4, 565);
comCargo[0][5] = new Array(2.25, 635);
comCargo[0][6] = new Array(2.15, 500);
comCargo[0][7] = new Array(2.05, 480);
comCargo[0][8] = new Array(2, 460);
comCargo[0][9] = new Array(1.95, 450);
comCargo[0][10] = new Array(1.9, 435);

/* Ekaterinburg */
comCargo[1] = Array();
comCargo[1][0] = new Array(4.8, 970);
comCargo[1][1] = new Array(3.55, 745);
comCargo[1][2] = new Array(2.95, 650);
comCargo[1][3] = new Array(2.6, 610);
comCargo[1][4] = new Array(2.4, 565);
comCargo[1][5] = new Array(2.25, 535);
comCargo[1][6] = new Array(2.15, 500);
comCargo[1][7] = new Array(2.05, 480);
comCargo[1][8] = new Array(2, 460);
comCargo[1][9] = new Array(1.95, 450);
comCargo[1][10] = new Array(1.9, 435);

/* Chelyabinsk */
comCargo[2] = Array();
comCargo[2][0] = new Array(4.8, 970);
comCargo[2][1] = new Array(3.55, 745);
comCargo[2][2] = new Array(2.95, 650);
comCargo[2][3] = new Array(2.6, 610);
comCargo[2][4] = new Array(2.4, 565);
comCargo[2][5] = new Array(2.25, 535);
comCargo[2][6] = new Array(2.15, 500);
comCargo[2][7] = new Array(2.05, 480);
comCargo[2][8] = new Array(2, 460);
comCargo[2][9] = new Array(1.95, 450);
comCargo[2][10] = new Array(1.9, 435);

/* Ufa */
comCargo[3] = Array();
comCargo[3][0] = new Array(5.2, 1040);
comCargo[3][1] = new Array(3.9, 820);
comCargo[3][2] = new Array(3.3, 720);
comCargo[3][3] = new Array(2.95, 685);
comCargo[3][4] = new Array(2.7, 640);
comCargo[3][5] = new Array(2.55, 610);
comCargo[3][6] = new Array(2.45, 570);
comCargo[3][7] = new Array(2.35, 560);
comCargo[3][8] = new Array(2.3, 530);
comCargo[3][9] = new Array(2.25, 520);
comCargo[3][10] = new Array(2.2, 510);

/* Kazan */
comCargo[4] = Array();
comCargo[4][0] = new Array(5.4, 1090);
comCargo[4][1] = new Array(4.1, 865);
comCargo[4][2] = new Array(3.5, 770);
comCargo[4][3] = new Array(3.15, 735);
comCargo[4][4] = new Array(2.95, 690);
comCargo[4][5] = new Array(2.75, 660);
comCargo[4][6] = new Array(2.65, 630);
comCargo[4][7] = new Array(2.55, 605);
comCargo[4][8] = new Array(2.5, 580);
comCargo[4][9] = new Array(2.45, 570);
comCargo[4][10] = new Array(2.4, 560);

/* Samara */
comCargo[5] = Array();
comCargo[5][0] = new Array(5.4, 1090);
comCargo[5][1] = new Array(4.1, 865);
comCargo[5][2] = new Array(3.5, 770);
comCargo[5][3] = new Array(3.15, 735);
comCargo[5][4] = new Array(2.95, 690);
comCargo[5][5] = new Array(2.75, 660);
comCargo[5][6] = new Array(2.65, 630);
comCargo[5][7] = new Array(2.55, 605);
comCargo[5][8] = new Array(2.5, 580);
comCargo[5][9] = new Array(2.45, 570);
comCargo[5][10] = new Array(2.4, 560);

/* Moscow */
comCargo[6] = Array();
comCargo[6][0] = new Array(5.6, 1110);
comCargo[6][1] = new Array(4.2, 890);
comCargo[6][2] = new Array(3.6, 790);
comCargo[6][3] = new Array(3.25, 760);
comCargo[6][4] = new Array(3.05, 720);
comCargo[6][5] = new Array(2.9, 680);
comCargo[6][6] = new Array(2.75, 650);
comCargo[6][7] = new Array(2.65, 630);
comCargo[6][8] = new Array(2.6, 605);
comCargo[6][9] = new Array(2.55, 590);
comCargo[6][10] = new Array(2.5, 575);

/* S.Petersburg */
comCargo[7] = Array();
comCargo[7][0] = new Array(6.6, 1325);
comCargo[7][1] = new Array(5.2, 1095);
comCargo[7][2] = new Array(4.6, 1005);
comCargo[7][3] = new Array(4.2, 980);
comCargo[7][4] = new Array(3.95, 935);
comCargo[7][5] = new Array(3.8, 900);
comCargo[7][6] = new Array(3.65, 865);
comCargo[7][7] = new Array(3.55, 845);
comCargo[7][8] = new Array(3.5, 825);
comCargo[7][9] = new Array(3.45, 810);
comCargo[7][10] = new Array(3.4, 790);

var comCargoWeights = new Array(2.5, 4, 5.5, 7, 8.5, 10, 11.5, 13, 14.5, 16, 17.5);
var comCargoVolumes = new Array(12.5, 19, 25, 30, 36, 42, 49, 55, 62, 68, 75);
var minimumCost = new Array(8000, 8000, 8000, 8000, 8000, 8000, 8000, 9000);

function calculateCargoCost(city, weight, volume){
    var priceWeight = -1;
    var priceVolume = -1;
    var resultCost = 0;
    if(typeof(comCargo[city]) != 'undefined'){
        for(var i = 0; i <= 10; i++){
            if(priceWeight == -1 && weight <= comCargoWeights[i]){
                priceWeight = i;
            }
            if(priceVolume == -1 && volume <= comCargoVolumes[i]){
                priceVolume = i;
            }
        }
        
        if(priceWeight != -1 && priceVolume != -1){
            priceWeight = comCargo[city][priceWeight][0]*weight*1000;
            priceVolume = comCargo[city][priceVolume][1]*volume;
            resultCost = Math.max(priceWeight, priceVolume, minimumCost[city]);
        }
    }
    return resultCost;
}

function checkCargoForm(oForm){
    var city = parseInt(oForm.city.value);
    var weight = parseFloat(oForm.weight.value);
    var volume = parseFloat(oForm.volume.value);
    
    if(weight <= 0.009 || weight > comCargoWeights[10]){
        alert('Груз с таким весом мы не повезем.\nДопустимый вес: 10кг-'+comCargoWeights[10]+'т.');
        oForm.weight.focus;
        return false;
    }
    else if(volume <= 0 || volume > comCargoVolumes[10]){
        alert('Груз с таким объемом мы не повезем.\nДопустимый объем: 1-'+comCargoVolumes[10]+'м3');
        oForm.weight.focus;
        return false;
    }
    
    //var reslutObj = document.getElementById('costResult');
    //if(reslutObj != null){
        var reslultCost = calculateCargoCost(city, weight, volume);
        if(reslultCost > 0){
            reslultCost = reslultCost.toString().replace(/^(\d+\.\d{0,2}).*/, '$1', reslultCost);
            alert('Стоимость перевозки вашего груза: '+reslultCost+'руб.');
            //reslutObj.innerHTML = 'Стоимость перевозки вашего груза: <strong>'+reslultCost+'руб.</strong><br>';
        }else{
            alert('Произошла ошибка рассчета. Возможно не заданы параметры в форме.');
            //reslutObj.innerHTML = 'Произошла ошибка рассчета. Возможно не заданы параметры в форме.<br>';
        }
    //}
    
    return false;
}

function checkConsultForm(oForm){
    if(oForm.name.value == ''){
        alert('Введите ваше имя');
        oForm.name.focus();
        return false;
    }
    re = new RegExp("^[a-zA-Z0-9\\_\\.\\-]+@([a-zA-Z0-9\\-]+\\.)+[a-zA-Z]{2,5}$");
    if(oForm.email.value != '' && !re.test(oForm.email.value)){
        alert('E-mail введен неверно');
        oForm.email.focus();
        return false;
    }
    if(oForm.message.value == ''){
        alert('Сообщение не заполнено');
        oForm.message.focus();
        return false;
    }
    return true;
}

function setFormSession(){
    var aForms = new Array('send', 'email', 'consultForm');
    for(i = 0; i < aForms.length; i++){
        if(document.forms[aForms[i]]){
            var oForm = document.forms[aForms[i]];
            var sessionId = getCookie('usid');
            if(sessionId != null){
                var isIE = typeof(document.swapNode) != 'undefined';
                var sessionField = document.createElement(isIE ? '<input name="form_session_id" type="text">' : 'input');
                sessionField.type = 'hidden';
                sessionField.name = 'form_session_id';
                sessionField.value = sessionId;
                oForm.appendChild(sessionField);
            }
        }
    }
}

function onBodyLoad(){
    setFormSession();
}

addEventHandler(window, 'load', function(){onBodyLoad()});

function onCargoNameChanged(oForm, bClearOther){
    bClearOther = bClearOther != undefined ?  bClearOther : true;
    if(oForm.cargo_name.value != 'Другой'){
        oForm.cargo.style.display = 'none';
        oForm.cargo.value = oForm.cargo_name.value;
    }else{
        oForm.cargo.style.display = 'inline';
        if(bClearOther){
            oForm.cargo.value = '';
        }
    }
    
}

function onChangePrepay(oForm){
    oForm.prepay_percent.disabled = !oForm.prepay.checked;
}

function onChangePayOn(oForm, element){
    var bDisableDays = null;
    if(element != undefined){
        if(element == 'unload' && oForm.pay_on_unload.checked){
            oForm.pay_after.checked = false;
            bDisableDays = true;
        }else if(element == 'after' && oForm.pay_after.checked){
            oForm.pay_on_unload.checked = false;
            bDisableDays = false;
        }else if(element == 'after' && !oForm.pay_after.checked){
            bDisableDays = true;
        }
    }else{
        bDisableDays = !oForm.pay_after.checked;
    }
    
    if(bDisableDays != null){
        oForm.pay_bank_days.disabled = bDisableDays;
    }
}

function checkCargoForm(formObj){
    if(formObj.cargo.value == ''){
        alert('Укажите наименование груза');
        return false;
    }
    if(formObj.weight.value == ''){
        alert('Введите вес');
        formObj.weight.focus();
        return false;
    }
    if(formObj.volume.value == ''){
        alert('Введите объём');
        formObj.volume.focus();
        return false;
    }
    if(formObj.load_point.value == ''){
        alert('Заполните место погрузки');
        formObj.load_point.focus();
        return false;
    }
    if(formObj.unload_point.value == ''){
        alert('Заполните место разгрузки');
        formObj.unload_point.focus();
        return false;
    }
    var bHasChecked = false;
    var aFields = formObj.elements['car_types[]'];
    for(var i = 0; i < aFields.length; i++){
        if(aFields[i].checked){
            bHasChecked = true;
            break;
        }
    }
    if(!bHasChecked){
        alert('Выберите транспорт');
        return false;
    }
    if(formObj.price.value == ''){
        alert('Заполните ставку');
        formObj.price.focus();
        return false;
    }
    if(formObj.price_cashless.value == ''){
        alert('Заполните ставку по безналу');
        formObj.price_cashless.focus();
        return false;
    }
    if(formObj.pay_type.value == ''){
        alert('Выберите тип ставки');
        formObj.pay_type.focus();
        return false;
    }
}

function openPopupWindow(url, wndW, wndH){
    wndW = wndW || 780;
    wndH = wndH || 750;
    wndX = (screen.availWidth-wndW)/2;
    wndY = (screen.availHeight-wndH)/2;
    this.popupWindow = window.open(url, "popupimg", "toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable,alwaysRaised,dependent,titlebar=yes,width=" + wndW + ",height=" + wndH + ",left=" + wndX + ",top=" + wndY);
}

var rotateSpecial = {
    aImages: [],
    aUrls: [],
    interval: 5000,
    fadeInSteps: 20,
    animateTime: 500,
    
    currentImage: 0,
    oImage: null,
    oNextImage: null,
    currentFadeInStep: 0,
    fadeInStart: 0,
    
    setImages: function(aImages){
        this.aImages = aImages;
        return this;
    },
    
    setUrls: function(aUrls){
        this.aUrls = aUrls;
        return this;
    },
    
    next: function(){
        this.currentImage ++;
        if(this.currentImage >= this.aImages.length){
            this.currentImage = 0;
        }
        
        this.oNextImage = new Image();
        this.oNextImage.onload = function(_this){return function(){_this.setImage()}}(this);
        this.oNextImage.src = this.aImages[this.currentImage];
        this.oNextImage.className = 'specBack'
    },
    
    setImage: function(){
        var oBlock = document.getElementById('specBig');
        if(oBlock != null){
            this.oImage = oBlock.getElementsByTagName('IMG')[0];
            if(this.oImage){
                if(this.oImage.parentNode.childNodes.length > 1){
                    for(var i = this.oImage.parentNode.childNodes.length - 1; i >= 1; i--){
                        this.oImage.parentNode.removeChild(this.oImage.parentNode.childNodes[i]);
                    }
                }
                
                var oClone = this.oImage.cloneNode(true);
                oClone.className = 'specBack';
                oBlock.appendChild(oClone);

                this.oImage.src = this.oNextImage.src;
                this.oNextImage = null;
                this.setOpacity(this.oImage, 0);
                
                this.currentFadeInStep = 0;
                if(this.fadeInSteps > this.currentFadeInStep){
                    this.fadeInStart = (new Date()).getTime();
                    this.fadeIn();
                }
            }
        }
    },
    
    fadeIn: function(){
        this.currentFadeInStep ++;
        var opacity = Math.min(1, this.currentFadeInStep / this.fadeInSteps);
        this.setOpacity(this.oImage, opacity);

        if(this.currentFadeInStep < this.fadeInSteps){
            setTimeout(function(){rotateSpecial.fadeIn()}, this.animateTime / this.fadeInSteps);
        }else{
            document.getElementById('specBig').href = this.aUrls[this.currentImage];
            setTimeout(function(){rotateSpecial.next()}, rotateSpecial.interval);
            
            if((new Date()).getTime() - this.fadeInStart > this.animateTime + this.fadeInSteps * 5){
                this.fadeInSteps = 5;
            }
        }
    },
    
    setOpacity: function(oElement, iOpacity){
        if(typeof(oElement.style.MozOpacity) != "undefined"){
            oElement.style.MozOpacity = iOpacity;
        }else if(typeof(oElement.style.opacity) != "undefined"){
            oElement.style.opacity = iOpacity;
        }else if(typeof(oElement.style.KhtmlOpacity) != "undefined"){
            oElement.style.KhtmlOpacity = iOpacity;
        }else{
            oElement.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + (iOpacity * 100) + ");";
        }
    }
}

var oPositions = {
    getDocumentLeft : function(){
        return window.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft); 
    },

    getDocumentTop : function(){
        return window.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop); 
    },

    getPointerPosition : function(oEvent){
        var aData = new Array(0, 0);
        oEvent = oEvents.validate(oEvent);
        if(oEvent.pageX || oEvent.pageY){
            aData[0] = oEvent.pageX;
            aData[1] = oEvent.pageY;
        }else if(oEvent.clientX || oEvent.clientY){
            aData[0] = oEvent.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
            aData[1] = oEvent.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
        }
        return aData;
    },

    getObjectPosition : function(oObject, isCalculatRelative){
        if(!isCalculatRelative){
            isCalculatRelative = false;
        }

        var counter = 0;
        var aData = new Array(0, 0);
        do{
            if(counter > 0 && isCalculatRelative){
                var sParentPositionStyle = oDOM.getStyle(oObject, 'position');
                if(sParentPositionStyle == 'absolute' || sParentPositionStyle == 'relative'){
                    break;
                }
            }
            aData[0] += oObject.offsetLeft;
            aData[1] += oObject.offsetTop;
            counter ++;
        }while((oObject = oObject.offsetParent) != null);

        return aData;
    }
}

var oEvents = {
    validate : function(oEvent){
        return oEvent ? oEvent : window.event;
    },

    getTarget : function(oEvent){
        oEvent = this.validate(oEvent);
        return oEvent.srcElement || oEvent.target;
    },

    send : function(oTarget, sEvent){
        if(document.createEventObject){
            var oEvent = document.createEventObject();
            oTarget.fireEvent('on' + sEvent, oEvent);
        }else if(document.createEvent){
            var oEvent = document.createEvent("HTMLEvents");
            oEvent.initEvent(sEvent, false, false);
            oTarget.dispatchEvent(oEvent);
        }else{
            return false;
        }
        return true;
    },

    addHandler : function(oTarget, sEvent, oHandler){
        if(typeof(oTarget.addEventListener) != 'undefined'){
            oTarget.addEventListener(sEvent, oHandler, false);
        }else{
            oTarget.attachEvent('on' + sEvent, oHandler);
        }
    },

    removeHandler : function(oTarget, sEvent, oHandler){
        if(typeof(oTarget.removeEventListener) != 'undefined'){
            oTarget.removeEventListener(sEvent, oHandler, false);
        }else if(oTarget.detachEvent){
            oTarget.detachEvent('on' + sEvent, oHandler);
        }
    },

    stopProcessing : function(oEvent){
        oEvent = this.validate(oEvent);
        if(typeof(oEvent.stopPropagation) != 'undefined'){
            oEvent.stopPropagation();
        }else if(typeof(oEvent.cancelBubble) != 'undefined'){
            oEvent.cancelBubble = true;
        }
        if(typeof(oEvent.preventDefault) != 'undefined'){
            oEvent.preventDefault();
        }else{
            oEvent.returnValue = false;
        }
    }
}

var oPopupMenu = {
    definedHandlers : {},
    currentOpened : {
        oLink : null,
        oPopup : null
    },

    showMenu : function(oLink, sPopupId, iCustomTopOffset){
        clearTimeout(this.hideTimeout);
        this.hideCurrentOpenedPopup();

        if(typeof(iCustomTopOffset) == 'undefined'){
            iCustomTopOffset = 0;
        }

        var oPopup = document.getElementById(sPopupId);
        if(oPopup != null && oPopup.innerHTML != ''){
            var linkSId = oLink.href ? oLink.href : (oLink.id ? oLink.id : '');
            if(!this.definedHandlers['link' + linkSId]){
                oEvents.addHandler(oLink, 'mouseout', function(_this){return function(){_this.hideMenu()}}(this));
                this.definedHandlers['link' + linkSId] = true;
            }
            if(!this.definedHandlers['popup' + sPopupId]){
                oEvents.addHandler(oPopup, 'mouseover', function(_this){return function(){_this.disableHideMenu()}}(this));
                oEvents.addHandler(oPopup, 'mouseout', function(_this){return function(){_this.hideMenu()}}(this));
                this.definedHandlers['popup' + sPopupId] = true;
            }

            oLink.className = oLink.className + ' activePopup';

            var linkPosition = oPositions.getObjectPosition(oLink, false);
            oPopup.style.left = linkPosition[0] - 1 + 'px';
            oPopup.style.top = linkPosition[1] + oLink.offsetHeight + iCustomTopOffset + 'px';
            /*oPopup.style.width = oLink.offsetWidth - 1 + 'px';*/
            oPopup.style.display = 'block';

            this.currentOpened.oLink = oLink;
            this.currentOpened.oPopup = oPopup;
        }
    },

    hideCurrentOpenedPopup : function(){
        if(this.currentOpened.oPopup != null){
            this.currentOpened.oLink.className = this.currentOpened.oLink.className.replace(' activePopup', '');
            this.currentOpened.oPopup.style.display = 'none';

            this.currentOpened.oLink = null;
            this.currentOpened.oPopup = null;
        }
    },

    hideMenu : function(isDoHide){
        if(!isDoHide){
            this.hideTimeout = setTimeout(function(_this){return function(){_this.hideMenu(true)}}(this), 50);
        }else{
            this.hideCurrentOpenedPopup();
        }
    },

    disableHideMenu : function(){
        clearTimeout(this.hideTimeout);
    }
}






if(typeof(document.getElementsByClassName) == 'undefined'){
    document.getElementsByClassName = function(className){return getElementsByClassName(document, className)};
}

function getElementsByClassName(oParent, className){
    var rxCheck = new RegExp('\\b' + className + '\\b');
    var oTags = oParent.getElementsByTagName('*');
    
    var aResult = [];
    for(var i = 0; i < oTags.length; i++){
        if(rxCheck.test(oTags[i].className)){
            aResult.push(oTags[i]);
        }
    }
    
    return aResult;
}

function setOpacity(oElement, iOpacity){
    if(typeof(oElement.style.MozOpacity) != "undefined"){
        oElement.style.MozOpacity = iOpacity;
    }else if(typeof(oElement.style.opacity) != "undefined"){
        oElement.style.opacity = iOpacity;
    }else if(typeof(oElement.style.KhtmlOpacity) != "undefined"){
        oElement.style.KhtmlOpacity = iOpacity;
    }else{
        oElement.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + (iOpacity * 100) + ");";
    }
}

var oBase = {
    isIE : document.swapNode,
    isWebKit : /WebKit/.test(navigator.userAgent),
    isFF : this.isWebKit && /Gecko/.test(navigator.userAgent)
}

function onDomLoaded(callbackFunction){
    if(document.addEventListener){
        oEvents.addHandler(document, 'DOMContentLoaded', callbackFunction);
    }else if(/WebKit/i.test(navigator.userAgent)){
        var checkInterval = setInterval(
            function(){
                if (/loaded|complete/.test(document.readyState)){
                    clearInterval(checkInterval);
                    callbackFunction();
                }
            },
            10
        );
    }else if(document.swapNode){
        var oScript = document.createElement('SCRIPT');
        oScript.setAttribute('type', 'text/javascript');
        oScript.setAttribute('src', '');
        oScript.setAttribute('defer', 'true');
        oScript.onreadystatechange = function(){
            if(this.readyState == 'complete'){
                setTimeout(callbackFunction, 1);
            }
        };
        document.getElementsByTagName('HEAD')[0].appendChild(oScript);
    }else{
        oEvents.addHandler(window, 'load', callbackFunction);
    }
}

var oSizes = {
    getWindowWidth : function(){
        return document.documentElement.clientWidth || document.body.clientWidth;
    },
    
    getWindowHeight : function(){
        return document.documentElement.clientHeight || document.body.clientHeight;
    },

    getDocumentWidth : function(){
        return Math.max(this.getWindowWidth(), document.documentElement.scrollWidth || document.body.scrollWidth);
    },
    
    getDocumentHeight : function(){
        return Math.max(this.getWindowHeight(), document.documentElement.scrollHeight || document.body.scrollHeight);
    }
}


function cClient(){
    this.oTransport = null;
    this.checkInterval = null;
    this.callbackForData = null;

    this.getTransport = function(){
        this.oTransport = null;
        for(var i = 0; i < 3; i++){
            activeXName = (i == 1 ? 'Msxml2.XMLHTTP' : 'Microsoft.XMLHTTP');
            try{
                if(i == 0){
                    this.oTransport = new XMLHttpRequest();
                }else{
                    this.oTransport = new ActiveXObject(activeXName);
                }
            }catch(exception){
                this.oTransport = null;
            }
            if(this.oTransport != null){
                break;
            }
        }
    }

    // sData required only for POST request, format: a=value&b=value&...
    this.getContent = function(sMethod, sURL, sData){
        this.getTransport();
        if(this.oTransport != null){
            this.oTransport.open(sMethod, sURL, true);
            if(sMethod != 'POST' || typeof(sData) == 'undefined'){
                sData = null;
            }else if(sMethod == 'POST'){
                this.oTransport.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            }
            if(sMethod == 'GET' && !oBase.isWebKit && !oBase.isFF){
                this.oTransport.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');
            }
            this.checkInterval = setInterval(function(_oClient){return function(){_oClient.checkState()}}(this), 50);
            this.oTransport.send(sData);
        }else{
            alert('Невозможно сделать асинхронный запрос на сервер');
        }
    }

    this.checkState = function(){
        if(this.oTransport.readyState == 4){
            clearInterval(this.checkInterval);
            if(this.oTransport.status == 200){
                this.callbackForData(this.oTransport.responseText);
            }else{
                alert('Задан неверный адрес страницы (404) для получения данных асинхронным запросом');
            }
        }
    }

    this.getContentCallback = function(sURL, oCallback, sMethod, sData){
        if(typeof(oCallback) == 'function'){
            this.callbackForData = oCallback;
            if(typeof(sMethod) == 'undefined' || sMethod != 'POST'){
                sMethod = 'GET';
                this.getContent(sMethod, sURL);
            }else{
                if(!sData){
                    sData = '';
                }
                this.getContent(sMethod, sURL, sData);
            }
        }
    }

    this.submitFormCallback = function(oForm, oCallback){
        var sURL = oForm.attributes.action.value;
        if(sURL.indexOf('http') != 0){
            sURL = document.location.protocol + '//' + document.location.host + sURL;
        }
        
        var sParameters = '';
        for(i = 0; i < oForm.elements.length; i++){
            if(oForm.elements[i].type == 'checkbox' || oForm.elements[i].type == 'radio'){
                if(oForm.elements[i].checked){
                    sParameters += (sParameters == '' ? '' : '&') + encodeURIComponent(oForm.elements[i].name) + '=' + encodeURIComponent(oForm.elements[i].value);
                }
            }else if(oForm.elements[i].name && oForm.elements[i].name != ''){
                sParameters += (sParameters == '' ? '' : '&') + encodeURIComponent(oForm.elements[i].name) + '=' + encodeURIComponent(oForm.elements[i].value);
            }
        }

        if(oForm.attributes.method && oForm.attributes.method.value.toLowerCase() == 'post'){
            this.getContentCallback(sURL, oCallback, 'POST', sParameters);
        }else{
            this.getContentCallback(sURL + '?' + sParameters, oCallback);
        }
    }
}

function popupImages(idBlock, imagesClassName){
    this.bInitialized = false;
    this.imagesGroup = imagesClassName;
    
    this.oBlock = document.getElementById(idBlock + 'Container');
    this.oOverlay = document.getElementById(idBlock + 'Overlay');
    this.oLoading = document.getElementById(idBlock + 'Loading');
    this.oContent = document.getElementById(idBlock + 'Content');
    this.oControls = document.getElementById(idBlock + 'Controls');
    this.oPrevious = document.getElementById(idBlock + 'Previous');
    this.oNext = document.getElementById(idBlock + 'Next');
    this.oClose = document.getElementById(idBlock + 'Close');
    this.oImage = null;

    this.aImages = [];
    this.currentImageId = 0;
    this.hFadeInImageTimout = null;
    
    this.init = function(){
        if(this.oOverlay != null && this.oBlock != null && this.oContent != null){
            var oRegExpClassName = new RegExp('(^| )' + this.imagesGroup + '($| )', 'i');
            var oHref = document.getElementsByTagName('A');
            for(var i = 0; i < oHref.length; i++){
                if(oRegExpClassName.test(oHref[i].className)){
                    this.aImages[this.aImages.length] = oHref[i].href;
                    oEvents.addHandler(oHref[i], 'click', function(_this, _index){return function(evt){_this.show(evt, _index); return false;}}(this, this.aImages.length - 1));
                }
            }
        
            oEvents.addHandler(this.oOverlay, 'click', function(_this){return function(evt){_this.close(evt)}}(this));
            if(this.oControls != null){
                oEvents.addHandler(this.oBlock, 'mouseover', function(_this){return function(){_this.showControls();}}(this));
                oEvents.addHandler(this.oBlock, 'mouseout', function(_this){return function(){_this.hideControls();}}(this));
            }
            if(this.oPrevious != null){
                oEvents.addHandler(this.oPrevious, 'click', function(_this){return function(evt){_this.previous(evt); return false;}}(this));
            }
            if(this.oNext != null){
                oEvents.addHandler(this.oNext, 'click', function(_this){return function(evt){_this.next(evt); return false;}}(this));
            }
            if(this.oClose != null){
                oEvents.addHandler(this.oClose, 'click', function(_this){return function(evt){_this.close(evt); return false;}}(this));
            }
            
            this.bInitialized = true;
        }
    };

    this.showOverlay = function(){
        this.oOverlay.style.display = 'block';
    }

    this.hideOverlay = function(){
        this.oOverlay.style.display = 'none';
    }
    
    this.showBlock = function(bClearContent){
        if(this.oControls != null){
            this.hideControls();
        }
        this.oBlock.style.display = 'block';
        if(bClearContent){
            this.oContent.innerHTML = '';
        }
    }
    
    this.hideBlock = function(){
        this.oBlock.style.display = 'none';
    }
    
    this.setContentSize = function(iWidth, iHeight){
        this.oContent.style.width = iWidth + 'px';
        this.oContent.style.height = iHeight + 'px';

        var iBlockTop = Math.max(0, Math.floor((oSizes.getWindowHeight() - this.oBlock.offsetHeight) / 2));
        var iBlockLeft = Math.floor((oSizes.getWindowWidth() - this.oBlock.offsetWidth) / 2);
        
        if(iBlockLeft + this.oBlock.offsetWidth > oSizes.getWindowWidth()){
            iBlockLeft = Math.max(20, oSizes.getWindowWidth() - this.oBlock.offsetWidth - 20);
        }
        
        if(iBlockTop + this.oBlock.offsetHeight > oSizes.getWindowHeight()){
            iBlockTop = Math.max(20, oSizes.getWindowHeight() - this.oBlock.offsetHeight - 20);
        }
        
        this.oBlock.style.left = oPositions.getDocumentLeft() + iBlockLeft + 'px';
        this.oBlock.style.top = oPositions.getDocumentTop() + iBlockTop + 'px';
    }

    this.showLoader = function(){
        if(this.oImage != null){
            setOpacity(this.oImage, 0.3);
        }
        this.oLoading.style.display = 'block';
    }
    
    this.showControls = function(){
        this.oControls.style.display = 'block';
    }
    
    this.hideControls = function(){
        this.oControls.style.display = 'none';
    }
    
    this.load = function(imageId){
        clearTimeout(this.hFadeInImageTimout);
        
        this.oPrevious.className = imageId == 0 || this.imagesGroup.indexOf('Single') >= 0 ? 'popupImagePreviousInactive' : '';
        this.oNext.className = imageId == this.aImages.length - 1 || this.imagesGroup.indexOf('Single') >= 0 ? 'popupImageNextInactive' : '';
        
        this.oImage = new Image();
        this.oImage.onload = function(_this){return function(){_this.onImageLoaded()}}(this);
        this.oImage.setAttribute('imageIndex', imageId);
        this.oImage.src = this.aImages[imageId];
    }

    this.onImageLoaded = function(){
        if(this.oImage.getAttribute('imageIndex') == this.currentImageId){
            this.oLoading.style.display = 'none';
            
            this.fadeInImage(0);
            if(this.oImage.width > 0){
                this.setContentSize(this.oImage.width, this.oImage.height);
            }
            this.oContent.appendChild(this.oImage);
        }
    }

    this.fadeInImage = function(opacity){
        setOpacity(this.oImage, opacity);
        nextOpacity = Math.min(1, opacity + (document.swapNode ? 0.4 : 0.2));
        if(opacity < 1){
            this.hFadeInImageTimout = setTimeout(function(_this, _nextOpactiy){return function(){_this.fadeInImage(_nextOpactiy)}}(this, nextOpacity), 30);
        }else{
            var iNumberOfImages = this.oContent.getElementsByTagName('IMG').length;
            if(iNumberOfImages > 1){
                for(var i = 0; i < iNumberOfImages - 1; i++){
                    this.oContent.removeChild(this.oContent.firstChild);
                }
            }
        }
    }
    
    this.show = function(evt, iIndex){
        this.currentImageId = typeof(iIndex) == 'undefined' ? 0 : iIndex;
        if(this.bInitialized){
            this.showOverlay();
            this.showBlock(true);
            this.showLoader();
            this.setContentSize(300, 200);

            this.load(this.currentImageId);
            oEvents.stopProcessing(evt);
        }
    }

    this.previous = function(evt){
        if(this.currentImageId > 0 && this.imagesGroup.indexOf('Single') == -1){
            this.showLoader();
            this.load(-- this.currentImageId);
        }
        oEvents.stopProcessing(evt);
    }
    
    this.next = function(evt){
        if(this.currentImageId < this.aImages.length - 1 && this.imagesGroup.indexOf('Single') == -1){
            this.showLoader();
            this.load(++ this.currentImageId);
        }
        oEvents.stopProcessing(evt);
    }
    
    this.close = function(evt){
        this.hideBlock();
        this.hideOverlay();
        oEvents.stopProcessing(evt);
    }
    
    this.init();
}

onDomLoaded(function(){
    var aPopupImages = document.getElementsByClassName('popupImage');
    for(i = 0; i < aPopupImages.length; i++){
        if(aPopupImages[i].tagName == 'A'){
            if(document.getElementById('popupImageOverlay') == null){
                var oOverlay = document.createElement('DIV');
                oOverlay.id = 'popupImageOverlay';
                document.body.appendChild(oOverlay);
            }
            if(document.getElementById('popupImageContainer') == null){
                var oContainer = document.createElement('DIV');
                oContainer.id = 'popupImageContainer';
                oContainer.innerHTML = '\
                    <div id="popupImageLoading"></div>\
                    <div id="popupImageContent"></div>\
                    <div id="popupImageControls"><a href="/" id="popupImagePrevious"></a><a href="/" id="popupImageNext"></a><a href="/" id="popupImageClose"></a></div>\
                    <div class="popupImageL"></div><div class="popupImageT"></div><div class="popupImageR"></div><div class="popupImageB"></div><div class="popupImageLT"></div><div class="popupImageRT"></div><div class="popupImageLB"></div><div class="popupImageRB"></div>';
                document.body.appendChild(oContainer);
            }

            window.oPopupImagesHandler = new popupImages('popupImage', 'popupImage');
            break;
        }
    }
    
    var aForms = new Array('feedback', 'consultForm');
    for(i = 0; i < aForms.length; i++){
        if(document.forms[aForms[i]]){
            var oForm = document.forms[aForms[i]];
            var sessionId = getCookie('usid');
            if(sessionId != null){
                var isIE = typeof(document.swapNode) != 'undefined';
                var sessionField = document.createElement(isIE ? '<input name="form_session_id" type="text">' : 'input');
                sessionField.type = 'hidden';
                sessionField.name = 'form_session_id';
                sessionField.value = sessionId;
                oForm.appendChild(sessionField);
            }
        }
    }
});
