/*******************************************************************************
*                  НАЧАЛЬНЫЕ УСТАНОВКИ ИНДИКАТОРА КОРЗИНЫ                      *
*******************************************************************************/

var cart_id = ""; // id области в которую будет встроена корзина.
                   // Если нет, корзина формируется скритом и м.б. перемещаемой
var dragbar = "dragbox"; // id области захвата перемещаемой области.
                   // Если нет, функции перемещения в конце скрипта можно убрать

// Настройка корзины, если нет cart_id
function setCart() {
   this.width      = 120; // ширина индикатора
   this.height     = 71;  // высота индикатора
   this.left       = 103; // положение относительно левого края
   this.top        = 5;   // положение относительно верхнего края
   this.background = '#f0f8ff'; // цвет фона корзины
   this.css        = '/css/esm.css'; // файл с css корзины (если необходим)
   return this; 

} // End function setCart

// скрипт корзины (со списком товаров)
//var cart_script = '/cgi-bin/esm/cart.pl';
var cart_script = '/esm/';
var cart_script_popup = 0; // открывать в PopUp-окне 

// путь к скрипту добавления товара (индикатор корзины)
var add_to_cart_script = '/cgi-bin/esm/add_to_cart.pl'; 


/*******************************************************************************
*                    ДИНАМИЧЕСКОЕ ОТОБРАЖЕНИЕ КОРЗИНЫ                          *
*******************************************************************************/

var bwc = new esmBrowseCheck(); 
document.cookie = " check_esm=on; path=/";
// Конструктор индикатора
var esmDiv;
if( bwc.ok ) { 
   
   if( cart_id != "" ) {
      esmDiv = document.getElementById( cart_id );
   } else {
      cart = new setCart();
      if( cart.css ) {
         var esmCSS = document.createElement( "link" ); 
         esmCSS.type = 'text/css';
         esmCSS.rel  = 'StyleSheet';
         esmCSS.href = cart.css;
         document.body.appendChild( esmCSS );
         
      } // End if   
      esmDiv = document.createElement( "div" );
      esmDiv.style.width           = cart.width + 'px';
      esmDiv.style.height          = cart.height + 'px';
      esmDiv.style.left            = cart.left + 'px';
      esmDiv.style.top             = cart.top + 'px';   
      esmDiv.style.position        = 'absolute';
      esmDiv.style.visibility      = 'hidden';
      esmDiv.style.zIndex          = '999';
      esmDiv.style.backgroundColor = cart.background;
      document.body.appendChild( esmDiv );              
   
   } // End if
   
} // End if

if( bwc.ok ) { 
   
   loadCart(); 
   
   if( cart_id == "" ) {
   
      esmPosition(); 
      onresize = esmPosition; 
   
   } // End if


} // End if


// Определяем тип браузера
function esmBrowseCheck() {
   this.ver     = navigator.appVersion;
   this.agent   = navigator.userAgent;
   this.dom     = document.getElementById ? 1 : 0;
   
   this.opera5 = ( window.opera && this.dom ) ? 1 : 0; 
   this.opera6 = ( this.opera5 && window.print ) ? 1 : 0; 
   this.opera7 = ( this.opera5 && document.readyState ) ? 1 : 0;
   
   this.opera =  this.opera5;
    
   this.firefox = ( this.agent.indexOf( "Firefox" ) > -1 ) ? 1 : 0;
   this.ie5     = ( this.ver.indexOf( "MSIE" ) > -1 && this.dom && !this.opera5 ) ? 1 : 0;
   this.ie4     = ( document.all && !this.dom && !this.opera5 ) ? 1 : 0;
   
   this.ie      = this.ie4 || this.ie5;
   this.ns6     = ( this.dom && parseInt( this.ver ) >= 5 ) ? 1 : 0;
   this.ns4     = ( document.layers && !this.dom ) ? 1 : 0;
   this.safari  = ( this.ver.indexOf( "Safari" ) > -1 ) ? 1 : 0;
   this.ok      = this.ie || this.opera || this.firefox || this.safari;
   return this; 

} // End function esmBrowseCheck


function setCid( cid ) { 
   if( cid ) document.cookie = " esm_cid=" + escape( cid ) + "; path=/";
} // End function setСid


// Первая загрузка корзины
function loadCart() { 
   getFile( add_to_cart_script + "?" + parseInt( ( Math.random() * 1000000 + 1 ) ) ); 
} // End function loadCart


function getFile( filename ) {
   var obj = get_http_obj();
   if( obj ){
      obj.open( "GET", filename, true );
      obj.onreadystatechange = function(){
         if( obj.readyState== 4 && obj.responseText ) {
            var re = /(\d)cid=/;
            if( re.test( obj.responseText ) ) {
               var is_visible = RegExp.$1;  
               esmDiv.innerHTML = obj.responseText.substr( 35 );
               
               var element = document.createElement( "script" );
               element.text = 'setCid(\'' + obj.responseText.substr( 5, 30 ) + '\');';
               
               if( is_visible != '0' && cart_id == "" ) {
                  element.text += 'esmDiv.style.visibility = "visible"';
                  if( dragbar ) {
                  
                     // ИНИЦИАЛИЗАЦИЯ ПЕРЕТАСКИВАНИЯ КОРЗИНЫ
                     document.getElementById( dragbar ).onmousedown = initializedrag;
                     document.getElementById( dragbar ).style.cursor = 'pointer';
                     
                  } // End if  
                                  
               } else if( cart_id == "" ) {
                  element.text += 'esmDiv.style.visibility = "hidden"';
               } // End if
               
               
               esmDiv.appendChild( element );
               
            } else {
               alert ( 'Ошибка при отображении корзины' );
               return false;
               
            } // End if
            
         } // End if
         
      } // End function
      
      obj.send( null )
      return true;
     
   } else {
      return false;
   } // End if
   
} // End function getFile


function get_http_obj() {
   var obj = null;
   try{
      obj = new ActiveXObject( "Msxml2.XMLHTTP" ); 
   } catch( err ){
      try{
         obj = new ActiveXObject( "Microsoft.XMLHTTP" ); 
      } catch( err ){
         obj = null;
      } // End try
      
   } // End try
         
   if( !obj && typeof XMLHttpRequest != "undefined" ) {
      obj = new XMLHttpRequest(); 
   } // End if
   return obj;
   
} // End function get_http_obj


// Добавление в корзину
function toCart( goods_id, quantity ) {
   var check_esm = "";
    
   var re = new RegExp( "check_esm=([^;]*);" );
   if( re.exec( document.cookie + ";" ) ) { check_esm = RegExp.$1; }
    
   if( !( bwc.ok && check_esm == "on" ) || 
       !getFile( add_to_cart_script + "?" + parseInt( ( Math.random() * 1000000 + 1 ) ) + 
                                      "&quantity=" + quantity + "&goods_id=" + goods_id ) 
     ) orderGoods( goods_id, quantity );
   
} // End function toCart


// Открытие списка заказанных товаров
function orderGoods( goods_id, quantity ) { 
   var page = new bwSize(); 
   
   if( cart_script_popup ) {
      
      var property = "left=50px,top=" + ( bwc.opera ? 30 : 103 ) + "px,width=" + ( page.w - 100 ) +
                     ",height=" + ( page.sh - 205 ) + 
                     ",toolbar=0,menubar=0,scrollbars=1,resizable=0"
      var order_url = cart_script;
      if( goods_id && quantity ) order_url += "?quantity=" + quantity + 
                                              "&goods_id=" + goods_id;
      esm_win = window.open( order_url, "esm_" + parseInt( Math.random() * 1000000 ), property ); 
         
   } else {
      
      if( goods_id && quantity ) cart_script += "?quantity=" + quantity + 
                                                "&goods_id=" + goods_id;
      window.location =  cart_script;
      
   } // End if
   
} // End function orderGoods


// Разрешение экрана и размер окна браузера
function bwSize() {
   this.w = ( bwc.ok ) ? document.body.offsetWidth : innerWidth; 
   this.h = ( bwc.ok ) ? document.body.offsetHeight : innerHeight;
   
   if( self.screen ) { 
       this.sw = screen.width; 
       this.sh = screen.height; 
    
   } else if( self.java ) { 
       jkit = java.awt.Toolkit.getDefaultToolkit(); 
       scrsize = jkit.getScreenSize(); 
       this.sw = scrsize.width; 
       this.sh = scrsize.height; 
    
   }  // End if
             
   return this;
   
} // End function bwSize

////////////////////////////////////////////////////////////////////////////////
// ВСЁ НИЖЕСЛЕДУЮЩЕЕ МОЖНО УБРАТЬ, ЕСЛИ ЗАДАНА ПЕРЕМЕННАЯ cart_id

// Позиционирование индикатора
function esmPosition() { 
    esmDiv.style.left = cart.left + document.body.scrollLeft; 
    esmDiv.style.top  = cart.top + document.body.scrollTop; 
     
} // End function esmPosition


/*******************************************************************************
*                          ПЕРЕМЕЩЕНИЕ КОРЗИНЫ                                 *
*******************************************************************************/

if( bwc.ok && cart_id == "" ) { 
   initMove();
   window.onload = initMove;
} // End if

function drag_drop( e ){
   if( bwc.ok && dragapproved ){
      
      var evt = window.event ? window.event : e;

      new_y = tempy + evt.clientY - offsety;
      if( document.body.offsetHeight + document.body.scrollTop - cart.height < new_y ) { 
         crossobj.style.top = document.body.offsetHeight + document.body.scrollTop - cart.height + 'px';
      } else if( new_y < document.body.scrollTop ) {
         crossobj.style.top = document.body.scrollTop + 'px';
      } else {
         crossobj.style.top = new_y + 'px';
      } // End if
      
      new_x = tempx + evt.clientX - offsetx;
      if( document.body.offsetWidth + document.body.scrollLeft - cart.width < new_x ) { 
         crossobj.style.left = document.body.offsetWidth + document.body.scrollLeft - cart.width + 'px';
      } else if( new_x < document.body.scrollLeft ) {
         crossobj.style.left = document.body.scrollLeft + 'px';
      } else {
         crossobj.style.left = new_x + 'px';
      } // End if
      
      topOffset = crossobj.style.top - document.body.scrollTop;
      return false;
      
   } // End if
   
} // End function drag_drop


function initializedrag( e ) {
   if( bwc.ok && crossobj ) {
   
      var evt = window.event ? window.event : e;

      offsetx = evt.clientX;
      offsety = evt.clientY;
      
      tempx = parseInt( crossobj.style.left );
      tempy = parseInt( crossobj.style.top );
      
      dragapproved = true;
      document.onmousemove = drag_drop;

      
   } // End if
   
   return false;
   
} // End function initializedrag


var shiftMinimize = 0;
var topOffset     = 0;


function initMove() {
   crossobj = esmDiv;
   crossobj.onmouseup = new Function( "dragapproved=false" );

   topOffset = crossobj.style.top - document.body.scrollTop;
   setInterval( "doMove()", 30 );
   
} // End function initMove


function doMove() {
   var shiftPage = document.body.scrollTop;
   if( shiftPage != shiftMinimize ) {
      dif = ( shiftPage - shiftMinimize ) >> 2;
      if( dif ) shiftMinimize += dif; 
      else shiftMinimize = shiftPage;
      crossobj.style.top = shiftMinimize + topOffset;
      
   } // End if

} // End function doMove

