﻿function enablePrintView(isExtend) 
{
  if (isExtend) document.getElementById("printViewTools").style.display = "block";
  document.styleSheets[0].disabled = false;
  document.styleSheets[1].disabled = true;
  window.scrollTo(0, 0);
}
function enableBrowseView(isExtend)
{
  if (isExtend) document.getElementById("printViewTools").style.display = "none";
  document.styleSheets[0].disabled = true;
  document.styleSheets[1].disabled = false;
}
function beginPrint()
{
  var isMoz = /Firefox/i.test(navigator.userAgent);
  if (isMoz) {
    document.getElementById("printViewTools").style.display = "none";
  } else {
    // это работает только для IE
    window.onafterprint = new Function('enableBrowseView();'); 
    window.onbeforeprint = new Function('document.getElementById("printViewTools").style.display = "none";');
  }
  window.print();
  if (isMoz) setTimeout('enableBrowseView();', 1000*40); // это альтернатива для Firefox после задержки к нормальному виду
}


//проверка заполенности поля ввода поисковой фразы
function CheckInitSearch() {
    var form_obj = document.SearchForm;
    if ((form_obj.srch98query.value != form_obj.srch98query.defaultValue) && (form_obj.srch98query.value.length > 0)) {
        form_obj.submit();
    } else {
        alert("Необходимо задать условия поиска");
    }
    return false;
}

function window_open(title, href, target, width, height) {
    width = parseInt(width, 10);
    height = parseInt(height, 10);
    var wind_img = window.open('', target, 'width=' + (height > 800 ? width + 16 : width) + ',height=' + (height > 800 ? 800 : height) + (height > 800 ? ',scrollbars=yes' : '') + ',resizable=yes');
    wind_img.focus();
    wind_img.document.open();
    wind_img.document.write('<html><head><META http-equiv="Content-Type" content="text/html; charset=windows-1251">' + (title ? '<title>' + title + '</title>' : '<title>Большое изображение</title>') + '</head>');
    wind_img.document.write('<body leftmargin="0" rightmargin="0" topmargin="0" bottommargin="0" marginwidth="0" marginheight="0"><img src="' + href + '" border="0" width="' + width + '" height="' + height + '" title="' + title + '" alt="' + title + '">');
    wind_img.document.write('</body></html>');
    wind_img.document.close();
    return false;
}

var PrintView = {

    _printIndex: -1,
    _printLink: null,
    enabled: false,

    enable: function() {
        if (this.enabled) return;
        if (this._printLink == null) {
            this._printLink = document.createElement("link");
            this._printLink.setAttribute("rel", "stylesheet");
            this._printLink.setAttribute("href", "/_css/print.css");
            document.body.appendChild(this._printLink);
            this._printIndex = document.styleSheets.length - 1;
        }
        this.enabled = true;
        for (var i = 0; i < document.styleSheets.length; ++i) {
            if (i == this._printIndex)
                document.styleSheets[i].disabled = false;
            else
                document.styleSheets[i].disabled = true;
        }
    }
  ,
    disable: function() {
        if (this._printLink == null || !this.enabled) return;
        this.enabled = false;
        for (var i = 0; i < document.styleSheets.length; ++i) {
            if (i == this._printIndex)
                document.styleSheets[i].disabled = true;
            else
                document.styleSheets[i].disabled = false;
        }
    }
  ,
    autoPrint: function() {
        if (document.location.search.indexOf("?printv") >= 0 || document.location.search.indexOf("&printv") >= 0) {
            this.run();
        }
    }
  ,
    run: function() {
        this.enable();
        window.print();
    }
  ,
    openWindow: function() {
        var url = document.location.href;
        if (url.indexOf('?') >= 0) url += "&printv";
        else url += "?printv";
        var pwin = window.open(url, 'printWindow');
    }
}

jQuery(function() { PrintView.autoPrint(); });







function CalculatorFieldActive(obj) {
    var ch_list = (obj) ? $(obj) : $("input[name='cf_checked']]");
    for (var i = 0; i < ch_list.length; i++) {
        var ch_obj = ch_list[i];
        var tr_obj = ch_obj.parentNode.parentNode;
        tr_obj.className = (ch_obj.checked) ? "cf_enabled" : "cf_disabled";
    }
    UpdateSummary();
}

function CountChange(id) {

    //получаем количество
    var input_obj = document.CalculatorForm["cf" + id + "_value"];
    var count = parseInt(input_obj.value, 10);
    if ((count <= 0) || (isNaN(count))) count = 1;

    input_obj.value = count;

    //обновляем строку

    var ch_obj = $("input[name='cf_checked'][value='" + id + "']").get(0);
    ch_obj.checked = true;
    CalculatorFieldActive(ch_obj);

    //получаем цену
    var input_price_obj = document.CalculatorForm["cf" + id + "_price"];
    var price = parseInt(input_price_obj.value, 10);
    if (price <= 0) price = 1;

    //обновляем строку
    $("span#cf" + id + "_cost").text((isNaN(count) || isNaN(price)) ? "-" : count * price);

    UpdateSummary();
}

//обновляем итог
function UpdateSummary() {
    var span_list = $("span[id$='_cost']");
    var summary = 0;
    for (var i = 0; i < span_list.length; i++) {
        var span_obj = span_list[i];
        var tr_obj = span_obj.parentNode.parentNode;
        if (tr_obj.className != "cf_disabled") summary += parseInt(span_obj.innerHTML);
    }
    $("span#total").text(isNaN(summary) ? "-" : summary);
}

$(function() {
    UpdateSummary();
    //if (!CheckSelectedChGroup('ch_fmi_active_') {}
});

function AddToFavorites(obj, title, url) {
    if (window.sidebar) {
        // Mozilla Firefox 
        window.sidebar.addPanel(title, url, "");
    }
    else if (window.external) {
        // IE 
        window.external.AddFavorite(url, title);
    }
    else if (window.opera && window.print) {
        //Opera
        obj.setAttribute('href', url);
        obj.setAttribute('title', title);
        obj.setAttribute('rel', 'sidebar');
        obj.click();
    }
    return false;
}



function changeInputType(
  oldElm, // Элемент, тип которого будем менять
  iType, // Тип: 'text' или 'password'
  iValue, // Значение по умолчанию
  blankValue, // true если значение должно быть пустым, иначе false
  noFocus) {  // true чтобы нельзя было установать фокус на элемент
    if (!oldElm || !oldElm.parentNode || (iType.length < 4) || !document.getElementById || !document.createElement) {
        return;
    }
    
    var isMSIE = /*@cc_on!@*/false; //http://dean.edwards.name/weblog/2007/03/sniff/
    
    if (!isMSIE) {
        var newElm = document.createElement('input');
        newElm.type = iType;
    } else {
        var newElm = document.createElement('span');
        newElm.innerHTML = '<input type="' + iType + '" name="' + oldElm.name + '">';
        newElm = newElm.firstChild;
    }

    var props = ['name', 'id', 'className', 'size', 'tabIndex', 'accessKey'];
    
    for (var i = 0, l = props.length; i < l; i++) {
        if (oldElm[props[i]]) newElm[props[i]] = oldElm[props[i]];
    }
    
    newElm.onfocus = function() {
        return function() {
            if (this.hasFocus) return;
            var newElm = changeInputType(this, 'password', iValue,
      (this.value.toLowerCase() == iValue.toLowerCase()) ? true : false);
            if (newElm) newElm.hasFocus = true;
        }
    } ();
    
    newElm.onblur = function() {
        return function() {
            if (this.hasFocus)
                if (this.value == '' || (this.value.toLowerCase() == iValue.toLowerCase())) {
                changeInputType(this, 'text', iValue, false, true);
            }
        }
    } ();

    // устанавливаем hasFocus = false чтобы не вызывалось событие onfocus, что привело бы к зацикливанию
    newElm.hasFocus = false;
    
    // some browsers need the value set before the element is added to the page
    // while others need it set after
    if (!blankValue) {
        newElm.value = iValue;
    }
    
    oldElm.parentNode.replaceChild(newElm, oldElm);
    if (!isMSIE && !blankValue) {
        newElm.value = iValue;
    }
    
    if (!noFocus || typeof (noFocus) == 'undefined') {
        window.tempElm = newElm;
        setTimeout("tempElm.hasFocus=true;tempElm.focus();", 1);
    }
    
    return newElm;
}


function change_password_input_visibility(id, changePasswordStr, cancelStr) {
    var password_input = $("#" + id).get(0);
    var tr_password_copy = $("#tr_password_copy_" + id).get(0);
    var change_password_link = $("#link_change_password_" + id).get(0);

    var display = "";

    if (change_password_link.innerHTML == changePasswordStr) {
        change_password_link.innerHTML = cancelStr;
    }
    else {
        display = "none"
        change_password_link.innerHTML = changePasswordStr;
    }

    password_input.style.display = display;
    tr_password_copy.style.display = display;
}

function ChangeCalendar(calendarDivId, idSubContainer, year, month) {

    // alert(calendarId + ' ' + year + ' ' + month);
    var url = "/_modules/calendar/calendar.ashx"

    $.ajax({
        type: "POST",
        url: url,
        data: "id_sub_container=" + idSubContainer + "&year=" + year + "&month=" + month,
        cache: false,
        success: function(data) { UpdateCalendar(calendarDivId, data); },
        error: function() { alert("Произошла ошибка на вызываемой странице."); }
    });
}


function UpdateCalendar(calendarDivId, data) {
    if (data != "") {
        $("#" + calendarDivId).replaceWith(data);
    }
}
