

var artEventHelper = {
  'bind' : function (obj, evt, fn) {
    if (obj.addEventListener)
      obj.addEventListener(evt, fn, false);
    else if (obj.attachEvent)
      obj.attachEvent('on' + evt, fn);
    else
      obj['on' + evt] = fn;
  }
};

var artLoadEvent = (function() {
  var userAgent = navigator.userAgent.toLowerCase();
  var browser = {
    version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
    safari: /webkit/.test(userAgent),
    opera: /opera/.test(userAgent),
    msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
    mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
  };

  var list = [];

  var done = false;
  var ready = function () {
    if (done) return;
    done = true;
    for (var i = 0; i < list.length; i++)
      list[i]();
  };

  if (document.addEventListener && !browser.opera)
    document.addEventListener('DOMContentLoaded', ready, false);

  if (browser.msie && window == top) {
    (function () {
      try {
        document.documentElement.doScroll('left');
      } catch (e) {
        setTimeout(arguments.callee, 10);
        return;
      }
      ready();
    })();
  }

  if (browser.opera) {
    document.addEventListener('DOMContentLoaded', function () {
      for (var i = 0; i < document.styleSheets.length; i++) {
        if (document.styleSheets[i].disabled) {
          setTimeout(arguments.callee, 10);
          return;
        }
      }
      ready();
    }, false);
  }

  if (browser.safari) {
    var numStyles;
    (function(){
      if (document.readyState != 'loaded' && document.readyState != 'complete') {
        setTimeout(arguments.callee, 10);
        return;
      }
      if ('undefined' == typeof numStyles) {
        numStyles = document.getElementsByTagName('style').length;
        var links = document.getElementsByTagName('link');
        for (var i = 0; i < links.length; i++) {
          numStyles += (links[i].getAttribute('rel') == 'stylesheet') ? 1 : 0;
        }
        if (document.styleSheets.length != numStyles) {
          setTimeout(arguments.callee, 0);
          return;
        }
      }
      ready();
    })();
  }

  artEventHelper.bind(window, 'load', ready);

  return ({
    add: function(f) {
      list.push(f);
    }
  })
})();

(function () {
  // fix ie blinking
  var m = document.uniqueID && document.compatMode && !window.XMLHttpRequest && document.execCommand;
  try{ if(!!m) { m("BackgroundImageCache", false, true); } }
  catch(oh){};
})();

function xGetElementsByClassName(clsName, parentEle, tagName) {
  var elements = null;
  var found = [];
  var slash = String.fromCharCode(92);
  var re = new RegExp(slash + "b" + clsName + slash + "b");
  if (!parentEle) parentEle = document;
  if (!tagName) tagName = '*';
  elements = parentEle.getElementsByTagName(tagName);
  if (elements) {
    for (var i = 0; i < elements.length; ++i) {
      if (elements[i].className.search(re) != -1) {
        found[found.length] = elements[i];
      }
    }
  }
  return found;
}

var styleUrlCached = null;
function GetStyleUrl() {
  if (null == styleUrlCached) {
    var ns;
    styleUrlCached = '';
    ns = document.getElementsByTagName('link');
    for (var i = 0; i < ns.length; i++) {
      var l = ns[i];
      if (l.href && /style\.css(\?.*)?$/.test(l.href)){
        return styleUrlCached = l.href.replace(/style\.css(\?.*)?$/,'');
      }
    }

    ns = document.getElementsByTagName('style');
    for (var i = 0; i < ns.length; i++) {
      var matches = new RegExp('import\\s+"([^"]+\\/)style\\.css"').exec(ns[i].innerHTML);
      if (null != matches && matches.length > 0)
        return styleUrlCached = matches[1];
    }
  }
  return styleUrlCached;
}


function artButtonSetupJsHover(btn)
{
    artEventHelper.bind(btn, 'mouseover', function() {
        var spans = btn.getElementsByTagName("span");
        if (spans.length > 0)
            spans[0].className += " hover";
    });
    artEventHelper.bind(btn, 'mouseout', function() {
        var spans = btn.getElementsByTagName("span");
        if (spans.length > 0)
            spans[0].className = spans[0].className.replace(/hover/, "").replace(/active/, "");
    });
    artEventHelper.bind(btn, 'mousedown', function() {
        var spans = btn.getElementsByTagName("span");
        if (spans.length > 0)
            spans[0].className += " active";
    });
    artEventHelper.bind(btn, 'mouseup', function() {
        var spans = btn.getElementsByTagName("span");
        if (spans.length > 0)
            spans[0].className = spans[0].className.replace(/active/, "");
    });
}

function artButtonsSetupJsHover() {
  var elements = xGetElementsByClassName("btn", document, "span");
  for (var i = 0; i < elements.length; i++) {
    if (!elements[i].tagName) continue;
    artButtonSetupJsHover(elements[i].parentNode);
  }
}
artLoadEvent.add(artButtonsSetupJsHover);

/* end Page */

/* begin Menu */
function Insert_Separators()
{
  var menus = xGetElementsByClassName("artmenu", document);
  for (var i = 0; i < menus.length; i++) {
    var menu = menus[i];
    var childs = menu.childNodes;
    var listItems = [];
    for (var j = 0; j < childs.length; j++){
      var el = childs[j];
      if (String(el.tagName).toLowerCase() == "li")listItems.push(el);
    }
    for (var j = 0; j < listItems.length - 1; j++){
      var span = document.createElement('span');
      span.className = 'separator';
      var li = document.createElement('li');
      li.appendChild(span);
      listItems[j].parentNode.insertBefore(li, listItems[j].nextSibling);
    }
  }
}
artLoadEvent.add(Insert_Separators);

function Menu_IE6Setup() {
  var isIE6 = navigator.userAgent.toLowerCase().indexOf("msie") != -1
    && navigator.userAgent.toLowerCase().indexOf("msie 7") == -1;
  if (!isIE6) return;
  var aTmp2, i, j, oLI, aUL, aA;
  var aTmp = xGetElementsByClassName("artmenu", document, "ul");
  for (i=0;i<aTmp.length;i++) {
    aTmp2 = aTmp[i].getElementsByTagName("li");
    for (j=0;j<aTmp2.length;j++) {
      oLI = aTmp2[j];
      aUL = oLI.getElementsByTagName("ul");
      if (aUL && aUL.length) {
        oLI.UL = aUL[0];
        aA = oLI.getElementsByTagName("a");
        if (aA && aA.length)
        	oLI.A = aA[0];
         oLI.onmouseenter = function() {
         	this.className += " artmenuhover";
         	this.UL.className += " artmenuhoverUL";
         	if (this.A) this.A.className += " artmenuhoverA";
         };
        oLI.onmouseleave = function() {
          this.className = this.className.replace(/artmenuhover/,"");
          this.UL.className = this.UL.className.replace(/artmenuhoverUL/,"");
          if (this.A) this.A.className = this.A.className.replace(/artmenuhoverA/, "");
        };
      }
    }
  }
}
artLoadEvent.add(Menu_IE6Setup);
/* end Menu */

/* AJAX */

function doLoad(value)
{
    document.getElementById('price').innerHTML='<img src="images/loading.gif" alt="" />';
    var req = new JsHttpRequest();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
			if (req.status == 200 || req.status == 201)
			{
					if (req.responseJS.ans != '')
					 {
                        if(req.responseJS.ans=='error')
                        {                        	return;
                        }
                        var tmp=req.responseJS.ans.split('|');
                        document.getElementById('btn').innerHTML=tmp[0];
                        document.getElementById('price').innerHTML=tmp[1];
                        return;
					 }
			}
         }
	}

    req.open("POST", 'be.php', true);
    req.setRequestHeader('Connection', 'close');
    req.send( { q: value } );
}

function modelChange()
{ 	var mod = document.getElementById('name').value;
 	if(mod=='-')
 	{ 		document.getElementById('btn').innerHTML='';
		document.getElementById('price').innerHTML='0';
 		return;
 	}
 	var re=/^\d+$/;
	if(!re.test(mod))
	{
    	return;
	}
	document.getElementById('model').value=mod;
	document.getElementById('chac').value='mod';
	document.getElementById('mcnt').value='1';
	document.getElementById('cnt').value='1';
	doLoad(document.getElementById('clcfrm'));
}

function calculate()
{	var cnt=document.getElementById('cnt');
	var re=/^\d+$/;
	if(!re.test(cnt.value))
	{		cnt.value='0';
		document.getElementById('price').innerHTML='0';
		alert('Пожалуйста, укажите числовое значение.');
		return;
	}
	if(cnt.value=='0')
	{		document.getElementById('price').innerHTML='0';
		return;
	}
	document.getElementById('mcnt').value=cnt.value;
	document.getElementById('chac').value='cnt';
	doLoad(document.getElementById('clcfrm'));
}
/* end AJAX */
function sendOrder()
{
	if (trim(document.getElementById('customer').value) == '')
	{		alert('Пожалуйста, укажите, как Вас зовут.');
		return;
	}
	if (trim(document.getElementById('mail').value) == '' && trim(document.getElementById('phone').value) == '')
	{		alert('Пожалуйста, укажите, как с Вами можно связаться.');
		return;
	}
	if (trim(document.getElementById('name').value) == '-')
	{		alert('Пожалуйста, выберите модель.');
		return;
	}
	if (document.getElementById('cnt').value < 1)
	{
		alert('Количество не может быть меньше 1.');
		return;
	}
	document.getElementById('mord').value='1';
	document.getElementById('order').submit();

}

function trim (str) {
   var newstr = str.replace(/^\s*(.+?)\s*$/, "$1");
    if (newstr == " ") {
        return "";
    }
    return newstr;
}

/*-------------------------------modal-------------------------------------------------*/
var popupStatus = 0;

function loadPopup(){
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("slow");
		$("#popup").fadeIn("slow");
		popupStatus = 1;
	}
}

function disablePopup(){
	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("slow");
		$("#popup").fadeOut("slow");
		popupStatus = 0;
	}
}

function centerPopup(){

	var tmp =getPageSize();
	var windowWidth = tmp[2];
	var windowHeight = tmp[3];
	var pageHeight = tmp[1];
	var popupHeight = $("#popup").height();
	var popupWidth = $("#popup").width();
	$("#popup").css({
		"position": "absolute",
		"top": (windowHeight/2-popupHeight/2)+document.documentElement.scrollTop,
		"left": (windowWidth/2-popupWidth/2)+document.documentElement.scrollLeft
	});
	$("#backgroundPopup").css({
		"height": pageHeight
	});
}

function showFull(img,wid,hei)
{
	var popup=document.getElementById('popup');
	popup.innerHTML='<center><a class="ma"><img src="images/'+img+'.jpg" alt="Закрыть" onclick="disablePopup();" style="cursor:hand;cursor:pointer;" /><span>Нажмите, чтобы закрыть.</span></a></center><p style="font-family:Tahoma;font-size:18px;">Вы можете приобрести у нас оригинальный подарок для автомобилистов - биту-блокиратор руля.</p><p style="font-family:Tahoma;font-size:18px;">Цена составляет <b><font color="red">1500</font></b> рублей.<br />Сделать заказ можно по телефону <b>+7 (916) 445 7935</b>, либо написав письмо на адрес <a href="mailto:info@superdefender.ru" title="">info@superdefender.ru</a></b></p> ';
	popup.style.width=wid;
	popup.style.height=hei;
	centerPopup();
	loadPopup();
}

function  getPageSize(){
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
		xScroll = document.documentElement.scrollWidth;
		yScroll = document.documentElement.scrollHeight;
	} else { // Explorer Mac...would also work in Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) { // all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	return [pageWidth,pageHeight,windowWidth,windowHeight,xScroll,yScroll];
}
