var loading = new Image();
loading.src = host + "/sitedesign/images/load.gif";

var colors = new Array();
colors[0] = "#000";
colors[1] = "#111";
colors[2] = "#222";
colors[3] = "#333";
colors[4] = "#444";
colors[5] = "#555";
colors[6] = "#666";
colors[7] = "#777";
colors[8] = "#888";
colors[9] = "#999";
colors[10] = "#AAA";
colors[11] = "#BBB";
colors[12] = "#CCC";
colors[13] = "#DDD";
colors[14] = "#EEE";
colors[15] = "#FFF";
var borders = new Array();
borders[0] = "#F7EB11";
borders[1] = "#E2DA2C";
borders[2] = "#E3DD33";
borders[3] = "#E5E03D";
borders[4] = "#E7E448";
borders[5] = "#E8E755";
borders[6] = "#EAE962";
borders[7] = "#EBEC70";
borders[8] = "#EDEF7E";
borders[9] = "#EFF08E";
borders[10] = "#F0F29D";
borders[11] = "#F2F5AC";
borders[12] = "#F4F7BC";
borders[13] = "#F7F9CD";
borders[14] = "#F9FCCD";
borders[15] = "#FFF";

var isIE = false; // надеемся на лучшее
if(navigator.userAgent.indexOf('MSIE') != -1 && navigator.userAgent.indexOf('Opera') == -1)
{
	isIE = true;// но сталкиваемся с суровой реальностью
}

// объект vxml
var vxml = {
	useActiveX: typeof ActiveXObject != 'undefined',
	useXMLHTTP: typeof XMLHttpRequest != 'undefined'
}

vxml.XMLHTTP_Versions = [ 'MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP' ];

// объект vXMLHTTP, посредством этого объекта происходит вся работа
function vXMLHTTP() {}

vXMLHTTP.createRequest = function()
{
	if( vxml.useXMLHTTP == true )
	{
		return new XMLHttpRequest();
	}
	else if( vxml.useActiveX == true )
	{
		if( !vxml.XMLHTTP_Version )
		{
			for( var i = 0; i < vxml.XMLHTTP_Versions.length; i++ )
			{
				try
				{
					new ActiveXObject( vxml.XMLHTTP_Versions[i] );
					vxml.XMLHTTP_Version = vxml.XMLHTTP_Versions[i];
					break;
				}
				catch( error )
				{}
			}
		}
		if( vxml.XMLHTTP_Version )
		{
			return new ActiveXObject( vxml.XMLHTTP_Version );
		}
		else
		{
			throw new Error( 'Невозможно создать запрос XMLHTTP' );
		}
	}
	else
	{
		throw new Error( 'Ваш браузер не поддерживает AJAX' );
	}
}

function sendRequest( action, pid )
{
if (action != 'add') {
	if( isIE == false )
	{
		var n = document.getElementById('loading');
		if( n )
		{
			n.parentNode.removeChild( n );
		}
		h = window.scrollY + screen.availHeight / 2 - 54;
		var icon = document.createElement('div');
		icon.id = 'loading';
		icon.style.top = h+'px';
		icon.style.left = '50%';
		icon.style.position = 'absolute';
		icon.style.zIndex = '10000';
		icon.style.border = '2px solid #F7EB11';
		icon.style.width = '50px';
		icon.style.height = '40px';
		icon.style.marginLeft = '-27px';
		icon.style.background = '#FFF';
		icon.style.textAlign = 'center';
		icon.style.paddingTop = '10px';
		var animation = document.createElement('img');
		animation.src = loading.src;
		icon.appendChild(animation);
//	var b = document.getElementById('page');
//	b.appendChild(icon);
		var b = document.getElementsByTagName( 'body' );
		b[0].appendChild( icon );
	}
	else
	{
		var n = document.getElementById('loading');
		if( n )
		{
			n.parentNode.removeChild( n );
		}
//		h = window.scrollY + screen.availHeight / 2 - 54;
		h = (document.documentElement.scrollTop+300)+'px';
		var icon = document.createElement('div');
		icon.id = 'loading';
		var b = document.getElementsByTagName( 'body' );
		b[0].appendChild( icon );
		icon.style.top = h;
		icon.style.left = '50%';
		icon.style.position = 'absolute';
		icon.style.zIndex = '10000';
		icon.style.border = '2px solid #F7EB11';
		icon.style.width = '50px';
		icon.style.height = '40px';
		icon.style.marginLeft = '-27px';
		icon.style.background = '#FFF';
		icon.style.textAlign = 'center';
		icon.style.paddingTop = '10px';
		var animation = document.createElement('img');
		animation.src = loading.src;
		icon.appendChild(animation);
//	var b = document.getElementById('page');
//	b.appendChild(icon);
		/**/
	}
}

	var params = new Array();
	var address = '';
	var param = '';
	var sbody = '';
    var handler = '';
    var async = true;
	switch(action)
	{
		case 'add':
			/*var pcount = document.getElementById('addProduct'+pid).value;
			pcount = pcount.replace( /,/, '.' );
			pcount = ( pcount == '' || NaN == parseFloat(pcount) ) ? 1 : parseFloat(pcount);
			document.getElementById('addProduct'+pid).value = '';*/
			var pcount = 1;
			param = encodeURIComponent( 'pid' );
			param += "=" + encodeURIComponent( pid );
			params.push(param);
			param = encodeURIComponent( 'pcount' );
			param += "=" + encodeURIComponent( pcount );
			params.push(param);
            var chb = document.getElementById('connect');
            if( chb && chb.checked )
            {// добавить в корзину тариф
                param = encodeURIComponent( 'apid' );
                param += "=" + encodeURIComponent( document.getElementById('tarif').options[document.getElementById('tarif').selectedIndex].value );
                params.push(param);
            }
			param = encodeURIComponent( 'time' );
			param += "=" + encodeURIComponent( time+Math.random() );
			params.push(param);
			sbody = params.join("&");
			address = host+'/index.php/trade/j_add2cart/';//?pid='+pid+'&pcount='+pcount+ua+'&time='+time+Math.random();

	if( isIE == false )
	{
		var n = document.getElementById('messagebox');
		if( n )
		{
			n.parentNode.removeChild( n );
		}
		var msg = document.createElement('div');
		msg.id = 'messagebox';
		msg.style.zIndex = '20000';
		msg.style.border = '1px solid #000';
		msg.style.width = '400px';
		msg.style.height = '150px';
		msg.style.marginLeft = '-27px';
		msg.style.textAlign = 'center';
		msg.style.paddingTop = '10px';
		msg.style.display = 'block';
		msg.innerHTML = '<table width="100%"><tr><th>&nbsp;</th><tr><td align="middle" valign="middle"><font size=5>Товар добавлен в корзину<br><br><a href="http://www.eolis.ru/index.php/trade/cart/">Оформить заказ</a>&nbsp;&nbsp;<a href="javascript:void(0);" onclick="hideMessageBox();">Продолжить</a></font></td></tr></table>';
		msgdiv = document.getElementById('msgdiv');
		document.body.insertBefore(msg, msgdiv);
	}
	else
	{
		var n = document.getElementById('messagebox');
		if( n )
		{
			n.parentNode.removeChild( n );
		}
		left = screen.availWidth / 2 - 200;
		var icon = document.createElement('div');
		icon.id = 'messagebox';
		var b = document.getElementsByTagName( 'body' );
		b[0].appendChild( icon );
		icon.style.left = left + 'px';
		icon.style.zIndex = '10000';
		icon.style.border = '1px solid #000';
		icon.style.width = '400px';
		icon.style.height = '150px';
		icon.style.marginLeft = '-27px';
		icon.style.background = '#FFF';
		icon.style.textAlign = 'center';
		icon.style.paddingTop = '10px';
		//var animation = document.createElement('img');
		//animation.src = loading.src;
		//icon.appendChild(animation);
		icon.innerHTML = '<table width="100%"><tr><th>&nbsp;</th><tr><td align="middle" valign="middle"><font size=5>Товар добавлен в корзину<br><br><a href="http://www.eolis.ru/index.php/trade/cart/">Оформить заказ</a>&nbsp;&nbsp;<a href="javascript:void(0);" onclick="hideMessageBox();">Продолжить</a></font></td></tr></table>';
//	var b = document.getElementById('page');
//	b.appendChild(icon);
	}

			break;
		case 'remove':
			param = encodeURIComponent( 'pid' );
			param += "=" + encodeURIComponent( pid );
			params.push(param);
			param = encodeURIComponent( 'time' );
			param += "=" + encodeURIComponent( time+Math.random() );
			params.push(param);
			sbody = params.join("&");
			address = host+'/index.php/trade/j_removefromcart/';//?pid='+pid+ua+'&time='+time+Math.random();
			break;
		case 'emptyCart':
			address = host+'/index.php/trade/j_emptycart/';
			break;
		case 'getModels':
			param = encodeURIComponent( 'cid' );
			param += "=" + encodeURIComponent( pid );
			params.push(param);
			param = encodeURIComponent( 'time' );
			param += "=" + encodeURIComponent( time+Math.random() );
			params.push(param);
			sbody = params.join("&");
			address = host+'/index.php/trade/j_getmodels/';
			break;
		case 'vote':
			param = encodeURIComponent( 'pid' );
			param += "=" + encodeURIComponent( pid );
			params.push(param);
			param = encodeURIComponent( 'mark' );
			param += "=" + encodeURIComponent(document.getElementById('mark').value);
			params.push(param);
			param = encodeURIComponent( 'time' );
			param += "=" + encodeURIComponent( time+Math.random() );
			params.push(param);
			sbody = params.join("&");
			address = host+'/index.php/trade/j_vote/';
			break;
        case 'tarif':
            param = encodeURIComponent( 'operator' );
            pid = escapeToCode( pid );
            param += "=" + encodeURIComponent( pid );
            params.push(param);
            param = encodeURIComponent( 'time' );
            param += "=" + encodeURIComponent( time+Math.random() );
            params.push(param)
            sbody = params.join("&");
            address = host+'/index.php/trade/j_tarif/';
            break;
        case 'tarifchange':
            handler = 'saveRequest1';
            param = encodeURIComponent( 'tarif' );
            param += "=" + encodeURIComponent( pid );
            params.push(param);
            param = encodeURIComponent( 'time' );
            param += "=" + encodeURIComponent( time+Math.random() );
            params.push(param)
            sbody = params.join("&");
            address = host+'/index.php/trade/j_tarifchange/';
            async = false;
            break;
	}

	var oXmlHTTP = vXMLHTTP.createRequest();
	oXmlHTTP.open( "post", address, async );
	oXmlHTTP.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
	if( async )
	{
		oXmlHTTP.onreadystatechange = function()
		{
			if(oXmlHTTP.readyState == 4 )
			{
				if(oXmlHTTP.status == 200)
				{
	//				setTimeout( saveRequest(oXmlHTTP.responseText), 10000 );
					if( handler == '' )
					{
						saveRequest(oXmlHTTP.responseText);
					}
					else
					{
						saveRequest1(oXmlHTTP.responseText);
					}

				}
				else
				{
					if( handler == '' )
					{
						saveRequest("Error: " + oXmlHTTP.statusText);
					}
					else
					{
						saveRequest1("Error: " + oXmlHTTP.statusText);
					}
				}
			}
		}
		oXmlHTTP.send(sbody);
	}
	else
	{
		oXmlHTTP.send(sbody);
		saveRequest1(oXmlHTTP.responseText);
	}
}

function getBodyScrollTop(){
	return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

function getClientHeight(){
	return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function handleRequestStateChange()
{
	if( xmlHttp.readyState == 4 )
	{
		if( xmlHttp.status == 200 )
		{
			try
			{
				handleServerResponse();
            }
            catch(e)
			{
	            alert( 'Ошибка чтения ответа '+ e.toString() );
            }
        }
        else
		{
	        alert( 'Возникли проблемы при получении данных:\n'+ xmlHttp.statusText+'\nПопробуйте сменить браузер\n Рекомендуем использовать Mozilla Firefox' );
        }
	}
}
function saveRequest( response )
{
	//if( isIE == false )
	setTimeout( "{ var n = document.getElementById('loading'); if( n ) { n.parentNode.removeChild( n ); } }", 2000 );
//	alert(response);
//	response = escapeToWin1251(response);
//	alert(response);
//	response = unescape(response)
//	alert(response);
	var parts = response.split( '|||' );
	contentHolder = document.getElementById( parts[0].substr( 1, parts[0].length - 2 ) );
	if( isIE == false )
	{
		contentHolder.innerHTML = escapeToNormal( parts[1].substr( 1, parts[1].length - 2 ) );
	}
	else
	{
		contentHolder.innerHTML = '';
		var str = escapeToNormal( parts[1].substr( 1, parts[1].length - 2 ) );
		if( str.indexOf( 'option' ) != -1 )
		{
			contentHolder.outerHTML = contentHolder.outerHTML.replace( /<\/select>/gi, str+"</select>" );
		}
		else
		{
			contentHolder.innerHTML = escapeToNormal( parts[1].substr( 1, parts[1].length - 2 ) );
		}
	}
    if( parts[2] )
    {
        var f = escapeToNormal( parts[2].substr( 1, parts[2].length - 2 ) );
        eval(f+"()");
    }
}
function saveRequest1( response )
{
	setTimeout( "{ var n = document.getElementById('loading'); if( n ) { n.parentNode.removeChild( n ); } }", 2000 );
	var parts = response.split( '|||' );
	contentHolder = document.getElementById( parts[0].substr( 1, parts[0].length - 2 ) );
	contentHolder.value = escapeToNormal( parts[1].substr( 1, parts[1].length - 2 ) );
    if( parts[2] )
    {
        var f = escapeToNormal( parts[2].substr( 1, parts[2].length - 2 ) );
        if( f !== 'false' )
        {
            eval("window."+f+"()");
        }
    }
    if( parts[3] && parts[4] )
    {
        contentHolder = document.getElementById( parts[3].substr( 1, parts[3].length - 2 ) );
        contentHolder.innerHTML = escapeToNormal( parts[4].substr( 1, parts[4].length - 2 ) );
    }
}

function hideMessageBox()
{
	wnd = document.getElementById('messagebox');
	wnd.style.display="none";
}

function escapeToNormal( str )
{
	str = str.replace( /%C0/g, 'А' );
	str = str.replace( /%C1/g, 'Б' );
	str = str.replace( /%C2/g, 'В' );
	str = str.replace( /%C3/g, 'Г' );
	str = str.replace( /%C4/g, 'Д' );
	str = str.replace( /%C5/g, 'Е' );
	str = str.replace( /%C6/g, 'Ж' );
	str = str.replace( /%C7/g, 'З' );
	str = str.replace( /%C8/g, 'И' );
	str = str.replace( /%C9/g, 'Й' );
	str = str.replace( /%CA/g, 'К' );
	str = str.replace( /%CB/g, 'Л' );
	str = str.replace( /%CC/g, 'М' );
	str = str.replace( /%CD/g, 'Н' );
	str = str.replace( /%CE/g, 'О' );
	str = str.replace( /%CF/g, 'П' );
	str = str.replace( /%D0/g, 'Р' );
	str = str.replace( /%D1/g, 'С' );
	str = str.replace( /%D2/g, 'Т' );
	str = str.replace( /%D3/g, 'У' );
	str = str.replace( /%D4/g, 'Ф' );
	str = str.replace( /%D5/g, 'Х' );
	str = str.replace( /%D6/g, 'Ц' );
	str = str.replace( /%D7/g, 'Ч' );
	str = str.replace( /%D8/g, 'Ш' );
	str = str.replace( /%D9/g, 'Щ' );
	str = str.replace( /%DA/g, 'Ъ' );
	str = str.replace( /%DB/g, 'Ы' );
	str = str.replace( /%DC/g, 'Ь' );
	str = str.replace( /%DD/g, 'Э' );
	str = str.replace( /%DE/g, 'Ю' );
	str = str.replace( /%DF/g, 'Я' );
	str = str.replace( /%E0/g, 'а' );
	str = str.replace( /%E1/g, 'б' );
	str = str.replace( /%E2/g, 'в' );
	str = str.replace( /%E3/g, 'г' );
	str = str.replace( /%E4/g, 'д' );
	str = str.replace( /%E5/g, 'е' );
	str = str.replace( /%E6/g, 'ж' );
	str = str.replace( /%E7/g, 'з' );
	str = str.replace( /%E8/g, 'и' );
	str = str.replace( /%E9/g, 'й' );
	str = str.replace( /%EA/g, 'к' );
	str = str.replace( /%EB/g, 'л' );
	str = str.replace( /%EC/g, 'м' );
	str = str.replace( /%ED/g, 'н' );
	str = str.replace( /%EE/g, 'о' );
	str = str.replace( /%EF/g, 'п' );
	str = str.replace( /%F0/g, 'р' );
	str = str.replace( /%F1/g, 'с' );
	str = str.replace( /%F2/g, 'т' );
	str = str.replace( /%F3/g, 'у' );
	str = str.replace( /%F4/g, 'ф' );
	str = str.replace( /%F5/g, 'х' );
	str = str.replace( /%F6/g, 'ц' );
	str = str.replace( /%F7/g, 'ч' );
	str = str.replace( /%F8/g, 'ш' );
	str = str.replace( /%F9/g, 'щ' );
	str = str.replace( /%FA/g, 'ъ' );
	str = str.replace( /%FB/g, 'ы' );
	str = str.replace( /%FC/g, 'ь' );
	str = str.replace( /%FD/g, 'э' );
	str = str.replace( /%FE/g, 'ю' );
	str = str.replace( /%FF/g, 'я' );
	str = str.replace( /%A8/g, 'Ё' );
	str = str.replace( /%B8/g, 'ё' );

	return str;
}

function escapeToCode( str )
{
	str = str.replace( /A/g, '%C0' );
	str = str.replace( /Б/g, '%C1' );
	str = str.replace( /В/g, '%C2' );
	str = str.replace( /Г/g, '%C3' );
	str = str.replace( /Д/g, '%C4' );
	str = str.replace( /Е/g, '%C5' );
	str = str.replace( /Ж/g, '%C6' );
	str = str.replace( /З/g, '%C7' );
	str = str.replace( /И/g, '%C8' );
	str = str.replace( /Й/g, '%C9' );
	str = str.replace( /К/g, '%CA' );
	str = str.replace( /Л/g, '%CB' );
	str = str.replace( /М/g, '%CC' );
	str = str.replace( /Н/g, '%CD' );
	str = str.replace( /О/g, '%CE' );
	str = str.replace( /П/g, '%CF' );
	str = str.replace( /Р/g, '%D0' );
	str = str.replace( /С/g, '%D1' );
	str = str.replace( /Т/g, '%D2' );
	str = str.replace( /У/g, '%D3' );
	str = str.replace( /Ф/g, '%D4' );
	str = str.replace( /Х/g, '%D5' );
	str = str.replace( /Ц/g, '%D6' );
	str = str.replace( /Ч/g, '%D7' );
	str = str.replace( /Ш/g, '%D8' );
	str = str.replace( /Щ/g, '%D9' );
	str = str.replace( /Ъ/g, '%DA' );
	str = str.replace( /Ы/g, '%DB' );
	str = str.replace( /Ь/g, '%DC' );
	str = str.replace( /Э/g, '%DD' );
	str = str.replace( /Ю/g, '%DE' );
	str = str.replace( /Я/g, '%DF' );
	str = str.replace( /а/g, '%E0' );
	str = str.replace( /б/g, '%E1' );
	str = str.replace( /в/g, '%E2' );
	str = str.replace( /г/g, '%E3' );
	str = str.replace( /д/g, '%E4' );
	str = str.replace( /е/g, '%E5' );
	str = str.replace( /ж/g, '%E6' );
	str = str.replace( /з/g, '%E7' );
	str = str.replace( /и/g, '%E8' );
	str = str.replace( /й/g, '%E9' );
	str = str.replace( /к/g, '%EA' );
	str = str.replace( /л/g, '%EB' );
	str = str.replace( /м/g, '%EC' );
	str = str.replace( /н/g, '%ED' );
	str = str.replace( /о/g, '%EE' );
	str = str.replace( /п/g, '%EF' );
	str = str.replace( /р/g, '%F0' );
	str = str.replace( /с/g, '%F1' );
	str = str.replace( /т/g, '%F2' );
	str = str.replace( /у/g, '%F3' );
	str = str.replace( /ф/g, '%F4' );
	str = str.replace( /х/g, '%F5' );
	str = str.replace( /ц/g, '%F6' );
	str = str.replace( /ч/g, '%F7' );
	str = str.replace( /ш/g, '%F8' );
	str = str.replace( /щ/g, '%F9' );
	str = str.replace( /ъ/g, '%FA' );
	str = str.replace( /ы/g, '%FB' );
	str = str.replace( /ь/g, '%FC' );
	str = str.replace( /э/g, '%FD' );
	str = str.replace( /ю/g, '%FE' );
	str = str.replace( /я/g, '%FF' );
	str = str.replace( /Ё/g, '%A8' );
	str = str.replace( /ё/g, '%B8' );

	return str;
}


function escapeToWin1251(str){
str=str.replace(/&/g, '&');
str=str.replace(/ /g, ' ');
str=str.replace(/=/g, '=');
str=str.replace(/\+/g, '+');
str=str.replace(/№/g, '№');
str=str.replace(/\;/g, ';');
str=str.replace(/Ё/g, 'Ё');
str=str.replace(/ё/g, 'ё');
str=str.replace(/©/g, '©');
str=str.replace(/[А-Яа-я]/g, function(symbol){return '%'+Number(symbol.charCodeAt(0)-0x0350).toString(16);});
return str;
}
function showImage( address, alt, width, height )
{	
	w = Math.floor(width)+20;
	h = Math.floor(height)+20;
	var newWindow = window.open('','newWindow','width='+w+',height='+h);
	newWindow.document.open();
	newWindow.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
	newWindow.document.write('<html>');
	newWindow.document.write('<head>');
	newWindow.document.write('<title>'+alt+'</title>');
	newWindow.document.write('<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />');
	newWindow.document.write('<meta name="generator" content="220V, ~400Hz" />');
	newWindow.document.write('<style type="text/css">');
	newWindow.document.write('body { padding-top:  5px; padding-bottom: 5px; background:  #F3F3F3; text-align: center;}');
	newWindow.document.write('</style>');
	newWindow.document.write('</head>');
	newWindow.document.write('<body>');
	newWindow.document.write('<img src="'+host+address+'" alt="'+alt+'" title="'+alt+'" />');
	newWindow.document.write('</body>');
	newWindow.document.write('</html>');
	newWindow.document.close();
}
function selectPhones()
{
	var vendor = document.getElementById('vendor').value;
	if( vendor != '-1' )
	{
		sendRequest( 'getModels', vendor );
	}
}
function changeSorting(n)
{
	//document.getElementById('sorting').value = document.getElementById('sortBy').value;
	document.getElementById('sorting').value = n;
	document.getElementById('filterFormSelectBtn').click();
}
function changeSortBy(n)
{
	document.getElementById('sortBy').value = n;
	document.getElementById('phSel').submit();
}
function recalc()
{
    sendRequest( 'tarifchange', document.getElementById('tarif').options[document.getElementById('tarif').selectedIndex].value );
    var chb = document.getElementById('connect');
    if( chb )
    {
        var phonePrice = document.getElementById('phonePrice');
        var tarifPrice = document.getElementById('tarifPrice');
        var price = document.getElementById('price');
        if( !isNaN( parseInt(price.innerHTML) ) )
        {// проверка на eolis
            if( chb.checked )
            {// добавить стоимость тарифа
                price.innerHTML = parseInt(phonePrice.value) + parseInt(tarifPrice.value);
            }
            else
            {// вычесть стоимость тарифа, т.е. вернуть стоимость телефона
                price.innerHTML = phonePrice.value;
            }
        }
    }
}
