$(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);
    }
});
lastExpanded = 0;
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()
{
    frm = document.forms['personal'];
    pass1 = document.forms['personal']['password'];
    pass2 = document.forms['personal']['password2'];
    msg = document.getElementById('passEqual');
    if(pass1.value == pass2.value && pass1.value != '') msg.style.visibility = 'visible';
    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';
    }
  }
  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() {
    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;

        if (currency == undefined) currency='';
        
        if (totalPrice == 0)
        {
          if (document.getElementById('prodPrice')) document.getElementById('prodPrice').innerHTML = "Call";
      	  if (document.getElementById('prodPrice1')) document.getElementById('prodPrice1').innerHTML = "Call";        
      	  return;
        }
        
        // Прибавляем все отмеченные опции кроме тех, что помечены как 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 inPrice = parseInt(elem.getAttribute('inprice'));
                var price = parseFloat(elem.getAttribute('price'));
                var optnum = parseInt(elem.getAttribute('optnum'));
                if (inPrice != 1) {
                    totalPrice += price * optnum;
                }
            }
        }
        
        // Сгруппируем опции

        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(/\]\[\]/, ''));
                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;
                    }
                }
            }
        }
        
        if (document.getElementById('prodPrice')) document.getElementById('prodPrice').innerHTML = roundFloat(totalPrice, 2) + ' ' + currency;
	if (document.getElementById('prodPrice1')) document.getElementById('prodPrice1').innerHTML = roundFloat(totalPrice, 2) + ' ' + currency;
    }
}

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;
}
