////////////////////////// Подключаем Ajax //////////////////////////
var xmlHttp = false;
try
{
	 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
	try
	{
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	catch (e2)
	{
		xmlHttp = false;
	}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined'){
	xmlHttp = new XMLHttpRequest();
}

////////////////////////// Общие функции //////////////////////////
function getwindowHeight(){
	var windowHeight;
	if(window.innerHeight){ 
		windowHeight=window.innerHeight; 
	} else if(document.documentElement && document.documentElement.clientHeight){ 
		windowHeight=document.documentElement.clientHeight; 
	} else if(document.body){ 
		windowHeight=document.body.clientHeight; 
	}
	return windowHeight;
}

function getwindowWidth(){
	var windowWidth;
	if(window.innerWidth){ 
		windowWidth=window.innerWidth; 
	} else if(document.documentElement && document.documentElement.clientWidth){ 
		windowWidth=document.documentElement.clientWidth; 
	} else if(document.body){ 
		windowWidth=document.body.offsetWidth; 
	}
	return windowWidth;
}

function showBlock(name){
	var o = document.getElementById(name);
	if ('none' == o.style.display){
		o.style.display = '';
	}else{
		o.style.display = 'none';
	}
}

function getAttributes(node){   
	var ret = new Object();   
	if(node.attributes){ 
		for(var i=0; i<node.attributes.length; i++){   
			var attr = node.attributes[i];   
			ret[attr.name] = attr.value;   
		}
	}  
	return ret;   
}

function getElemText(node){
        return node.text || node.textContent || (function(node){
                var _result = "";
                if (node == null) {
                        return _result;
                }
                var childrens = node.childNodes;
                var i = 0;
                while (i < childrens.length) {
                        var child = childrens.item(i);
                        switch (child.nodeType) {
                                case 1: // ELEMENT_NODE
                                case 5: // ENTITY_REFERENCE_NODE
                                        _result += arguments.callee(child);
                                        break;
                                case 3: // TEXT_NODE
                                case 2: // ATTRIBUTE_NODE
                                case 4: // CDATA_SECTION_NODE
                                        _result += child.nodeValue;
                                        break;
                        }
                        i++;
                }
                return _result;
        }(node));
 }

////////////////////////// Авторизация //////////////////////////
function autorize(){
	poststr = "login="+document.getElementById("login").value+"&pass="+document.getElementById("pass").value;
	url='/scripts/autorization.class.php';
	xmlHttp.open('POST', url);
	xmlHttp.onreadystatechange = resultAutorize;
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", poststr.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(poststr);
}

function resultAutorize(){
	if (xmlHttp.readyState == 4) {
		var response = xmlHttp.responseText;
		if(response == 'ok') {window.location.reload();}
		else {alert('Указанные данные не найдены!')}
		xmlHttp.abort();
	}
}

function unautorize()
{
	poststr = "null";
	url='/scripts/unautorization.class.php';
	xmlHttp.open('POST', url);
	xmlHttp.onreadystatechange = resultUnAutorize;
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", poststr.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(poststr);
}
		//Обработка ответа сервера на создание нового документа
function resultUnAutorize() {
	if (xmlHttp.readyState == 4) {
		window.location.reload();
		xmlHttp.abort();
	}
}

////////////////////////// Функции для товара //////////////////////////
function addBasket(product_id){
	if(document.getElementById("is_different_eyes").checked){
		var cnt_left = document.getElementById("cnt_left").value;
		var curvature_left = document.getElementById("curvature_left").value;
		var optic_left = document.getElementById("optic_left").value;
		var color_left = document.getElementById("color_left").value;

		var cnt_right = document.getElementById("cnt_right").value;
		var curvature_right = document.getElementById("curvature_right").value;
		var optic_right = document.getElementById("optic_right").value;
		var color_right = document.getElementById("color_right").value;
		var poststr = "";

		if(cnt_left){
			poststr += "&cnt_left=" + cnt_left + "&curvature_left=" + curvature_left + "&optic_left=" + optic_left + "&color_left=" + color_left;
		}
		if(cnt_right){
			poststr += "&cnt_right=" + cnt_right + "&curvature_right=" + curvature_right + "&optic_right=" + optic_right + "&color_right=" + color_right;
		}
		if(poststr != ""){
			poststr = "product_id=" + product_id + "&is_different_eyes=1" + poststr;
			url='/scripts/addbasket.class.php';
			SendRequest("post", url, poststr, resultAddBasket);
		}
	}else{
		var cnt_all = document.getElementById("cnt_all").value;
		var curvature_all = document.getElementById("curvature_all").value;
		var optic_all = document.getElementById("optic_all").value;
		var color_all = document.getElementById("color_all").value;
		var poststr = "";

		if(cnt_all){
			poststr += "&cnt_all=" + cnt_all + "&curvature_all=" + curvature_all + "&optic_all=" + optic_all + "&color_all=" + color_all;
		}
		if(poststr){
			poststr = "product_id=" + product_id + "&is_different_eyes=0" + poststr;
			url='/scripts/addbasket.class.php';
			SendRequest("post", url, poststr, resultAddBasket);
		}
	}
	//xmlHttp.open('POST', url);
	//xmlHttp.onreadystatechange = resultAddBasket;
	//xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//xmlHttp.setRequestHeader("Content-length", poststr.length);
	//xmlHttp.setRequestHeader("Connection", "close");
	//xmlHttp.send(poststr);
}
		//Обработка ответа сервера на создание нового документа
function resultAddBasket(Request) {
	var response = Request.responseText;
	document.getElementById("divbskt").innerHTML = response;
	document.getElementById("tdbasketref").innerHTML = '<a href="/basket/" style="font-size:9px; color:#fff;">оформить заказ</a>';
	if(confirm("Товар добавлен. Вы хотите перейти к оформлению заказа сейчас?")){
		window.location = "http://www.lensation.ru/basket/";
	}else{
		return '';
	}
}

function isDifferentEyes(){
	if(document.getElementById("is_different_eyes").checked){
		document.getElementById('tbl_different_eyes').style.display = '';
		document.getElementById('tbl_notdifferent_eyes').style.display = 'none';
	}else{
		document.getElementById('tbl_different_eyes').style.display = 'none';
		document.getElementById('tbl_notdifferent_eyes').style.display = '';
	}
}

function selectCurvature(item, type, product_id){
	if(item){
		poststr = "section=tovar&action=get_optic&curvature=" + item + "&type=" + type + "&product_id=" + product_id;
		url='/detail.php';
		SendRequest("post", url, poststr, resultSelectCurvature);
	}else{
		var objSel = document.getElementById('optic_' + type);
		objSel.options.length=1; //добавляем в конец списка пустой элемент
		objSel.options[0].text = "-";
	}
	//xmlHttp.open('POST', url);
	//xmlHttp.onreadystatechange = resultSelectCurvature;
	//xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//xmlHttp.setRequestHeader("Content-length", poststr.length);
	//xmlHttp.setRequestHeader("Connection", "close");
	//xmlHttp.send(poststr);
}

function resultSelectCurvature(Request){
//alert(xmlHttp.responseText);
	xmlDocumentElement = Request.responseXML.documentElement;
	var optic = xmlDocumentElement.getElementsByTagName('o');
	var type = xmlDocumentElement.getElementsByTagName('type');
	var valueType = getElemText(type[0]);
	if(optic){
		var objSel = document.getElementById('optic_' + valueType);
		for(var i=0; i<optic.length; i++){
			var valueRegion = getAttributes(optic[i]);
//alert(valueRegion['id']);
			objSel.options[i+1] = new Option(getElemText(optic[i]), getElemText(optic[i]));
		}
	}
}

////////////////////////// Управление прозрачностью //////////////////////////
function setElementOpacity(sElemId, nOpacity)
{
  var opacityProp = getOpacityProperty();
  var elem = document.getElementById(sElemId);

  if (!elem || !opacityProp) return; // Если не существует элемент с указанным id или браузер не поддерживает ни один из известных функции способов управления прозрачностью
  
  if (opacityProp=="filter")  // Internet Exploder 5.5+
  {
    nOpacity *= 100;
	
    // Если уже установлена прозрачность, то меняем её через коллекцию filters, иначе добавляем прозрачность через style.filter
    var oAlpha = elem.filters['DXImageTransform.Microsoft.alpha'] || elem.filters.alpha;
    if (oAlpha) oAlpha.opacity = nOpacity;
    else elem.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity="+nOpacity+")"; // Для того чтобы не затереть другие фильтры используем "+="
  }
  else // Другие браузеры
    elem.style[opacityProp] = nOpacity;
}

function getOpacityProperty()
{
  if (typeof document.body.style.opacity == 'string') // CSS3 compliant (Moz 1.7+, Safari 1.2+, Opera 9)
    return 'opacity';
  else if (typeof document.body.style.MozOpacity == 'string') // Mozilla 1.6 и младше, Firefox 0.8 
    return 'MozOpacity';
  else if (typeof document.body.style.KhtmlOpacity == 'string') // Konqueror 3.1, Safari 1.1
    return 'KhtmlOpacity';
  else if (document.body.filters && navigator.appVersion.match(/MSIE ([\d.]+);/)[1]>=5.5) // Internet Exploder 5.5+
    return 'filter';

  return false; //нет прозрачности
}

////////////////////////// Управление акциями //////////////////////////
function showImageAction(imgSrc, productId, productName){
	var html = '';
	//html += '<div style="font-size:12px; color:#0047B3; font-weight:bold; margin-bottom:10px;">' + productName + '</div>';
	html += '<a href="/product/' + productId + '.html"><img src="' + imgSrc + '" width="240px" height="200px" border="0"></a>';
	document.getElementById('tdactionimg').innerHTML = html;
}