
function SmartAjax() {    // эти переменные можно использовать, если нужно знать реальную
	// ширину/высоту отображаемой области браузера
	// для определения нужно вызвать метод getWindowDimensions()
	var smartWindowWidth;
	var smartWindowHeight;
	var xmlhttp = new Array();
	this.smartWindowWidth = 0;
	this.smartWindowHeight = 0;

	// сокращенный аналог для document.getElementById(id)
	// smartajax.$(id) ~~ document.getElementById(id)
	this.$ = function(ajxObjid)	{
		if (!ajxObjid) { return null; }
		var res = document.getElementById(ajxObjid);
		if (!res && document.all) {
			res = document.all[ajxObjid];
		}
		return res;
	}

    // вставить элемент перед другим
	// ajxObjid - id вставляемого элемента
	// beforeId - id элемента перед которым вставляем
	// theTag - тег (напр, 'div'), элемента
    this.insertBefore = function(ajxObjid,beforeId,theTag) {
		var objBefore = this.$(beforeId);
		obj = document.createElement(theTag);
		obj.setAttribute('id',ajxObjid);
		objBefore.parentNode.insertBefore(obj, objBefore);
	}

	// создать элемент внутри указанного родительского элемента
	// parentId - id родительского элемента
	// theTag - тег вставляемого элмента (напр, div)
	// objId - id вставляемого элемента
	this.create = function(parentId, theTag, objId) {
		var objParent = this.$(parentId);
		obj = document.createElement(theTag);
		obj.setAttribute('id',objId);
		if (objParent)
			objParent.appendChild(obj);
	}

	// удалить элемент с указанным id
	this.remove = function(removeId) {
		obj = this.$(removeId);
		if (obj && obj.parentNode && obj.parentNode.removeChild)
		{
			obj.parentNode.removeChild(obj);
		}
	}

	// функция редиректа
	this.go = function(url) {		window.location = url;	}

	// метод рассчитывает значение ширины и высоты отображаемой области браузера
	// this.smartWindowWidth - ширина
	// this.smartWindowHeight - высота
 	this.getWindowDimensions = function () { 		var body = document.body;
		if (typeof( body.scrollHeight ) == 'number') { 			tmpY = body.scrollHeight; 		} else {
			tmpY = 0; 		}
 		if (typeof( body.scrollWidth ) == 'number') {
 			tmpX = body.scrollWidth;
 		} else {
			tmpX = 0;
 		}
  		if( typeof( window.innerWidth ) == 'number' ) {
    		this.smartWindowWidth = Math.max(window.innerWidth, tmpX);
    		this.smartWindowHeight = Math.max(window.innerHeight, tmpY);
  		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    		//IE 6+ in 'standards compliant mode'
    		this.smartWindowWidth = Math.max(document.documentElement.clientWidth, tmpX);
    		this.smartWindowHeight = Math.max(document.documentElement.clientHeight,tmpY);
  		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    		//IE 4 compatible
    		this.smartWindowWidth = Math.max(document.body.clientWidth,tmpX);
    		this.smartWindowHeight = Math.max(document.body.clientHeight,tmpY);
  		}
	}

	// если нужно вывести какой-то блок с абсолютным позиционированием ровно по
	// центру окна, метод getLeft позволяет получить значение координаты x
	// параметр winWidth - ширина выводимого блока
	// obj.style.left = smartajax.getLeft(500)+'px';
	this.getLeft = function(winWidth) {
		this.getWindowDimensions();
		return Math.round((this.smartWindowWidth - winWidth) / 2);
	}

	// функция позволяет получить объект XMLHTTP независимо от используемого браузера
	this.getAjax = function() {    	var ajaxObj = null;
		if (typeof(XMLHttpRequest) != "undefined")
			ajaxObj = new XMLHttpRequest();
		if (!ajaxObj && typeof(ActiveXObject) != "undefined") {			try { ajaxObj = new ActiveXObject("Msxml2.XMLHTTP"); }
			catch (err1) {				try { ajaxObj = new ActiveXObject("Microsoft.XMLHTTP"); }
				catch (err2) {					try { ajaxObj = new ActiveXObject("Msxml2.XMLHTTP.4.0"); }
					catch (err3) {						ajaxObj = null;					}				}			}		}
		if (!ajaxObj && window.createRequest)
			ajaxObj = window.createRequest();
		return ajaxObj;    }

	// Функция добавляет к адресу специальный параметр, чтобы не вызывать эффекта
	// кэширования
	this.anticacheURL = function(url) { 		if (url.indexOf('?') == -1) {
 			url += '?anticachetime=';
 		} else {
 			url += '&anticachetime=';
 		}
		url += new Date().getTime();
		return url;
	}

	// выполнить асинхронный GET запрос
	// ajxUrl - URL адрес
	// ajxObjid - id объекта (напр, div) в innerHTML которого нужно вставить результат
    this.getRequest = function(ajxUrl,ajxObjid) {		var current_xmlhttp_index = xmlhttp.length;
		//alert(current_xmlhttp_index+' object: '+ajxObjid);
    	ajxUrl = this.anticacheURL(ajxUrl);    	xmlhttp[current_xmlhttp_index] = this.getAjax();
		obj = this.$(ajxObjid);
		if (!obj) return false;
        xmlhttp[current_xmlhttp_index].open("GET",ajxUrl);
		eval('xmlhttp['+current_xmlhttp_index+'].onreadystatechange = function () {	if (xmlhttp['+current_xmlhttp_index+'].readyState == 4) { smartajax.$(\''+ajxObjid+'\').innerHTML = xmlhttp['+current_xmlhttp_index+'].responseText; xmlhttp['+current_xmlhttp_index+'] = "";} }');
		xmlhttp[current_xmlhttp_index].send(null);
		obj.innerHTML = '<div width="100%" align="center"><b>Loading... Please wait</b><br /><img src="/skin1/modules/One_Page_Checkout/loading.gif" alt="Loading... Please wait" /></div>';    }

	// выполнить синхронный GET запрос - нужно когда результат запроса нужно обрабатывать, например в яваскрипте
	// функция пишет результат запроса не в innerHTML, а возвращает его
    this.getRequestAndReturn = function(ajxUrl) {
    	ajxUrl = this.anticacheURL(ajxUrl);
		var current_xmlhttp_index = xmlhttp.length;
    	xmlhttp[current_xmlhttp_index] = this.getAjax();
        xmlhttp[current_xmlhttp_index].open("GET",ajxUrl,false);
		var retvar = "";
    	xmlhttp[current_xmlhttp_index].onreadystatechange = function () {
	    	if (xmlhttp[current_xmlhttp_index].readyState == 4) {
    			retvar = xmlhttp[current_xmlhttp_index].responseText;
    			xmlhttp[current_xmlhttp_index] = "";
    		}
		}
		xmlhttp[current_xmlhttp_index].send(null);
		return retvar;
    }

	// выполнить асинхронный POST запрос
	// formId - id формы
	// ajxObjid - id объекта (напр, div) в innerHTML которого нужно вставить результат
	this.postRequest = function(formId,ajxObjid,ajxUrl) {		postVars = '';
		for (i=0;i<this.$(formId).elements.length;i++) {			tmpobj = this.$(formId).elements[i];
   			if (typeof tmpobj.name == 'undefined') continue;
			if (typeof tmpobj.type != "undefined" && (tmpobj.type == "checkbox" || tmpobj.type == "radio")) {				if (tmpobj.checked) {
					tmpvalue = tmpobj.value;
				} else continue;
			} else if (typeof tmpobj.value != 'undefined') {    			tmpvalue = tmpobj.value;			} else {				tmpvalue = tmpobj.innerHTML;			}
			if (postVars.search('=') == -1) {				postVars += encodeURIComponent(tmpobj.name) + '=' + encodeURIComponent(tmpvalue);			} else {				postVars += '&' + encodeURIComponent(tmpobj.name) + '=' + encodeURIComponent(tmpvalue);			}		}
		ajxUrl = this.anticacheURL(ajxUrl);
		var current_xmlhttp_index = xmlhttp.length;
		xmlhttp[current_xmlhttp_index] = this.getAjax();
		obj = this.$(ajxObjid);
		if (!obj) return false;
		xmlhttp[current_xmlhttp_index].open("POST",ajxUrl);
		xmlhttp[current_xmlhttp_index].setRequestHeader("Method", "POST " + ajxUrl + " HTTP/1.1");
		xmlhttp[current_xmlhttp_index].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	eval('xmlhttp['+current_xmlhttp_index+'].onreadystatechange = function () {	if (xmlhttp['+current_xmlhttp_index+'].readyState == 4) {  smartajax.$(\''+ajxObjid+'\').innerHTML = xmlhttp['+current_xmlhttp_index+'].responseText; xmlhttp['+current_xmlhttp_index+'] = ""; if (\''+ajxObjid+'\' == \'opc_profile\')	ajx_reload_cart();	if (\''+ajxObjid+'\' == \'opc_cart\') ajx_reload_profile();	} 	}');
		xmlhttp[current_xmlhttp_index].send(postVars);
		obj.innerHTML = '<div width="100%" align="center"><b>Loading... Please wait</b><br /><img src="/skin1/modules/One_Page_Checkout/loading.gif" alt="Loading... Please wait" /></div>';	}

	// выполнить синхронный POST запрос - нужно когда результат запроса нужно обрабатывать, например в яваскрипте
	// функция пишет результат запроса не в innerHTML, а возвращает его
	// formId - id формы
	this.postRequestAndReturn = function(formId,ajxUrl) {
		postVars = '';
		for (i=0;i<this.$(formId).elements.length;i++) {
			tmpobj = this.$(formId).elements[i];
   			if (typeof tmpobj.name == 'undefined') continue;
			if (typeof tmpobj.value != 'undefined') {
    			tmpvalue = tmpobj.value;
			} else {
				tmpvalue = tmpobj.innerHTML;
			}
			if (postVars.search('=') == -1) {
				postVars += encodeURIComponent(tmpobj.name) + '=' + encodeURIComponent(tmpvalue);
			} else {
				postVars += '&' + encodeURIComponent(tmpobj.name) + '=' + encodeURIComponent(tmpvalue);
			}
		}
		ajxUrl = this.anticacheURL(ajxUrl);
		var current_xmlhttp_index = xmlhttp.length;
		xmlhttp[current_xmlhttp_index] = this.getAjax();
		xmlhttp[current_xmlhttp_index].open("POST",ajxUrl,false);
		xmlhttp[current_xmlhttp_index].setRequestHeader("Method", "POST " + ajxUrl + " HTTP/1.1");
		xmlhttp[current_xmlhttp_index].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		var retvar = "";
		xmlhttp[current_xmlhttp_index].send(postVars);
		retvar = xmlhttp[current_xmlhttp_index].responseText;
		xmlhttp[current_xmlhttp_index] = '';
		return retvar;
	}
	this.imagePreload = function(vsrc) {    	var img = new Image();
		img.src = vsrc;	}
}
var smartajax = new SmartAjax(); // дальше можно юзать smartajax.methodName();

// One Page Checkout
smartajax.imagePreload('/skin1/modules/One_Page_Checkout/loading.gif');
smartajax.getRequest('opc.php?section=opc_cart', 'opc_cart');
smartajax.getRequest('opc.php?section=opc_profile', 'opc_profile');
function ajx_reload_cart() {
	if (smartajax.$('opc_profile') == "undefined")
		return;
	if (smartajax.$('opc_profile').innerHTML.search('LOGGEDIN') > -1)  {
		smartajax.getRequest('opc.php?section=opc_cart', 'opc_cart');
	}
}
function ajx_reload_profile() {
	if (smartajax.$('opc_profile') == "undefined")
		return;
	smartajax.getRequest('opc.php?section=opc_profile', 'opc_profile');
}
var heightfunc = 0;
var ajxaddtxt = '';
function dropdownfunc() {
	if (smartajax.$('ajxadd2cart')) {
    	smartajax.$('ajxadd2cart').style.height = heightfunc + 'px';
    	if (heightfunc < 50) {
    		heightfunc++;
    		setTimeout('dropdownfunc();', 5);
    	} else {
    		smartajax.$('ajxadd2cart').innerHTML = ajxaddtxt;
			heightfunc = 1;
			window.scroll(200,0);
    	}
	}
}
function showfunc(formname,thumbid){
	var theforms = document.getElementsByName(formname);
	for(var i=0;i<theforms.length;i++) {
		theforms[i].setAttribute('id',formname);
	}
	var itext = smartajax.postRequestAndReturn(formname,'ajxcart.php?mode=add');
	if (itext.search('AJAXOK') == -1)
		return;
	smartajax.$('parentasis').innerHTML = itext;
	smartajax.$('parentasis').innerHTML = smartajax.$('parentasis').innerHTML + '<div id="ajxadd2cart" class="cartdropdown"><img border="0" src="/skin1/images/spacer.gif" width="500px" height="50px" /></div>';
	var heightfunc = 2;
	ajxaddtxt = smartajax.$('resultreturned').innerHTML;
	smartajax.remove('resultreturned');
	setTimeout('dropdownfunc();',5);
	if (thumbid != null) {		$(thumbid).eq(0).effect("transfer", { to: "#parentasis" }, 1000, function() {			$("#parentasis").effect("highlight", {}, 1000);		});	}
	setTimeout('smartajax.remove("ajxadd2cart");',4000);
	window.scroll(200,0);
}