var lastExpanded = 0;
var lastFilter = 0;

var isIE = isOpera = false;
if (navigator.appName == "Mozilla" || navigator.appName == "Netscape") {
    if (document.normalizeDocument) {
        document.normalizeDocument();
    }
} else if (navigator.appName == "Microsoft Internet Explorer" && navigator.userAgent.toLowerCase().indexOf('opera') < 0) { 
    isIE = true;
} else if (navigator.userAgent.toLowerCase().indexOf('opera')) {
    isOpera = true;
}

function menuClick(menuItem, dontHide) {
	dontHide = dontHide || 0;

	subMenu = menuItem.parentNode.parentNode.getElementsByTagName('ul')[0];
	//alert(subMenu);
	if (!subMenu) {
		return;
	}
	subMenu.style.display = subMenu.style.display == 'block' ? 'none' : 'block';
	menuItem.className = menuItem.className == 'active' ? '' : 'active';
	if (!dontHide) {
		if (lastExpanded) {
			//lastExpanded.className = "";
			if (lastExpanded == menuItem) {
				lastExpanded = 0;
			}
			else {
				menuClick(lastExpanded, 1);
				lastExpanded = menuItem;
			}
		}
		else {
			lastExpanded = menuItem;
		}
	}
}

function checkEqual() {
	$('#passNotEqual').css({'display': 'block'});
	frm = document.forms['personal'];
	pass1 = document.forms['personal']['password'].value;
	pass2 = document.forms['personal']['password2'].value;
	msg = document.getElementById('passEqual');
	if (pass1.match(/[a-z]/) && pass1.match(/[A-Z]/) && pass1.match(/\d+/) && pass1.length > 7 ) 
		$('#passNotEqual').css({'display': 'none'});
	if (pass1 == pass2 && pass1 != '') {
		msg.style.visibility = 'visible';
		$('#submit').attr('disabled', false);
	}
	else {
		msg.style.visibility = 'hidden';
	}
}

function openW(url, name, w, h, noScroll) {
	if (noScroll == 1) {
		window.open(url, window.name + 'qq', 'toolbar=no,location=no,status=no,menubar=no,resizable=no,directories=no,scrollbars=no,width=' + w + ',height=' + h + '');
	}
	else {
		window.open(url, window.name + 'qq', 'toolbar=no,location=no,status=no,menubar=no,resizable=no,directories=no,scrollbars=yes,width=' + w + ',height=' + h + '');
	}
}

function filterClick(filterId) {
        var filter = document.getElementById(filterId);
	if (lastFilter == filter) {
		filter.style.display = (filter.style.display == 'block' ? 'none' : 'block');
	} else {	 
		if (lastFilter) {
			lastFilter.style.display = 'none';
		}
		filter.style.display = 'block';
	}
	lastFilter = filter;
}

function changeTab(tab, right) {
  tabDiv = document.getElementById(tab);
  tabLi = tabDiv.parentNode;
  activeDiv = document.getElementById(activeTab);
  activeLi = activeDiv.parentNode;
  if (tabLi && activeLi) {
    activeLi.id = '';
    tabLi.id = 'activeTab';
    activeTab = tab;
    if (right) {
      rightDiv = document.getElementById(right);
      rightLi = rightDiv.parentNode;
      if (rightLi) {
		rightLi.id = 'activeTabRight';
      }
    }
  }
  var content = document.getElementById(tab + '_content');
  activeContentElement = document.getElementById(activeContent);
  if (content && activeContentElement) {
    activeContentElement.style.display = 'none';
    content.style.display = 'block';
    activeContent = tab + '_content';
  }
}

function recountProdOptions() {
    //console.log("---------------------------------------------------------------------------------------------");
    var optForm = document.forms['prodOptions'];
    if (optForm != null) {
        if (document.getElementById('prodPrice') == null) {
            return;
        }
        var prodPriceStr = document.getElementById('prodPrice').innerHTML;
        var prodPrice = parseFloat(prodPriceStr.split(/\s/)[0]);
        var currency = prodPriceStr.split(/\s/)[1];
        var nominalPrice = parseFloat(document.getElementById('prodPrice').getAttribute('nominal'));
        var totalPrice = nominalPrice;
        var delta = 0;

        if (currency == undefined) {
            currency = '';
        }

        var debugStr = "Start at " + nominalPrice + "\n";

        if (totalPrice == 0) {
            if (document.getElementById('prodPrice')) {
                document.getElementById('prodPrice').innerHTML = "Call";
            }
            if (document.getElementById('prodPrice1')) {
                document.getElementById('prodPrice1').innerHTML = "Call";
            }
            if (document.getElementById('prodPrice1-float')) {
                document.getElementById('prodPrice1-float').innerHTML = "Call";
            }
            if (document.getElementById('prodPrice1-before')) {
                document.getElementById('prodPrice1-before').innerHTML = "Call";
            }
            return;
        }

        if ($('#add2cart').length > 0) {
            $('#add2cart').attr('disabled', false);
        }
        if ($('#add2cart-float').length > 0) {
            $('#add2cart-float-empty').hide();
            $('#add2cart-float').show();
        }
        if ($('.optionCount').length > 0) {
            $('.optionCount').removeClass('error');
        }

        var query_string = 'options=0';

        /* Прибавляем все отмеченные опции кроме тех, что помечены как inPrice */
        for (i = 0; i < optForm.elements.length; i++) {
            var elem = optForm.elements[i];
            if (elem.nodeName.toLowerCase() == 'input' && (elem.type == 'radio' || elem.type == 'checkbox') && elem.checked) {
                var elemId = elem.getAttribute('id');
                var inPrice = parseInt(elem.getAttribute('inprice'));
                var include = parseInt(elem.getAttribute('include'));
                var optnum = parseInt(elem.getAttribute('optnum'));
                var optionCartNum = optnum;
                if (optnum == 0) {
                    /* это надо для расчетов, особенное если товар уже включен в цену */
                    optnum = 1;
                }
                var price = 0;
                if (elem.getAttribute('nominal')) {
                    price = parseFloat(elem.getAttribute('nominal'));
                }
                else {
                    price = parseFloat(elem.getAttribute('price')) / optnum;
                }
                /* возможно там есть поле для количества? */
                var tmp = elemId.split('_', 3);
                var countElem = document.getElementById(elemId + '_count');
                var typedCount = 0;
                if(tmp[1] != 'none' || countElem) {
                    query_string += ',' + tmp[1];
                }
                if (countElem) {
                    typedCount = parseInt($('#' + elemId + '_count').attr('value'));
                    if (!isNaN(typedCount)) {
                        /* надо проверить, не нарушены ли границы */
                        if (countElem.getAttribute('min')) {
                            if (typedCount < parseInt(countElem.getAttribute('min'))) {
                                typedCount = 0;
                                $(countElem).addClass('error');
                            }
                        }
                        if (countElem.getAttribute('max')) {
                            if (typedCount > parseInt(countElem.getAttribute('max'))) {
                                typedCount = 0;
                                $(countElem).addClass('error');
                            }
                        }
                        query_string += '.' + typedCount;
                        if (inPrice == 1 && include == 1) {
                            typedCount -= optnum;
                        }
                        optnum = typedCount;
                    }
                    else {
                        if(include > 0) {
                            if(optnum > 0) {
                                $('#' + elemId + '_count').attr('value', optnum);
                                optnum = 0;
                            }
                            else $('#' + elemId + '_count').attr('value', include);
                        } else {
                            optnum = 0;
                            /* лишаем возможности отправить форму */
                            if ($('#add2cart').length > 0) {
                                $('#add2cart').attr('disabled', true);
                            }
                            if ($('#add2cart-float').length > 0) {
                                $('#add2cart-float').hide();
                                $('#add2cart-float-empty').show();
                            }
                            $(countElem).addClass('error');
                        }
                        query_string += '.' + optnum;
                    }
                }
                else {
                    if(tmp[1] != 'none') {
                        query_string += '_' + optionCartNum;
                    }

                    /* элемент без поля ввода количества */
                    if (inPrice == 1 && include == 1) {
                        optnum = 0;
                    }
                }

                debugStr += 'plus ' + price + ' * ' + optnum + ' = ' + (price * optnum) + '\n';

                delta += price * optnum;
            }
            if (elem.nodeName.toLowerCase() == 'input' && (elem.type == 'radio' || elem.type == 'checkbox') && !elem.checked) {
                /* если есть поле для количества - очистим его */
                inPrice = parseInt(elem.getAttribute('inprice'));
                include = parseInt(elem.getAttribute('include'));
                price = parseFloat(elem.getAttribute('price'));
                optnum = parseInt(elem.getAttribute('optnum'));
                elemId = elem.getAttribute('id');
                countElem = document.getElementById(elemId + '_count');
                if (countElem) {
                    $(countElem).val('');
                }
                if (inPrice == 1 && include == 1) {
                    delta -= price * 1;
                    debugStr += 'minus inprice ' + price + ' * ' + 1 + ' = ' + (price * 1) + '\n';
                }
            }
        }

        if($('.right-buttons a.button').length) $('.right-buttons a.button').each(function(){
            var href = $(this).attr('href');
            if(!href) return;
            var debugStr = '';
            debugStr += 'href BEFORE = ' + href + '\n';
            if(href.match(/options=[_0-9,\,\.]+/)) href = href.replace(/options=[^&]+/, query_string);
            else href += '&'+query_string;
            debugStr += 'href AFTER  = ' + href + '\n';
            //console.log(debugStr);
            $(this).attr('href', href)
        });
//
//        /* Сгруппируем опции */
//        var groups = new Array();
//        var ipcGroups = new Array();
//        var j = k = 0;
//        for (i = 0; i < optForm.elements.length; i++) {
//            var elem = optForm.elements[i];
//            var inpGroup = elem.name;
//            if (elem.nodeName.toLowerCase() == 'input' && (elem.type == 'radio' || elem.type == 'checkbox')) {
//                inpGroup = inpGroup.replace(/option\[/, '');
//                inpGroup = parseInt(inpGroup.replace(/\]\[\]/, ''));
//                var groupKey = 'group' + inpGroup;
//                var inPrice = parseInt(elem.getAttribute('inprice'));
//                if (inPrice == 1 && elem.checked == true) {
//                    ipcGroups[groupKey] = true;
//                }
//                if (groups[groupKey] == null) {
//                    groups[groupKey] = new Array();
//                    k = 0;
//                }
//
//                groups[groupKey][k] = elem;
//                k++;
//            }
//        }
//
//        /* вычитаем те, что уже включены в цену (?) */
//        for (groupKey in groups) {
//            if (groups[groupKey].length > 0) {
//                for (i = 0; i < groups[groupKey].length; i++) {
//                    var elem = groups[groupKey][i];
//                    var inPrice = parseInt(elem.getAttribute('inprice'));
//                    var include = parseInt(elem.getAttribute('include'));
//                    var price = parseFloat(elem.getAttribute('price'));
//                    var optnum = parseInt(elem.getAttribute('optnum'));
//                    if ((ipcGroups[groupKey] == null || ipcGroups[groupKey] != true) && include == 1 && inPrice == 1) {
//                        //totalPrice -= price * optnum;
//                    }
//                }
//            }
//        }

        debugStr += 'delta ' + delta + '\n';

        totalPrice += delta;
        debugStr += 'result ' + totalPrice + '\n';

        //console.log(debugStr);

        var calculatedPrice = roundFloat(totalPrice, 2);
        if (isNaN(calculatedPrice)) {
            calculatedPrice = 'Call';
        }
        else {
            calculatedPrice = calculatedPrice.toFixed(2)  + ' ' + currency;
        }

        if (document.getElementById('prodPrice')) {
            document.getElementById('prodPrice').innerHTML = calculatedPrice;
        }
        if (document.getElementById('prodPrice1')) {
            document.getElementById('prodPrice1').innerHTML = calculatedPrice;
        }
        if (document.getElementById('prodPrice-float')) {
            document.getElementById('prodPrice-float').innerHTML = calculatedPrice;
        }
        if (document.getElementById('prodPrice-before')) {
            document.getElementById('prodPrice-before').innerHTML = calculatedPrice;
        }
    }
}

function addProductToCart(actionUri) {
    var optForm = document.forms['prodOptions'];
    var orderForm = document.forms['prodOrder'];
    if (optForm != null && orderForm != null) {
        for (i = 0; i < optForm.elements.length; i++) {
            var elem = optForm.elements[i];
            if (elem.nodeName.toLowerCase() == 'input' && (elem.type == 'radio' || elem.type == 'checkbox') && elem.checked) {
                var optElem = document.createElement('input');
                optElem.setAttribute('type', 'hidden');
                if (elem.name.indexOf('option') >= 0) {
                    optElem.setAttribute('name', 'options[]');
                }
                else {
                    optElem.setAttribute('name', elem.name);
                }
                optElem.setAttribute('value', elem.value);
                orderForm.appendChild(optElem);
            }
        }
    }
    if (actionUri != null) {
        orderForm.action = actionUri;
    }
    orderForm.submit();
}

function submitTo(formNode, toUri) {
    if (formNode != null && formNode.tagName.toLowerCase() == 'form') {
        formNode.action = toUri;
        formNode.submit();
    }
}

function roundFloat(number, precision) {
    return Math.round(number * Math.pow(10, precision)) / Math.pow(10, precision);
}

function markCheckbox(formName, nameSubstr, flag) {
    if (flag == null) {
        flag = true;
    }
    var cForm = document.forms[formName];
    if (cForm != null) {
        for (i = 0; i < cForm.elements.length; i++) {
            var elem = cForm.elements[i];
            if (elem.nodeName.toLowerCase() == 'input' && elem.type == 'checkbox' && elem.name.indexOf(nameSubstr) >= 0) {
                elem.checked = flag;
            }
        }
    }
}

function umarkCheckbox(formName, nameSubstr) {
    markCheckbox(formName, nameSubstr, false);
}

function checkMark(formName, nameSubstr, need) {
    var countMark = 0;
    var needMark = (need == null ? 1 : need);
    var cForm = document.forms[formName];
    if (cForm != null) {
        for (i = 0; i < cForm.elements.length; i++) {
            var elem = cForm.elements[i];
            if (elem.nodeName.toLowerCase() == 'input' && elem.type == 'checkbox' && elem.name.indexOf(nameSubstr) >= 0) {
                if (elem.checked == true) {
                    countMark++;
                }
            }
        }
    }
    
    if (countMark >= needMark) {
        return true;
    }
    return false;
}

function getURI(formName, nameSubstr, alias) {
    var cForm = document.forms[formName];
    var ret = '';
    if (cForm != null) {
        for (i = 0; i < cForm.elements.length; i++) {
            var elem = cForm.elements[i];
            if (elem.nodeName.toLowerCase() == 'input' && elem.type == 'checkbox' && elem.name.indexOf(nameSubstr) >= 0) {
                if (elem.checked == true) {
                    ret = ret + alias + '[' + elem.value + ']=0&';
                }
            }
        }
    }
    return ret;    
}

function addProducts2ToCart(formName, nameSubstr, toUri, errorStr) {
	var result = checkMark(formName, nameSubstr);
	if (result == false) {
		alert(errorStr);
	}
	else {
		submitTo(document.forms[formName], toUri);
	}
}

function prodCompare(formName, nameSubstr, alias, toUri, errorStr) {
	var result = checkMark(formName, nameSubstr, 2);
	if (result == false) {
		alert(errorStr);
	}
	else {
    var link = getURI(formName, nameSubstr, alias);
    window.location = toUri + '?' + link;
/*    
    document.forms[formName].method="get";
    submitTo(document.forms[formName], toUri);
*/    
  }
}

function allCheckboxMarked(formName, nameSubstr) {
    var countMark = countCheckbox = 0;
    var cForm = document.forms[formName];
    if (cForm != null) {
        for (i = 0; i < cForm.elements.length; i++) {
            var elem = cForm.elements[i];
            if (elem.nodeName.toLowerCase() == 'input' && elem.type == 'checkbox' && elem.name.indexOf(nameSubstr) >= 0) {
                if (elem.checked == true) {
                    countMark++;
                }
                countCheckbox++;
            }
        }
    }
    
    if (countMark == countCheckbox) {
        return true;
    }
    return false;
}

function quikFilterSubmit(formName, checkboxNameSubstr) {
    var allMarked = allCheckboxMarked(formName, checkboxNameSubstr);
    if (allMarked == true) {
        var hiddenFlag = document.createElement('input');
        hiddenFlag.type = 'hidden';
        hiddenFlag.name = 'all_marked';
        hiddenFlag.value = 1;
        document.forms[formName].appendChild(hiddenFlag);
    }
    document.forms[formName].submit();
}

function isDigit(e) {
    if (!e) {
        var e = window.event;
    }
    if (isIE || isOpera) {
        code = e.keyCode;
    }
    else {
        code = e.charCode;
    }
    return (((code >= 48) && (code <= 57)) || code == 46 || code == 45);
}

function calcsumm(obj, tdid, prc) {
    if (document.getElementById('std'+tdid).innerHTML != 'Call') {
    	re = /[^0-9]/g;
		obj.value = obj.value.replace(re, '');    	
      var value = Math.round(prc * obj.value * 100) / 100;
      if (!isNaN(value)) {
	      document.getElementById('std' + tdid).innerHTML = value;
      }
    }
}

function submOrd() {
    var mess = '';
    if (document.getElementById('country').value.length < 1) {
        mess += ' - {$lang.Order_country}\n';
    }
    if (document.getElementById('zip').value.length < 1) {
        mess += ' - {$lang.Order_zip}\n';
    }
    if (document.getElementById('region').value.length < 1) {
        mess += ' - {$lang.Order_region}\n';
    }
    if (document.getElementById('city').value.length < 1) {
        mess += ' - {$lang.Order_city}\n';
    }
    if (document.getElementById('addres').value.length < 1) {
        mess += ' - {$lang.Order_addres}\n';
    }
    if (document.getElementById('phone').value.length < 1) {
        mess += ' - {$lang.Order_phone}\n';
    }
    if (document.getElementById('email').value.length < 1) {
        mess += ' - {$lang.Order_email}\n';
    }
    if (document.getElementById('contact').value.length < 1) {
        mess += ' - {$lang.Order_contact}\n';
    }
    if (mess.length > 0) {
        alert('Заполните, пожалуйста, обязательные поля:\n' + mess);
        return false;
    }
    re = new RegExp("^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$");
    if (re.exec(document.getElementById('email').value)) {
        return true;
    }
	alert('Не верно заполнено поле Email.');
    return false;
}

function setFilterFormAction(selectElem, filterPage) {
    var formAction = selectElem.options[selectElem.options.selectedIndex].getAttribute('path') + filterPage;
    selectElem.form.action = formAction;
    return true;
}

$(document).ready(function() {
    // Making bottom blocks equal height
    var el1 = $('div.orange-block div.opros-block .rb');
    var el2 = $('div.orange-block div.news-block:eq(0) .rb');
    var el3 = $('div.orange-block div.news-block:eq(1) .rb');
    if (el1.size() > 0) {
        var h1 = el1.height() || 0;
        var h2 = el2.height() || 0;
        var h3 = el3.height() || 0;

        var max = 0;
        if (h1 > h2 && h1 > h3) {
            max = h1;
        } else if (h3 > h1 && h3 > h2) {
            max = h3;
        }
        else {
            max = h2;
        }
        if (h1) el1.height(max);
        if (h2) el2.height(max);
        if (h3) el3.height(max);

    }
    
    if($('.expand').length && $('.collapse').length) {
        $('.expand a').click(function(){
            $('.expand').hide();
            $('.expand').parent().find('.collapse').show();
            return false;
        });
        $('.collapse a').click(function(){
            $('.collapse').hide();
            $('.collapse').parent().find('.expand').show();
            return false;
        });
    }
});


