alertSave = alert;
var isfuter=false;

if($.browser.msie && parseInt($.browser.version) >= 6)
  isfuter='msie';
else if($.browser.mozilla && parseInt($.browser.version)>=parseInt('1.5'))
  isfuter='mozilla'; 
else if($.browser.opera && parseInt($.browser.version)>=9)
  isfuter='opera';

//isfuter=false;
//alert(isfuter);
errorAjaxString = 'Произошла ошибка!\nДанные не обновлены\nПопробуйте позже, возможно это произошло из-за проблемы со связью.';
/*
if(isfuter) {
    function alert(msg) {
        if(msg.indexOf('\n') > -1){
            msg = msg.replace(/\n/g,'<br />');
        }
        $('#alert').find('div.jqmAlertContent').html(msg); 
        $('#alert').modal({close: false, overlayId: 'modalOverlay', containerId: 'ajaxcont', onShow : setModalHider})
    }
}
*/
function showModalTxt(msg) {

    if ( !isfuter ) {

        if(msg.indexOf('\n') > -1){

            msg = msg.replace(/<b>/g,'');
            msg = msg.replace(/<\/b>/g,'');
        }
        alert(msg);

    } else {

        if(msg.indexOf('\n') > -1){
            msg = msg.replace(/\n/g,'<br />');
        }

        $('#alert').find('div.jqmAlertContent').html(msg); 
        $('#alert').modal({close: false, overlayId: 'modalOverlay', containerId: 'ajaxcont', onShow : setModalHider})
    }
}

function initTooltip() {
  $('.ttip').tooltip({delay: 500, track: true, showURL: false});
  $('.ttip2').tooltip({delay: 500, track: true, showURL: false, extraClass: "ttip_"});
}

$(function(){
  if(!isfuter) return false;
  initTooltip();
});

function rand(a,b){
  return a+(b-a)*Math.random();
}

function popUP(mypage, myname, w, h, scroll, titlebar) {
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    var winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable';
    var win = window.open(mypage, myname, winprops);
    if (parseInt(navigator.appVersion) >= 4) {
        win.window.focus();
    }
}

function checkConfirm() {
 var retrn=true;
 $('div[id*=quality]').each(
  function(){
   if($(this).text().indexOf('недостаточн') >- 1) {
    var $msg = 'Качество файла недостаточно для печати.\nНеобходимо загрузить изображение более высокого качества или выбрать формат меньшего размера.\n\n<b>Удалить снимок</b>\n\nСнимок можно удалить из корзины товаров, нажав Удалить. ВНИМАНИЕ! Для повторного использования снимки необходимо будет загружать заново. Разумеется, снимок удаляется только из корзины товаров, а не оригинальный файл на Вашем жестком диске.\n\n<b>Скопировать снимок</b>\n\nМожно скопировать уже загруженный снимок, нажав Копировать, чтобы было можно дополнительно напечатать его в другом формате. Таким образом не обязательно загружать снимок второй раз.\n\n<b>Выбрать количество</b>\n\nКаждый снимок одного формата можно заказывать до 10 раз. Просто используйте для этого выпадающее меню. Заказ на большее количество экземпляров мы охотно выполним по запросу.';

    showModalTxt($msg);

    retrn=false;
   }
  });
 return retrn;
}

function userLogin() {

    $lf = $document.getElementById('login_form');
    $lf.submit();
    return false;
}

function ajaxPopup2(url,type){

  $('#ajaxcont').attr('class','jqmWindow').html('<div style="text-align:center;"><span class="darkgrey_text"><b>Загрузка...</b></span><br /><img src="/images/loadingAnimation.gif" border="0" width="220" height="19" alt="Загрузка..." align="absmiddle" />');
  var typeset='jqmWindow';
  if(type=='zoom')
    typeset='jqmZoom';
  if(type=='help')
    typeset='jqmHelp';
  $('#ajaxcont').jqm().jqmShow();
  $.get(url,function(data){$('#ajaxcont').attr('class',typeset).html(data);});
}

$.stopModalAction = true;
function setModalHider() {
  $('#modalOverlay').click( function () { $.stopModalAction = true; $.modal.close();} );
}

var modalConfig = {close: false, overlayId: 'modalOverlay', containerId: 'ajaxcont', onShow : setModalHider};

function ajaxPopup(url, type) {

    if ( type == 'help' && false ) {

        $.stopModalAction = false;
        $('#ajaxcont').attr('class','jqmWindow').html('<div style="text-align:center;"><span class="darkgrey_text"><b>Загрузка...</b></span><br /><img src="/images/loadingAnimation.gif" border="0" width="220" height="19" alt="Загрузка..." align="absmiddle" />').modal(modalConfig);
        var typeset = 'jqmWindow';
        if(type == 'zoom')
            typeset = 'jqmZoom';
        if(type == 'help')
            typeset = 'jqmHelp';
        $.get(url, function(data) {
            if(!$.stopModalAction) {
                $.modal.close();
                $('#ajaxcont').attr('class', typeset).html(data).modal(modalConfig);
            }
        });
    }
    else {

        popUP(url, 'popUp'+type, 430, 490, true, false);
    }
}

function setSubPrint(id,set) {
  $('#printsubtype'+id).children().each(function(w) {
    if(this.value==set) {
      this.selected=true;

      PostList.getItem(id).submit();
      return true;
    }
  });
}

function showLayer(pic,ol){
  document.bigpic.src='/gallery/big/' + pic;
  document.getElementById("orderlink").href = ol;
  if(document.getElementById("popdiv").style.display == 'block') {
    document.getElementById("popdiv").style.display = 'none'
  } else {
    document.getElementById("popdiv").style.display = 'block'
  }
}

function PosterCalc(type, wfield, hfield) {
  this.usedLimit = null;
  if(typeof(this.printtype[type]) != 'undefined' && this.printtype[type] != -1) {
    this.usedLimit = this.printLimit[ this.printtype[type] ];
  }
  this.wfield = wfield;
  this.hfield = hfield;
  this.type = type;
  this.isCorrect = false;
  this.errorMessage = false;
}

PosterCalc.prototype.printLimit = [
{'minH':30, 'maxH':150, 'minW':30, 'maxW':300}, 
{'minH':80, 'maxH':1500, 'minW':80, 'maxW':3000}, 
{'minH':30, 'maxH':1000, 'minW':30, 'maxW':2000}];
//key=printtype, value=limit type
PosterCalc.prototype.printtype = [0, 0, -1, 1, 2, 0];
PosterCalc.prototype.errorColor  = '#FF0000';
PosterCalc.prototype.normalColor = '#00020F';
PosterCalc.prototype.calcData = [
  [{'limit' : 0, 'point':10}, {'limit' : 5000, 'point':14}, {'limit' : 10000, 'point':12}],
  [{'limit' : 0, 'point':21}, {'limit' : 5000, 'point':29}, {'limit' : 10000, 'point':25}],
  -1,
  [{'limit' : 0, 'point':3.5}, {'limit' : 60000, 'point':4.5}, {'limit' : 180000, 'point':3.8}],
  [{'limit' : 0, 'point':14}, {'limit' : 10000, 'point':18}, {'limit' : 60000, 'point':16}],
  [{'limit' : 0, 'point':13}, {'limit' : 5000, 'point':17}, {'limit' : 10000, 'point':15}],
  -1
];
PosterCalc.prototype.Messages = new Object();
PosterCalc.prototype.Messages['maxWidthError']  = 'Внимание! Длина не может быть больше #val# cm!'; 
PosterCalc.prototype.Messages['minWidthError']  = 'Внимание! Длина должна быть больше #val# cm!';
PosterCalc.prototype.Messages['intWeightError'] = 'Внимание! Длина может быть только целым числом!';
PosterCalc.prototype.Messages['maxHeightError'] = 'Внимание! Ширина не может быть больше #val# cm!';
PosterCalc.prototype.Messages['minHeightError'] = 'Внимание! Ширина должна быть больше #val# cm!';
PosterCalc.prototype.Messages['intHeightError'] = 'Внимание! Ширина может быть только целым числом!';

PosterCalc.prototype.resetForm = function() {
  this.isCorrect = false;
  if (typeof(this.wfield) != 'undefined') {
  
      this.wfield.style.color = this.normalColor;
      this.hfield.style.color = this.normalColor;
  }
  if ( document.getElementById('calcUPEr') ) {
      document.getElementById('calcUPEr').innerHTML='';
  }
}

PosterCalc.prototype.OnSend = function() {
  this.price = 0;                                        
  this.resetForm();
  this.CheckLimit();
  this.price = this.calculate();
}

function isDiscount(clW, clH, type, wo_personal) {

    var isDiscount = false;
    if ( typeof(discount) != 'undefined' ) {

        if ( typeof(discount.type) != 'undefined' && ( discount.type == type || discount.type == 255) ) {

            isDiscount = true;
        } else if ( ( discount.width == clW && discount.height == clH )
                 || ( discount.width == clH && discount.height == clW ) ) {

            isDiscount = true;
        }
    }

    if ( typeof(wo_personal) == 'undefined' && typeof(personal_discount) != 'undefined' ) {

        isDiscount = true;
    }

    return isDiscount;
}

function getPriceWithDiscount(price, clW, clH, type) {

    if (isDiscount(clW, clH, type)) {

        if ( typeof(discount) != 'undefined' ) { 

            calc_discount = discount;
        }

        if ( typeof(personal_discount) != 'undefined' ) {

            if ( typeof(discount) != 'undefined' && isDiscount(clW, clH, type, true) ) {

                if ( discount.value < personal_discount.value) {

                    calc_discount = personal_discount;
                }
            } else {

                calc_discount = personal_discount;
            }
        }

        price = parseInt(price);
        price = parseInt(price*(1-calc_discount.value/100));
    }

    return price;
}

PosterCalc.prototype.calculate = function() {
  if( this.isCorrect == false) 
    return 0;
  var cData = this.calcData[this.type];
  if(typeof(cData) != 'undefined' && cData != -1) {
    var squar = parseFloat(this.wfield.value)*parseFloat(this.hfield.value);
    var defval = null;
    var price = 0;
//    alertSave('3: '+this.wfield.value+' '+this.hfield.value);
    for(key in cData) {
      if(cData[key].limit == 0) {
        defval = cData[key];
      } else if(price == 0 && squar < cData[key].limit) {
        price = squar*cData[key].point/100; 
      }
    }
    if(price == 0)
      price = squar * defval.point / 100;
    price = Math.ceil(price);
    if(price <= 0)
      this.isCorrect=false;

    clW = this.wfield.value * 10;
    clH = this.hfield.value * 10;
    if (isDiscount(clW, clH, this.type)) {

        price = '<s>' + price + '</s> <font color="red">' + getPriceWithDiscount(price, clW, clH, this.type) + '</font>';
    }
    return price;
  }
}

PosterCalc.prototype.setError = function(type, error, value) {
  this.isCorrect = false; 
  if('width' == type)
    var Element = this.wfield;
  if('height' == type)
    var Element = this.hfield;
  Element.style.color = this.errorColor;
  var message = this.Messages[error];
  if(typeof(value) != 'undefined')
    message = this.str_replace('#val#', value, message);
  this.errorMessage = message;
}

PosterCalc.prototype.CheckLimit = function() {

  if (typeof(this.wfield) != 'undefined') {
    if (parseInt(this.wfield.value) != 0 || parseInt(this.hfield.value) != 0) {

        if(!parseInt(this.wfield.value) && parseInt(this.wfield.value) !== 0) {
          this.setError('width', 'intWeightError');
        }
        else if(this.wfield.value  < this.usedLimit.minW) {
          this.setError('width', 'minWidthError', this.usedLimit.minW);
        }
        else if(this.wfield.value > this.usedLimit.maxW) {
          this.setError('width', 'maxWidthError', this.usedLimit.maxW);
        }
        else if(!parseInt(this.hfield.value)) {
          this.setError('height', 'intHeightError');
        }
        else if(this.hfield.value < this.usedLimit.minH) {
          this.setError('height', 'minHeightError', this.usedLimit.minH);
        }
        else if(this.hfield.value > this.usedLimit.maxH) {
          this.setError('height', 'maxHeightError', this.usedLimit.maxH);
        } else {
          this.isCorrect = true;
          this.errorMessage = false;
        }
    }
  }
}

PosterCalc.prototype.str_replace = function(search, replace, source) {
    return source.replace(new RegExp(search,'gi'), replace);
}

var array_math = [
  [{'limit' : 0, 'point':10}, {'limit' : 5000, 'point':14}, {'limit' : 10000, 'point':12}],
  [{'limit' : 0, 'point':21}, {'limit' : 5000, 'point':29}, {'limit' : 10000, 'point':25}],
  -1,
  [{'limit' : 0, 'point':3.5}, {'limit' : 60000, 'point':4.5}, {'limit' : 180000, 'point':3.8}],
  [{'limit' : 0, 'point':14}, {'limit' : 10000, 'point':18}, {'limit' : 60000, 'point':16}],
  [{'limit' : 0, 'point':13}, {'limit' : 5000, 'point':17}, {'limit' : 10000, 'point':15}],
  [{'limit' : 0, 'point':13}, {'limit' : 5000, 'point':17}, {'limit' : 10000, 'point':15}]
];
var array_printLimit = [
{'minH':30, 'maxH':150, 'minW':30, 'maxW':300}, 
{'minH':80, 'maxH':1500, 'minW':80, 'maxW':3000}, 
{'minH':30, 'maxH':1000, 'minW':30, 'maxW':2000}];
//key=printtype, value=limit type
var array_key_printLimit = [0, 0, -1, 1, 2, 0];
var array_name_material = ["Постер", "Жесткий постер", "Холст", "Баннер для наружной эксплуатации", "Баннер для интерьера", "Постер с ламинацией", "Световой короб"];

var ErrorMessages = [];
ErrorMessages['maxWidthError']  = 'Внимание! Длина не может быть больше #val# cm!'; 
ErrorMessages['minWidthError']  = 'Внимание! Длина должна быть больше #val# cm!';
ErrorMessages['intWeightError'] = 'Внимание! Длина может быть только целым числом &gt; 0!';
ErrorMessages['maxHeightError'] = 'Внимание! Ширина не может быть больше #val# cm!';
ErrorMessages['minHeightError'] = 'Внимание! Ширина должна быть больше #val# cm!';
ErrorMessages['intHeightError'] = 'Внимание! Ширина может быть только целым числом &gt; 0!';

function stError (error, value) {
  var message = ErrorMessages[error];

  if(typeof(value) != 'undefined')
    message = message.replace(new RegExp( '#val#','gi'), value);

  return message;

}

function apply_data_from_diff_cost_for_table ( type ) {

  var hls_h = $('#diff_u_height_table').val();
  var hls_w = $('#diff_u_width_table').val();

  var msgError = "";
  var isCorrect = true;
  
  if(!parseInt(hls_w)) {
      isCorrect = false;
  }
  else if( array_key_printLimit[ type ] != -1 
        && hls_w < array_printLimit[ array_key_printLimit[ type ] ].minW  ) {
      isCorrect = false;
  }
  else if( array_key_printLimit[ type ] != -1 
        && hls_w > array_printLimit[ array_key_printLimit[ type ] ].maxW) {
      isCorrect = false;
  }
  else if(!parseInt(hls_h)) {
      isCorrect = false;
  }
  else if( array_key_printLimit[ type ] != -1 
        && hls_h < array_printLimit[ array_key_printLimit[ type ] ].minH) {
      isCorrect = false;
  }
  else if( array_key_printLimit[ type ] != -1 
        && hls_h > array_printLimit[ array_key_printLimit[ type ] ].maxH) {
      isCorrect = false;
  }

  if ( !isCorrect ) {
      document.getElementById('m_type_table_'+type+'_1').innerHTML= '-';
      return;
  }

  var price = "";

  if ( type == 2) {
        arr_size_2 = arr_size[2];
        isCorrect = false;
        idd=0;
        for(iiii=0;arr_size_2[iiii];iiii++) {

            if ( ( parseInt(arr_size_2[iiii][0]) == hls_w*10 && 
                   parseInt(arr_size_2[iiii][1]) == hls_h*10 ) ||
                 ( parseInt(arr_size_2[iiii][0]) == hls_h*10 && 
                   parseInt(arr_size_2[iiii][1]) == hls_w*10 ) ) { 
                 isCorrect = true;
                 price = arr_size_2[iiii][2];
                 idd=arr_size_2[iiii][3];
                break;
            }
        }

        if ( ! isCorrect ) {
            price = "-";
        }

  } else {
    var cData = array_math[type];

    if(typeof(cData) != 'undefined' && cData != -1) {
        var squar = parseInt(hls_w)*parseInt(hls_h);
        var defval = null;
        //var price = 0;
        for(key in cData) {
            if(cData[key].limit == 0) {
                defval = cData[key];
            } else if(price == 0 && squar < cData[key].limit) {
                price = squar*cData[key].point/100; 
            }
        }

        if(price == 0)
        price = squar * defval.point / 100;
        price = Math.ceil(price);
    }
  }

  if (price != 0 && price != "-") {

      if (isDiscount(hls_w*10, hls_h*10, type)) {

          price = getPriceWithDiscount(price, hls_w*10, hls_h*10, type);
      }
      document.getElementById('m_type_table_'+type+'_1').innerHTML= price + ' р.';
      jQuery(document.getElementById('m_type_table_'+type+'_1')).parent().removeClass('minus');
  } else {
  
      document.getElementById('m_type_table_'+type+'_1').innerHTML= '-';
      jQuery(document.getElementById('m_type_table_'+type+'_1')).parent().addClass('minus');
  }
}

UploadB = new Object();
UploadB.Calc = UploadB.isShowCalc = UploadB.calcResult = UploadB.calcPriceL = UploadB.calcPType = UploadB.calcDisplay = UploadB.calcPriceB = false;
UploadB.filetypes = "jpg,jpeg,jpe";
UploadB.postLocation="pgbar.php";

UploadB.onCalc = function() {
  this.calcReset();
//  alert('1: '+this.Calc.price);
  var tempptype = $('#printtype').val();
/*
  alert(' '+typeof(this.Calc)+' '+tempptype +' '+ this.calcPType + ' ' +
         document.set_image.u_width.value + ' ' + document.set_image.u_width.value);
*/
  if(tempptype != this.calcPType 
     || (!this.Calc
         || ( this.Calc.wfield.value != document.set_image.u_width.value 
              || this.Calc.hfield.value != document.set_image.u_width.value ) 
         ) 
     ) {
//    alert('i hir ');
//    alert('0: '+document.set_image.u_width.value+' '+document.set_image.u_height.value);
    this.calcPType = tempptype;
    this.Calc = new PosterCalc(this.calcPType, document.set_image.u_width, document.set_image.u_height);
    //this.calcPriceL = $("#calc_pr1");
    //this.calcResult = document.getElementById('calc_pr2');
    //this.calcPriceB = document.getElementById('calc_pr3');
  }
  this.Calc.OnSend();
//  alert('2: '+this.Calc.price);
  if(this.Calc.isCorrect == false) {
    if ( document.getElementById('calcUPEr') && this.Calc.errorMessage != false) {
        document.getElementById('calcUPEr').innerHTML = this.Calc.errorMessage;
    }
  } else {
    UploadB.calcSuccess();
  }

  if (typeof selectColumnForDiffPricePage == 'function') {// если мы на странице сравнения цен

    if (typeof(document.set_image) != 'undefined' 
        && typeof(document.set_image.u_width) != 'undefined') {

        $("#diff_u_width_table").val(document.set_image.u_width.value);
        $("#diff_u_height_table").val(document.set_image.u_height.value);
        apply_data_from_diff_all_table();
    }
  }
}

UploadB.calcReset = function() {
  $("#calc_pr1").html("0");
  /*if (this.calcPriceL != undefined && this.calcPriceL != false) {
    this.calcPriceL.html("0");
    //this.calcPriceL.innerHTML = "0";
  }*/
  /*if (this.calcPriceB) {
    this.calcPriceB.innerHTML = "";
  }*/
  /*if (this.calcResult) {
    this.calcResult.innerHTML = "&lt;введите данные&gt;";
  }*/
  if ( document.getElementById('calcUPEr') ) {
      document.getElementById('calcUPEr').innerHTML = '';
  }
  UploadB.CalcSetup = false;
}

UploadB.calcSuccess = function() {
  /*if ( this.calcResult ) {
      this.calcResult.innerHTML = ""+this.Calc.wfield.value+" x "+this.Calc.hfield.value+" cm";
  }*/
  //this.calcPriceL.innerHTML = this.Calc.price;
  $("#calc_pr1").html(this.Calc.price);
  /*if ( this.calcPriceB ) {
      this.calcPriceB.innerHTML = this.Calc.price + " руб.";
  }*/
  UploadB.CalcSetup = true;
}

UploadB.showCalc = function(forcehide, formatId) {

  if (!formatId) {

    formatId = -1;
  }
  if(!this.calcDisplay)
    this.calcDisplay = document.getElementById("divcalc");
  if(this.isShowCalc == true) {
    this.calcDisplay.style.display = 'none';
    this.isShowCalc = false;
  } else if(typeof(forcehide) == 'undefined' && this.isShowCalc == false) {
    this.calcDisplay.style.display = 'block';
    this.isShowCalc = true;
  }
  if (typeof selectColumnForDiffPricePage == 'function' && formatId != -1) {

      selectTdForDiffPricePage(formatId);
  }
}

UploadB.changePtype = function(ptype) {
  if(this.calcPType != ptype) {
    if (typeof selectColumnForDiffPricePage == 'function') {// если на странице сравнения цен
        selectColumnForDiffPricePage('printType' + ptype);
    }
    $('#printtype').val(ptype);
    this.onCalc();
    var calcwidth = this.Calc.usedLimit.minW+' - '+this.Calc.usedLimit.maxW+' cm';
    var calcheight = this.Calc.usedLimit.minH+' - '+this.Calc.usedLimit.maxH+' cm';
    $('#calcwidth').html('('+calcwidth+')');
    $('#calcheight').html('('+calcheight+')');
  }
}

UploadB.checkInput =  function(sid,c) {
  /* check file extension */
  var filename = document.set_image.postpic.value;
  if(filename == "") {
    alert(unescape("Пожалуйста, выберите файл!"));
    return false;
  } else {
    var plist = document.set_image.products_list;
    var vlist = document.set_image.product_v;
    if( typeof(this.Calc.type) == 'undefined') {
      var ptype = $('#printtype').val();
    } else {
      var ptype = this.Calc.type;
    }
    if(typeof(plist) != 'undefined' && plist.checked == true && document.set_image.format.value == 0) {
      alert(unescape("Пожалуйста, выберите формат!"));
      return false;
    } else if(((typeof(vlist) != 'undefined' && vlist.checked == true) || (ptype == 3 || ptype == 4)) && this.CalcSetup != true) {
      alert(unescape("Пожалуйста, укажите размеры!"));
      return false;
    } else {
      if(filename) {
        var regtypes = this.filetypes.replace(/,/g,'|');
        var reg = new RegExp("(.*)\.(" + regtypes + ")$", "i");
        if (filename.match(reg)) {
                                                                                                                          
            uploadImgProgress();

            return true;

        } else {
          alert(unescape("Указанный формат файла не разрешен к загрузке.\nМы принимаем только файлы форматов: "+this.filetypes));
          return false;
        }
      }
    }
  }
}

UploadB.postIt = function () {
  var baseUrl = this.postLocation;
  var sid = document.set_image.sessionid.value;
  var iTotal = escape("-1");
  baseUrl += "?iTotal=" + iTotal + "&iRead=0&iStatus=1&sessionid=" + sid;
  popUP(baseUrl,"Uploader", 350, 200, false, false);
}

function getCalendarsPrice() {

  calendarsPrice = 0;
  for (iii=0; $('.calendarPrice')[iii]; iii++ ) calendarsPrice += $('.calendarPrice')[iii].value*1;

  return calendarsPrice;
}

PostList = new Object();
PostList.List = new Object();
PostList.dprice = null;
PostList.zprice = null;

PostList.setPrice = function(dprice, zprice) {
  if(!this.dprice || !this.zprice) {
    this.dprice = $('#dprice');
    this.zprice = $('#zprice');
  }

  zprice = zprice*1+getCalendarsPrice()*1;
  if ( dprice*1 > 0 ) {

      dprice = dprice*1;
      limit = 5000;

      existJestPoster = false;
      $('input[name=printtype]').each( function ( wwww ) { if( $(this).val() == 1 ) existJestPoster = true;} );
      if ( existJestPoster ) {
          limit = 15000;
      }

      if ( zprice*1-dprice > limit) {

          zprice=zprice-dprice;
          dprice='0';
      }
  }

  this.dprice.html(dprice);
  this.zprice.html(zprice);
}

PostList.deleteF = function (id) {
  document.location = "/ajaxproxy.php5?goto=cart&delete="+id;
}
PostList.completeDel = function (id) 
{
  if(Item = this.getItem(id)) {
    $('table:first',Item.form).css('border','none');
    Item.blockform(false);
  }
}
PostList.successDel = function (id, data) {
  if(Item = this.getItem(id)) {
    if(data.statys == '1') {
      PostList.remove(id);
      PostList.setPrice(data.dprice, data.zprice);
    }
  }
  this.List[id] = null;

}
PostList.remove = function(id) {
  if(Item = this.getItem(id)) {
    $(Item.form).fadeOut("normal", function() {
      $(this).remove();
      if ( $('.calendarPrice').length == 0 && $('input[name=printtype]').length == 1) {
          document.location = "/post.php5";
      }
    });
  }
}
PostList.beforeDel = function (id) {
  if(Item = this.getItem(id)) {
    $('table:first', Item.form).css('border','1px #ff0000 dashed');
    Item.blockform(true);
  }
}
PostList.copyF = function (id) {
  document.location = "/ajaxproxy.php5?goto=cart&copy="+id;
}
PostList.beforeCopy = function (id) {
  if(Item = this.getItem(id)) {
    $('table:first', Item.form).css('border','1px #87b303 dashed');
    Item.blockform(true);
  }
}
PostList.completeCopy = function (id) {
  if(Item = this.getItem(id)) {
    $('table:first',Item.form).css('border','none');
    Item.blockform(false);
  }
}
PostList.successCopy = function (data) {
  $(data.html).hide().insertAfter('#newForm');
  PostList.setPrice(data.dprice, data.zprice);
  zz = PostList.getItem(data.id);
  $('#change_form'+data.id).slideDown("slow");
}

PostList.getItem = function(id) {
  if(typeof(PostList.List[id]) == 'undefined' || PostList.List[id] == null) {
    var form = document.getElementById('change_form'+id);
    if(typeof(form) == 'undefined')
      return false;
    PostList.List[id] = new PostItem(form, id);
  }
  return PostList.List[id];
}


PostList.dostavkaGo = function() {
  var checked=2;
  if($('#dostavkaBtn').attr('checked')==true) {
      checked=1;
  }
  document.location = "/ajaxproxy.php5?goto=cart&dostavka="+checked;
}



function PostItem(form, id) {
  this.id = id;
  this.form = form;
  this.isSending = false;
  this.html = new Object();
  this.html.progress = $("div.progress",this.form);
  this.html.as = $("a",this.form);
  this.html.imgtd = $("div[id*=imgtd]",this.form);
  this.html.selectes = $("select,input",this.form);
  this.html.aim = $('a[id^=images]', this.form);
  this.CalcResult = this.Calc = false;
}

PostItem.prototype.qType = [ '<strong style="color:#cc0000">недостаточное</strong>',
'<strong style="color:#ff9900">плохое</strong>',
'<strong style="color:#ff9900">удовлетворительное</strong>',
'<strong style="color:#ff9900">хорошее</strong>',
'<strong style="color:#87b303">отличное</strong>' ];

PostItem.prototype.submit = function() {
  if(this.Calc && this.Calc.isCorrect == false) {
    this.isCorrect = false;
    this.onErrorCalc();
    return false;
  }
  var sid = this.id;
  $(this.form).append("<input type='hidden' name='goto' value='cart'>");
  this.form.submit();
} 

PostItem.prototype.blockform = function(isBlocking) {
  if(isBlocking == true) {
    this.html.imgtd.height($('img', this.html.aim).height());
    this.html.progress.show();
    this.html.as.hide();
  } else {
    this.html.imgtd.height(100);
    this.html.progress.hide();
    this.html.as.show();
  }
  this.html.selectes.each(function(){this.disabled=isBlocking;});
}

PostItem.prototype.setQuality = function(data) {
  if(typeof(data.dpi) != 'undefined') {
    var ukey = 0;
    if(typeof(data.isCreator) != 'undefined' && data.isCreator) {
        ukey = 3;
    } else if(data.dpi <= 30) {
        ukey = 0;
    } else if(data.dpi <= 49) {
        ukey = 1;
    } else if(data.dpi <= 74) {
        ukey = 2;
    } else if(data.dpi < 100) {
        ukey = 3;
    } else if(data.dpi >= 100) {
        ukey = 4;
    }
    $('#quality'+data.id, this.form).html(this.qType[ukey]);
  }
}

PostItem.prototype.onSuccess = function(data) {
 if(data.error) {
   alert(data.error);
   return false;
 }
 if(data.id) {
  var imTitle=$('img', this.html.aim).attr('title')+' ';
  var imSrc='/imgread.php5?file='+data.image+"&ncash="+rand(100,1000);
  $(this.html.aim).html('<img style="visibility: hidden;" src="'+imSrc+'" tille="'+imTitle+'" border="0" />');
  if(data.baget != "") {
   PostList.getItem(data.id).fillselect(data.baget, data.sbaget, 'printsubtype'+data.id);
   }
  if(data.lumen != "")
   PostList.getItem(data.id).fillselect(data.lumen, data.slumen, 'lumen'+data.id);
  this.setQuality(data);
  $('#rwidth'+data.id,this.form).html(data.rwidth);
  $('#rheight'+data.id,this.form).html(data.rheight);
  $('#price'+data.id,this.form).html(data.price);
  $('#fullprice'+data.id,this.form).html(data.fullprice);
  PostList.setPrice(data.dprice, data.zprice);
  $('img', this.html.aim).load( function() { $(this).css('visibility','visible'); } );
  }
}

PostItem.prototype.fillselect = function(Sarray, Sactive, Sid) {
 var selectB=$('#'+Sid, this.form);
 var optionB='';

 for(key in Sarray)
   optionB+="<option value=\""+key+"\" >"+Sarray[key]+"</option>";
   $(selectB).html(optionB);

   $(selectB).children().each(function(w){

   if( this.value == Sactive) this.selected=true; 
   else this.selected=false;
 });
}

PostItem.prototype.setCalc = function() {
  if(!this.Calc) {
    this.Calc = new PosterCalc($('input[name=printtype]', this.form).val(), this.form.u_width, this.form.u_height);
    this.CalcResult = $('#calc_'+this.id+'_result');
  }
}

PostItem.prototype.onCalc = function() {
  if(!this.Calc) {
    this.setCalc();
  }
  this.Calc.OnSend();
  var price = this.Calc.price;
  if(!price) price = "0";
  if ( this.Calc.isCorrect && this.oldPrice != price ) { this.submit(); }
  this.oldPrice = price;
  this.CalcResult.html(price);
}

PostItem.prototype.onErrorCalc = function() {
  alert(this.Calc.errorMessage);
}

function chkKs(e) {
  var key = (typeof(e.charCode) == 'undefined' ? e.keyCode : e.charCode);
  if (e.ctrlKey || e.altKey || key < 32)
    return true;
  key = String.fromCharCode(key);
  if ( /[\d\.]/.test(key) ) {

    prd_v = document.getElementById('product_v');
    if (prd_v) prd_v.checked = true;
    return true;
  }
  return false;
}

function chkKs_number(e) {
  var key = (typeof(e.charCode) == 'undefined' ? e.keyCode : e.charCode);
  key = String.fromCharCode(key);
  if ( /[\d\.]/.test(key) ) {

    return true;
  }
  return false;
}

function chkKs_mixed(e, str) {
  var key = (typeof(e.charCode) == 'undefined' ? e.keyCode : e.charCode);
  if (e.ctrlKey || e.altKey || key < 32)
    return true;

  key = String.fromCharCode(key);
  rgxp = new RegExp(str, "");
  if ( rgxp.test(key) ) {

    return true;
  }
  return false;
}

function thisMainPage() {
    var logo = document.getElementById('logo_href')
    logo.onclick = function() { return false; };
    $(logo).css('cursor', 'default');
    $(logo).css('outline', 'none');
    $(logo).attr('title', '');
}

var progressWidthBegin = 200;
var progressWidth = 200;
var progressStep = 2;
function progress( id ) {

    progressWidth = progressWidth - progressStep;

    jQuery( id+'' ).css( "width", progressWidth+"px");
    if ( progressWidth == 0 ) {

        progressWidth = progressWidthBegin;
    }

    setTimeout('progress("'+id+'")', 100);
}

function uploadImgProgress() {

    jQuery("#submit2").replaceWith('<div id="pb4" style="margin-left: 25px; margin-top: 5px;"></div>');

    var _pbbar_pos = 0;
    var _pbars_pbars = [];

    _pbars = [ $("#pb4").progressCtrl({ skin: '/images/pbskin2.png', width:270} ) ];

    setInterval(function(){
        if (++_pbbar_pos > 100) _pbbar_pos = 0;
        for (var i=0; i<_pbars.length; ++i)
        {
            _pbars[i].progressCtrl(_pbbar_pos);
        }
        
    }, 180);

}

function get_quality ( onpage, p_w, p_h, w, h ) {

    if ( parseFloat(width) == 0 || parseFloat(height) == 0 ) {
        dpi=0;
    }
    else {
        if ( onpage == 1 ) {

            SW           = get_w_h( p_w, p_h, w, h );
            real_print_w = SW[0];
            real_print_h = SW[1];
            dpi          = Math.round( Math.sqrt( ( w * h ) / ( real_print_w / 25.4 * real_print_h / 25.4 ) ) );

        } else {

            xx_ratio     = p_w / w;
            yy_ratio     = p_h / h;
            ratio        = Math.max( xx_ratio, yy_ratio );
            if ( xx_ratio == ratio ) { use_x_ratio = true; }
            else { use_x_ratio = false; }

            if ( use_x_ratio ) {

                rpW = w;
                rpH = Math.floor( p_h / ratio );
            }
            else {
                rpW = Math.floor( p_w / ratio );
                rpH = h;
            }

            dpi = Math.round( Math.sqrt( ( rpW * rpH ) / ( p_w / 25.4 * p_h / 25.4 ) ) );
        }
    }
    return dpi;
}


function get_w_h( w, h, nw, nh ) {
    xs_ratio = w / nw;
    ys_ratio = h / nh;

    sratio   = Math.min( xs_ratio, ys_ratio );

    if ( xs_ratio == sratio ) { use_xs_ratio = true; }
    else { use_xs_ratio = false; }

    if ( use_xs_ratio ) {
        news_width   = w;
        news_height  = Math.floor( nh * sratio );
    }
    else {
        news_width   = Math.floor( nw * sratio );
        news_height  = h;
    }

    return [ Math.round( news_width ), Math.round( news_height ), use_xs_ratio ];
}

function chkKs_DPI( obj, event ) {
    if ( chkKs(event) ) { 

        if ( obj.value == ""){
            obj.value = 0; 
        } else {            
            if ( obj.value.substr(0, 1) == "0" &&  obj.value.length != 1) {
//                obj.value  = parseInt(obj.value);
                obj.value = obj.value.substr(1,obj.value.length - 1);
            }
        }   
        calcDPI();
        return true; 
    }
    else {        
        return false;
    }
}

arr_print_size = [ [ 300, 200 ], [ 600, 400 ], [ 900, 600 ], [ 1200, 800 ], [ 1500, 1000 ] ];
arr_quality = [ 99, 74, 49, 30 ];
arr_quality_desc = [ "<font color='#009933'>Отличное</font>", "<font color='#99cc33'>Хорошее</font>", "<font color='#eee007'>Удовлетворительное</font>", "<font color='#ff6600'>Плохое</font>", "<font color='#cc0000'>Недостаточное</font>" ];
function calcDPI () {

    onpage = jQuery('input[@name=calcDPIonpage]:checked').val();
    width  = jQuery('#calcDPIWidth_id').val();
    height = jQuery('#calcDPIHeight_id').val(); 
/*
    if ( width == 0 || height == 0 ) {
    }
    else {
*/
        for ( i=0; arr_print_size[i]; i++) {

            tr = jQuery('#calcDPIresult tr:eq('+(i+1)+')');
            dpi = get_quality ( onpage, arr_print_size[i][0], arr_print_size[i][1], width, height );
            dpi_desc = arr_quality_desc[arr_quality_desc.length-1];
            for ( j=0; arr_quality[j]; j++ ) {

                if ( arr_quality[j] < dpi ) {
                    dpi_desc = arr_quality_desc[j];
                    break;
                }
            }
            jQuery(tr).find('td:eq(2)').html( dpi_desc );
        }
//    }
}

function activateCalcDPI( obj ) {
//    dpi = get_quality ( true, 600, 400, 1200, 600 );
    
    jQuery(obj).append("<br><table>"
                       +"<tr><td colspan='3' align='left'><b>Размещение:</td></tr>"
                       +"<tr><td></td><td style='width: 10px;'></td><td><input type='radio' name='calcDPIonpage' value='1' checked onclick='calcDPI();'>&nbsp;Вписать</td></tr>"
                       +"<tr><td></td><td style='width: 10px;'></td><td><input type='radio' name='calcDPIonpage' value='0' onclick='calcDPI();'>&nbsp;Обрезать</td></tr>"
                       +"<tr><td style='height: 10px;'></td></tr>"
                       +"<tr><td colspan='3' align='left' nowrap><b>Размеры изображения в пикселях:</b></td></tr>"
                       +"<tr><td style='height: 5px;'></td></tr>"
                       +"<tr><td>Ширина</td><td></td><td><table><tr><td><input onkeyup='return chkKs_DPI(this, event);' onkeypress='return chkKs_DPI(this, event);' type='text' value='300' name='calcDPIWidth' id='calcDPIWidth_id' style='text-align: right; width: 40px'/></td><td align=left>px</td></tr></table></td></tr>"
                       +"<tr><td>Высота</td><td></td><td><table><tr><td><input onkeyup='return chkKs_DPI(this, event);' onkeypress='return chkKs_DPI(this, event);' type='text' value='300' name='calcDPIHeight' id='calcDPIHeight_id' style='text-align: right; width: 40px'/></td><td align=left>px</td></tr></table></td></tr>"
                       +"</table><br>"
                       +"<table id='calcDPIresult' style='border-collapse: collapse;'>"
                       +"<tr><td style='background: #eee; height: 20px;'><b>Размер печати</td><td style='width: 10px; background: #eee;'></td><td style='background: #eee;'><b>Качество</td></tr>"
                       +"</table><br>");

    for ( i=0; arr_print_size[i]; i++) {

        jQuery('#calcDPIresult').append("<tr><td style='height: 15px;' align='center'>"+arr_print_size[i][0]/10+"x"+arr_print_size[i][1]/10+"</td><td></td><td style='font-weight: bold;'>0</td></tr>");
    }
    calcDPI();
//    jQuery(this).html('<br/> ('+dpi+')');
    
}
