/************ OLD bgn ***************/

// функция добавляет html код окна в начало тега body
//onClick="ShowHide("'+sIdWindow+'",1)"
function iniWindow( sIdWindow, sClassWindow )
{
  var htmlWindow  =
  '<div id='+sIdWindow+' class='+sClassWindow+' style="display:none;/*не переносить в css, из-за эффектов*/">'+
    '<div class="'+sClassWindow+'_title">'+
      '<table><tr>'+
        '<td id='+sIdWindow+'_title style="width:100%"></td>'+
        '<td ><div class=cross onClick=ShowHide("'+sIdWindow+'",1) ></div></td>'+
      '</tr></table>'+
    '</div>'+
    '<div id='+sIdWindow+'_body class='+sClassWindow+'_body></div>'+
  '</div>';

  // lib prototype
  new Insertion.Top('ws', htmlWindow);
}

function iniProgressBar( sIdWindow, sClassWindow )
{
  var htmlWindow  =
  '<div id='+sIdWindow+' class='+sClassWindow+' style="display:none;/*не переносить в css, из-за эффектов*/">'+
    '<div class="'+sClassWindow+'_title">'+
      '<table><tr>'+
        '<td ><div class=loading></div></td>'+
        '<td id='+sIdWindow+'_title style="width:100%;text-align:center">Отправка данных...</td>'+
        '<td ><div class=cross onClick=ShowHide("'+sIdWindow+'",1) ></div></td>'+
      '</tr></table>'+
    '</div>'+
  '</div>';

  // lib prototype
  new Insertion.Top('ws', htmlWindow);
}

function setWindow( sIdWin, sTitleWin, sBodyWin )
{
  if(sTitleWin)
    $(sIdWin+'_title').innerHTML = sTitleWin;

  if(sBodyWin)
    $(sIdWin+'_body').innerHTML = sBodyWin;
}

// отображение слоя
function ShowHide( sIdEl, bHide )
{
  var oEl
  if (oEl = $(sIdEl) ) {

    if (!bHide) {
      new Effect.Appear(sIdEl, {duration:0.5});
      ElPos(oEl, 'c');
    }
    else {
      Element.hide(sIdEl);
    }
  }
}
/************ OLD end ***************/


/**************** SYS bgn  *******************/
/*
var base_ref = 'http://www.example.com';
var images = new Array();
var tmp_images = new Array();
tmp_images[0] = 'image1.jpg';
tmp_images[1] = 'image2.jpg';
tmp_images[2] = 'image3.jpg';
tmp_images[3] = 'image4.jpg';
tmp_images[4] = 'image5.jpg';

function cache_images () {
  for (var i=0; i < tmp_images.length; i++){
    var cacheimage=new Image();
    var tmp_name = tmp_images[i];
    var url = tmp_images[i] + '.png';
    cacheimage.src=url;
    images[tmp_name]=cacheimage;
  }
}
/**/

function getOffsetRect(elem) {
    // (1)
    var box = elem.getBoundingClientRect()

    // (2)
    var body = document.body
    var docElem = document.documentElement

    // (3)
    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft

    // (4)
    var clientTop = docElem.clientTop || body.clientTop || 0
    var clientLeft = docElem.clientLeft || body.clientLeft || 0

    // (5)
    var top  = box.top +  scrollTop - clientTop
    var left = box.left + scrollLeft - clientLeft

    return { top: Math.round(top), left: Math.round(left) }
}


/**
 * позиционирование элемента
 *
 * mEl - обьект или его id
 * sTypes - c,t,b,l,r,lt,lb,rt,rb
 * iXOff - конечное смещение по X
 * iYOff - конечное смещение по Y
 */
function ElPos( mEl, sTypes, iXOff, iYOff )
{
	if ("object" != typeof(mEl) && !(mEl = $(mEl)) )
    return;

  var x = y = l = 0
  if(!iXOff)
    iXOff =0
  if(!iYOff)
    iYOff =0

/*@todo fix для IE
  if (Prototype.Browser.IE) {
    var winWidth = document.documentElement.clientWidth
    var winHeight = document.documentElement.clientHeight
  }
  x = (winWidth-mEl.getWidth())/2
  y = (winHeight-mEl.getHeight())/2
*/      

  // centering element
  x = (document.documentElement.clientWidth-mEl.getWidth())/2
  y = (document.documentElement.clientHeight-mEl.getHeight())/2
  sTypes = sTypes.substr(0, 2)
  l = sTypes.length

  for (var i=0; i<l; i++) {
    switch (sTypes.substr(i, 1)) {
       case 'c':
         break;
       case 't':
           y = y-y
         break;
       case 'b':
           y = y+y
         break;
       case 'l':
           x = x-x
         break;
       case 'r':
           x = x+x
         break;
    }
  }

//  alert(x)
//  alert(y)

  mEl.style.left = x+iXOff+document.documentElement.scrollLeft+"px"
  mEl.style.top  = y+iYOff+document.documentElement.scrollTop+"px"
/*
  alert(mEl.style.left)
  alert(mEl.style.top)
/*
  alert(document.documentElement.scrollTop)
  alert(document.documentElement.scrollLeft)
  // debug
  <div id=test style='border:50px solid #000; width:100px; height:100px; position:absolute'></div>
  <script>ElPos( 'test' ,'r', -100 )</script>
*/
}

/**
 *
 * mDivs - строка id через зяпятую или массив с id элементов
 * 
 * @todo 
 * возвращаемый disabler сделать обьектом, а не массивом
 */
function Disabler(mEl, bEnable)
{
  if ("array" != typeof(mEl))
    mEl = new Array(mEl);

  for(var i=0, l=mEl.length; i<l; i++) {
    
    var oEl = $(mEl[i]);
    
    if (!oEl) {
      alert("Disabler: not found Element ["+oEl+"]")
      continue
    }

    if (!bEnable) {
      var top = getOffsetRect(oEl).top+"px";
      var left =getOffsetRect(oEl).left+"px";

      oEl.disabler = {}      

      oEl.disabler.mask = new Element('DIV').setStyle({
         zIndex:"1000"
        ,position:"absolute"
        ,left:left
        ,top:top
        ,width:oEl.getWidth()+"px"
        ,height:oEl.getHeight()+"px"
      })

      oEl.disabler.image = oEl.disabler.mask.cloneNode(true)

      oEl.disabler.mask.setStyle({
         left:left
        ,top:top

        // Editable
        ,backgroundColor:"#E0E0E0"
        ,opacity:.75
        ,filter:"alpha(opacity:75)"
      })

      oEl.disabler.image.setStyle({
         zIndex:"1001"
        ,backgroundRepeat:"no-repeat"

        // Editable
        ,backgroundImage:"url(./tpl/def/loader.gif)"
        ,backgroundPosition:"left"
      })

      document.body.appendChild(oEl.disabler.mask)
      document.body.appendChild(oEl.disabler.image)

      oEl.disabler.remove = function() {
        this.mask.remove()  
        this.image.remove()  
      }

      return oEl.disabler;        
    }

    else if(oEl.disabler)
      oEl.disabler.remove()  
  }
}

/**
 * возвращает текущий или переданный Location,
 * с примененным фильтром по переменным
 *
 * @param string sVarsFilter имена переменных через запятую
 * @param bool bFilterInverse переданные переменные вырезать
 * @return string
 */
function Location(sVarsFilter, bFilterInverse, sLocation )
{
  var iIndexEqual = i3 =0, aAllowVars = new Array()

  if (!sLocation)
    sLocation = window.location.toString()

  var iIndexQuery = sLocation.indexOf('?')
  if (-1 == iIndexQuery)
    return sLocation+"?"

  var sLocationAdress = sLocation.substr(0, iIndexQuery+1)
  var aQueryVars = sLocation.substr(iIndexQuery+1).split('&')

  var aVars = sVarsFilter.split(",");
  for (var i=0, l=aQueryVars.length; i<l; i++) {
    if((iIndexEqual = aQueryVars[i].indexOf('=')) && -1 != iIndexEqual)
      var sQueryVarName = aQueryVars[i].substr(0, iIndexEqual)
    else
      var sQueryVarName = aQueryVars[i]

    var bVarFind = false
    for (var i2=0, l2=aVars.length; i2<l2; i2++) {
      if (aVars[i2]==sQueryVarName)
        bVarFind = true
    }
    // 0110^1010 = 1100 XOR
    if (bFilterInverse^bVarFind) {
      aAllowVars[i3] = aQueryVars[i]
      i3++
    }
  }

  return sLocationAdress+aAllowVars.join('&');
}


/* ######### Cookie ############# */
var Cookie = {

  store : (function(){
    var allCookies = document.cookie.split ('; ');
    var values = new Array();
    for (var i=0, l=allCookies.length; i<l; i++) {
      var cookiesPair = allCookies[i].split('=');
      values[cookiesPair[0]] = unescape(cookiesPair[1]);
    }
    return values
  })(), 

  set : function(name,value,days) {
    if (days) {
      var date= new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = date.toGMTString();
    }
    else {
      var date= new Date();
      date.setTime(date.getTime()+(365*24*60*60*1000));//default to 1 year
      var expires = date.toGMTString();
    }
    document.cookie = name+"="+escape (value )+"; expires="+expires+";path=/";
  },

  get : function(name) {
    return this.store[name];
  },

  unset : function(name) {
    this.create(name,"",-1);
    this.store[name]=null;
  }
}

// глобальное хранилище
var GlobalScope = {
   // example
   Property: 'test'
  ,Property1: function(){
    //alert("GlobalScope.Property1 init");
    return {
       subProp1: 'test'
      ,subProp2: 'test'
    }
  }()
  ,Method: function(){
    alert("GlobalScope.Method()");
    return {
       prop1: 'test'
      ,prop2: 'test'
    }
  }

  // use
  ,bOrderAsWindow: false // перенести в Order
}
/**************** SYS end  *******************/


/**************** REFACTOR bgn  *******************/

// отображение окна заказа товара
function FirmWindow(iIdFirm, sNameFirm)
{
  //скрываем если открыто прежнее
  ShowHide ('window',1);

  setWindow(
    'window',

    'Информация',
    '<form id=form>'
    +'Продажу данного товара осуществит компания'
    +'<div class=w_fname>'+sNameFirm+"</div>"
    +'Минск, Республика Беларусь<br><br>'
    +'Вы можете установить просмотр товаров, только данной компании.'
    +'<div class=w_btn >'
    +' <input type=button class=w_btn value=установить onClick="setFirm('+iIdFirm+')">'
    +' <input type=button class=w_btn value=закрыть onClick="ShowHide(\'window\', 1)" >'
    +'</div>'
    +'</form>'
  );

  ShowHide ('window');
}

function setFirm(iIdFirm)
{
  window.location.href = Location("f,p", true)+"&f="+iIdFirm
}

function unsetFirm()
{
  window.location = Location("f,p", true)
}

/**
 * Сортировка
 * @param {} sField
 */function setOrder(sField)
{  // если поле не выбрано  var sURL = window.location.toString()
  var sParam = ""
  if (-1 == sURL.search('\\bsrtf='+sField+'\\b')){
    sURL = Location("srtf,srtr,p", true)
    sParam = "&srtf="+sField
  }
  else {
    if (-1 == sURL.search("\\bsrtr\\b") )
      sParam = '&srtr';
    else
      sURL = Location("srtr,p", true)
  }
  window.location.href = sURL+sParam;
}

function setSearch()
{
  //var sURL = LocationWithoutVars("r,u,ss,pss,p,srtf,srtr")+"&"+Form.serialize('search')
  var sURL = Location("f")+"&"+Form.serialize('search')
  //document.write(sURL) //debug
  window.location.href = sURL;
}


function sPriceHtml(sId, sType, sChecked, sVal,  sPriceType, sPrice)
{
  if(sPrice) {
    return ''
    +'<div>'
    +' <input id='+sId+' type='+sType+' '+sChecked+' value='+sVal+' name="">'
    +' <p><strong>'+sPriceType+':</strong>'+sPrice+'</p>'
    +'</div>'
  }
  return "";
}
function sPriceBlock(sPrice, sPriceRetail)
{
  var sTP = sTPR = 'hidden';
  var sCP = sCPR = '';

  if (sPrice)
    sTP = 'radio'
  if (sPriceRetail)
    sTPR = 'radio'

  if (sPrice)
    sCP = 'checked'
  else if (sPriceRetail && !sPrice)
    sCPR = 'checked'

  return sPriceHtml('bPrice', sTP, sCP, 1, 'Оптовая', sPrice ) + sPriceHtml('bPriceRetail', sTPR, sCPR, 2, 'Розничная', sPriceRetail );
}
// получить тип выбраной цены
function iGetSelectPriceType()
{
  if ( $('bPrice') && ($('bPrice').checked || !$('bPriceRetail')) )
    return 1; // 1 - опт

  if ( $('bPriceRetail') && ($('bPriceRetail').checked || !$('bPrice')) )
    return 2;  // 2 - розница
    
  return 0;  // 0 - без цены    
}
/**************** REFACTOR end  *******************/


   
/**************** EXT bgn  *******************/
function OrderWindowExt(id, name, price, priceRetail) {
  var params = {
     i:id
    ,n:name
    ,p1:price
    ,p2:priceRetail
    ,psi:Cookie.get('PHPSESSID')
  }

  var props = new Array(
     'width=272'
    ,'height=590'
    ,'left='+(document.documentElement.clientWidth-(265+160))
    ,'top=250'
    ,'resizable=1'
  )
  WindowOpen('order', props, params );
}

function BasketWindowExt() {

  var params = {
    psi:Cookie.get('PHPSESSID')
  }

  var props = new Array(
     'width=720'
    ,'height=400'
    ,'left='+(document.documentElement.clientWidth/2-360)
    ,'top=250'
    ,'resizable=1'
    ,'scrollbars=1'    
  )
  WindowOpen('basket', props, params );      
}

var win; // должна быть глобальной
function WindowOpen(id, props, params) {

  win = window.open('', id, props.join(','))

  // всегда принудительный replace
  // из-за различного поведения window.open в браузерах
  win.location.replace('about:blank')

  if (Prototype.Browser.IE)
    ChangePopUpContent($H(params).toQueryString())
  else
    window.setTimeout ('ChangePopUpContent("'+$H(params).toQueryString()+'")', 100)
}
function ChangePopUpContent(params) {
  // flash вместо gif, т.к. gif останавливает анимацию при смене location
  win.document.write('<embed height="100%" width="100%" wmode="transparent" quality="best" src="tpl/def/loader.swf" type="application/x-shockwave-flash" />')
  win.location.replace('http://srv/order/front.php?'+params);    
  win.focus();
}
/*
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");

// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");

var hiddenField = document.createElement("input");              
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);

window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');

form.submit();
*/
/**************** EXT end  *******************/

/* ######### GATE ############# */

/**
 * 
 * @param {} options 
 * {
 *    url:''
 *   ,params:{}
 *   ,onSuccess:function(info, oData){}
 *   ,onFailure:function(info, oData){}
 *   ,loader:   
 * }
 * 
 * @param {} scope 
 * 
 */
Gate = function(options, scope) {
  // ini options
  options.url = options.url || "/"
  options.params = options.params || {}
  options.onSuccess = options.onSuccess || function(){} 
  options.onFailure = options.onFailure || function(){}
  scope = scope || this
/*
  if(options.loaderTarget)
    Disabler(options.loaderTarget);
*/    
  new Ajax.Request (options.url, {
     method:'post'
    ,parameters:options.params 
    ,evalJSON:'force'
    ,onSuccess:function(result){

      // ini 
      var success, info, data, handler;

      if (null != result.responseJSON){
        success = (result.responseJSON.success != undefined ? result.responseJSON.success : false)
        info = (result.responseJSON.info != undefined ? result.responseJSON.info : "")
        data = (result.responseJSON.data != undefined ? result.responseJSON.data : {})
      }
      else {
        success = false
        info = ""
        data = {}
      }
      
      if (success)
        handler = options.onSuccess
      else
        handler = options.onFailure

      handler.call(scope, info, data)

    }

    ,onFailure:function(result) {
      alert('Gate: onFailure')
    }
    
    // Not guaranteed
    ,onLoaded:function(result) {
      if (options.loader)
        options.loader.remove()
    }
    
//    ,onComplete:function(oResp) {
//      if(options.maskTarget)
//        Disabler(options.maskTarget, true);
//    }
    
  });
}

/* ######### ORDER ############# */
var oOrder = {
    
   store:[]

  ,phone:""
  ,name:""
  ,note:""
  ,captcha:""
   
  ,window:null
  ,urlHandler:'order.php?'
  ,urlCaptcha:'libs/kcaptcha/?'
  
  ,Init : function() {

  }

  ,toOrder : function(orderUnit, reset) {

    if (reset)
      this.store = []

    this.store.push(orderUnit)
  }
  
  ,setOrderData : function(id, name, price, priceRetail) {

    this.toOrder(
       new OrderUnit(id, 1, (price ? 1:priceRetail ? 2:0))
      ,true
    )

    // set order data
    $('o_name').innerHTML = name;
    $('o_price').innerHTML = sPriceBlock(price, priceRetail);
  }
  
  ,Show : function(id, name, price, priceRetail) {
  
    this.setOrderData(id, name, price, priceRetail)
    
    GlobalScope.bOrderAsWindow = true //перенести в проперти обьекта Order

    this.Expand()
    
    ElPos('o_bar', 'r', -150, -25)
  
    new Draggable('o_bar', {handle:'o_title1'})
    $('o_title1').setStyle({cursor:'move'})

    $('o_bar').setStyle({display:'block'})
  }

	,Hide : function () {
		if (!$('o_bar'))
			return

	  if (GlobalScope.bOrderAsWindow)
	    $('o_bar').style.display= "none";
	  else
	    $('o_info').style.display= "none";

	  $('o_close').setStyle({display:"none"})
	}

  
  ,Execute1 : function(loaderTarget) {
    
    oOrder.store[0].q = $F('quan')
    oOrder.store[0].pt = iGetSelectPriceType()

    oOrder.phone = $('phone1').value
    oOrder.captcha = $('captcha1').value
    oOrder.name = $('name1').value
    oOrder.note = $('note1').value

    this.Execute(loaderTarget)
  }
  
  ,Execute : function(loaderTarget, extSucc, extFail, scope ) {

    if (!this.phone || !this.captcha)
      return ShowMsg('Заполните все необходимые поля')
      
    extSucc = extSucc || function (){
      // это вроде можно в oOrder.Reset()  
      $('note1').value=""
      this.Hide()

      // сброс корзины
      //oBasket.Reset()
    }
    extFail = extFail || function (){
      this.ReloadCaptcha(true)
    }
    
    scope = scope || this
    
    var params = Object.clone(this)
    delete params.window

    Gate({
       url:this.urlHandler
      ,params:{o:Object.toJSON(params)}
      ,onSuccess:function(info, data){
        extSucc.call(scope)
        alert(info)
      }
      ,onFailure:function(info, data){
        extFail.call(scope)
        alert(info)
      }
      ,loader: (loaderTarget ? Disabler(loaderTarget) : false)
    },this)
  }
  
   // раскрывает окно(слой) заказа
  ,Expand : function () {
    if ("block" != $('o_info').getStyle('display'))
      $('o_info').setStyle({display:"block"})

    this.ReloadCaptcha()

    $('o_close').setStyle({display:"block"})
  }
  
  ,ReloadCaptcha : function (forced) {
    if (forced || !$('captchaImg1').src) {
      // рандом для выключения кэширования
      $('captchaImg1').src=this.urlCaptcha+"&"+Math.random() 
      $('captcha1').value=""
    }
  }
  
}

var OrderUnit = function(id, quantity, priceType) {
  return {
     u:id
    ,q:quantity
    ,pt:priceType
  }
}


/* ######### BASKET ############# */
/**
 * 
 */
var oBasket = {
   
   store:[]
       
  ,window:null
  ,urlHandler:'basket.php?'
  ,urlCaptcha:'libs/kcaptcha/?'
       
  ,Init : function() {
    // basket window 
    this.window = new Window({
       maximizable:false
      ,minimizable:false
      ,resizable:false
      ,draggable:false
      ,hideEffect:Element.hide
      ,showEffect:Element.show
      ,className:"alphacube"
      //,destroyOnClose: true
      ,title:'Корзина'
    })

    this.window.setContent('sfBasketD', true, true)
    $('sfBasketD').style.display = 'block';
  }

  ,Show : function(loaderTarget) {
    Gate({
       url:this.urlHandler
      ,onSuccess:function(info, data){
        this.PreProcessStore(data)
        //this.Render()
        this.BuildContent()
        this.window.showCenter(true, 110)
        this.UpdateWindowSize(false, true)        
        this.ReloadCaptcha(true)
        this.UpdateQuantity()
      }
      ,loader:(loaderTarget ? Disabler(loaderTarget) : false)      
    },this)    
  }

  ,toBasket : function(id, loaderTarget) {
    Gate({
       url:this.urlHandler+'&b_add'
      ,params:{u:id}
      ,onSuccess:function(info, data){
        this.UpdateQuantity(data)
        alert(info)
      }
      ,loader:(loaderTarget ? Disabler(loaderTarget) : false)
    },this)    
  }

  ,Recount : function(loaderTarget) {
    
    this.store = this.store.reject(function(unit){
      return unit.deleted
    })

    Gate({
       url:this.urlHandler+'&b_upd'
      ,params:{b:Object.toJSON(this.store)}
      ,onSuccess:function(info, data){
//        this.Render()
        this.BuildContent()
        //this.window.setSize(this.window.width, this.window.content.firstChild.scrollHeight, true);
        this.UpdateWindowSize(false, true)
        this.UpdateQuantity()
      }
      ,loader:(loaderTarget ? Disabler(loaderTarget) : false)
    }, this)
  }
  
  /**
   * это наверное стоит вынести из метода в отдельную функу
   * которая обьеденяет в себе работу с обьектами
   * так как методы должны использовать this а не глоб. объекты 
   * @param {} loaderTarget
   */
  ,OrderExecute : function(loaderTarget) {

    // формируем заказ из корзины

    oOrder.store = [] // clear

    this.store.each(function(unit){
      oOrder.toOrder(new OrderUnit(unit.id, unit.quantity, unit.priceType))
    })

    oOrder.phone = $('phone2').value
    oOrder.captcha = $('captcha2').value
    oOrder.name = $('name2').value
    oOrder.note = $('note2').value

    oOrder.Execute(loaderTarget
      ,function(){
        this.window.close()
        // сброс корзины
        this.Reset()
        // поидее можно засунуть в oBasket.Reset 
        $('note2').value=""
      }
      ,function(){
        this.ReloadCaptcha(true)
      }
      ,this
    )
  }
  
  ,PreProcessStore : function(data) {
    // BasketUnit связываем данные с методами
    for (var i=0, l=data.length; i<l; i++)
      this.store[i] = Object.extend(new BasketUnit(), data[i]);
  }
  
  ,BuildContent : function() {
    
    var sRows="", c=0
    
    if (this.store.length) {
      
      this.store.each(function(unit, i) {
        c++;
        sRows += ''
          +'<tr class='+(c%2 ? 'even' : 'odd')+'>'
            +'<td class=num>'+c+'</td>'
            +'<td class=name>'+unit.name+'</td>'
            +'<td class=prices>'+unit.HtmlPrices(i)+'</td>'
            +'<td class=quantity>'+unit.HtmlQuantity(i)+'</td>'
            +'<td class=del>'+unit.HtmlDelete(i)+'</td>'
          +'</tr>'
      }, this)

      $('sfBasketT').select('tbody')[0].replace(sRows)
    }
    
    if (sRows) {    
      // sfBasketC - content, sfBasketE - empty  
      $('sfBasketE').style.display = 'none'
      $('sfBasketC').style.display = ''
    }
    else {
      $('sfBasketE').style.display = ''
      $('sfBasketC').style.display = 'none'
    }
  }
  

  ,UpdateQuantity : function(quantity) {
    if ($('bgc'))
      $('bgc').innerHTML = (null==quantity ? this.store.length : quantity)
  }
  
  ,Reset : function() {
    this.store = []
    this.UpdateQuantity()
  }
  
  ,ReloadCaptcha : function (forced) {
    if (forced || !$('captchaImg2').src) {
      // рандом для выключения кэширования
      $('captchaImg2').src=this.urlCaptcha+"&"+Math.random() 
      $('captcha2').value=""
    }
  }
  
  ,UpdateWindowSize : function (recalcWidth, recalcHeight) {
    var width = (undefined == recalcWidth
      ? this.window.width
      : this.window.content.firstChild.scrollWidth
    )
    var height = (undefined == recalcHeight
      ? this.window.height
      : this.window.content.firstChild.scrollHeight
    )
    
    this.window.setSize(width, height, true);  
  }
};

var BasketUnit = function() {
  return {
  	 id:null
  	,code:null
  	,name:null
  	,ad:null

  	,price:null 
  	,idCurrencyPrice:null
  	,fullPrice:null

  	,priceRetail:null
  	,idCurrencyPriceRetail:null  
  	,fullPriceRetail:null

  	,priceType:null
  	,quantity:null

    ,deleted:null

  	,HtmlPrices:function(i) {

      var html = '', chk;

      if (this.fullPrice) {

        chk = (1 == this.priceType ? 'checked' : "")

        html += '<input type=radio '+chk+' name=pt'+i+' onChange="oBasket.store['+i+'].priceType = 1">'
        +this.fullPrice
      }

      if (this.fullPrice && this.fullPriceRetail)
        html += '<br>'

      if (this.fullPriceRetail) {

        chk = (2 == this.priceType ? 'checked' : "")
        
        html += '<input type=radio '+chk+' name=pt'+i+' onChange="oBasket.store['+i+'].priceType = 2">'
        +this.fullPriceRetail
      }
        
      return html        
  	}
    ,HtmlQuantity:function(i) {
      return '' 
        +'<input type=text value='+this.quantity+' onChange="oBasket.store['+i+'].quantity = this.value">'
    }
    ,HtmlDelete:function(i) {
      return '' 
        +'<input type=checkbox onChange="oBasket.store['+i+'].deleted = this.checked">'
    }
/*    
    //oBasket.store[125].setPriceType(1)
     
    ,setPriceType : function(iPriceType){
    }
    ,setQuantity : function(iQuantity){
    }
    ,setDeleted : function(bDeleted){
    }
*/
  }
}

function ShowMsg(msg) {
  alert(msg)
}

document.observe("dom:loaded", function() {
  oBasket.Init()
  //oOrder.Init()  
});
		

