// TOOLS
function getXmlHttp(){
	var xmlhttp;
	try{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e){
		try{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(E){
			xmlhttp = false;
		}
	}
	if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function countClick(ID, title){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incAdv.php?ID='+ID+'&title='+title+'&rand='+Math.random(), true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				return true;
			}
		}
	};
	xmlhttp.send(null);
}

function panelUser(panel, message){
	var xmlhttp = getXmlHttp();
	var messageBlock = document.getElementById('messageBlock');
	xmlhttp.open('GET', '../../includes/inc'+panel+'.php?rand='+Math.random(), true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				if(message != undefined){
					messageBlock.innerHTML = '';
					messageBlock.innerHTML = '<div>'+message+'</div>';
				}
				result = xmlhttp.responseText;

				//link change
				var ar = document.getElementById('formUserPanelHeader');
				arLink = ar.getElementsByTagName('a');
				for(i = 0; i < arLink.length; i++){
					arLink[i].className = '';
				}
				document.getElementById('header'+panel).className += 'active';
				document.getElementById('header'+panel).blur();

				document.getElementById('panelBlock').innerHTML = result;
			}
		}
	};
	xmlhttp.send(null);
	
	if(message == undefined){
		var xmlhttp2 = getXmlHttp();
		xmlhttp2.open('GET', '../../includes/incMessage.php?rand='+Math.random(), true);
		xmlhttp2.onreadystatechange = function(){
			if (xmlhttp2.readyState == 4){
				if(xmlhttp2.status == 200) messageBlock.innerHTML = xmlhttp2.responseText;
			}
		};
		xmlhttp2.send(null);
	}
}

function selectField(field){
	document.getElementById(field).select();
}

function selectZone(currZone){
	tableSet = document.getElementsByTagName('table');
	if(typeof(prevZone) == 'undefined') prevZone = zone;

	if(zone != 0  && prevZone != currZone){
		if(confirm(zone == 4 ? helperConfirm : helperConfirmRU)){
			prevZone = currZone;
			var cleaner = true;
			//cleanin db && $user["address"]
			var xmlhttp = getXmlHttp();
			xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&cleanUser='+userID, true);
			xmlhttp.send(null);
		}else{
			var buttonSet = document.getElementById('buttonSet');
			button = buttonSet.getElementsByTagName('input');
			button[zone-1].checked = 1;
			button[zone-1].focus();
			exit;
		}
	}

	var arr = arrSet[currZone];
	var ID = arr[0];
	if(document.getElementById('block')){
		div = document.getElementById('block');
		div.innerHTML = '';

		//infill
		for(i = 1; i < arr.length; i++){
			div.innerHTML += tableCatalog(arr[i]);
		}
		//cleanin field
		if(cleaner == true){
			//address full
			if(document.getElementById('helperRegion')) document.getElementById('helperRegion').innerHTML = helperRegion;
			if(document.getElementById('helperAddress') && currZone != 3) document.getElementById('helperAddress').innerHTML = helperAddress;
			//error hide
			if(document.getElementById('error')) document.getElementById('error').className = 'blockClose';

			for(i = 0; i < tableSet.length; i++){
				table = tableSet[i];
				if(table.className != '' && table.className != 1 && table.className != 6 && table.className != 8 && table.className != 10 && table.className != 11 && table.className != 14){
					//input
					input = table.getElementsByTagName('input');
					for(k = 0; k < input.length; k++){
						input[k].value = '';
					}
					//textarea
					textarea = table.getElementsByTagName('textarea');
					for(k = 0; k < textarea.length; k++){
						textarea[k].value = '';
					}
				}
			}
		}
		//helpers infill
		helperSet = Array(
			Array('helperIndex', 2, Array(helperIndex, '')),
			Array('helperTranslitRU', 3, Array(helperTranslitRU, '')),
			Array('helperTranslit', 4, Array(helperTranslit, ''))
		);
		for(i = 0; i < helperSet.length; i++){
			helper = helperSet[i];
			if(document.getElementById(helper[0])){
				HTML = ID == helper[1] ? helper[2][0] : helper[2][1];
				if(helper[1].length){
					for(k = 0; k < helper[1].length; k++){
						if(ID == helper[1][k]) HTML = helper[2][0];
					}
				}
				document.getElementById(helper[0]).innerHTML = HTML;
			}
		}
	}

	zone = currZone;
}

function showProgress(){
	return '<div class="progress"><!-- --></div>';
}

function login(){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incAuthorization.php?rand='+Math.random()+'&email='+(document.getElementById('email')).value+'&password='+(document.getElementById('password')).value+'&remember='+(document.getElementById('remember')).value, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				if(xmlhttp.responseText == '') document.location = document.location;
				else panelUser('Authorization', xmlhttp.responseText);
			}
		}
	};
	xmlhttp.send(null);
}

function logout(){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incAuthorization.php?rand='+Math.random()+'&logout=yes');
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200) document.location = document.location;
		}
	};
	xmlhttp.send(null);
}

function generatePassword(message){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&password', true);
	xmlhttp.onreadystatechange = function(){
		if(xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				text = xmlhttp.responseText;
				document.getElementById('passwordSet').innerHTML = message+': '+text;
				document.getElementById('passwordInput').value = text;
				document.getElementById('passwordInput2').value = text;
			}
		}
	};
	xmlhttp.send(null);
}

function sendRecallpassword(message){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incRecallpassword.php?rand='+Math.random()+'&email='+(document.getElementById('email')).value, true);
	xmlhttp.onreadystatechange = function(){
		if(xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				if(xmlhttp.responseText == '') panelUser('Authorization', message);
				else panelUser('Recallpassword', xmlhttp.responseText);
			}
		}
	};
	xmlhttp.send(null);
}

function subscribe(param){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incSubscribe.php?rand='+Math.random()+'&param='+param, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				panelUser('Authorization');
			}
		}
	};
	xmlhttp.send(null);
}

function changeDiscout(userID, param){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&discount='+param+'&userID='+userID, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				document.location = document.location;
			}
		}
	};
	xmlhttp.send(null);
}

function gotoSelect(URL, title){
	document.location = title == 0 ? URL : URL+title+'/';
}

function checkDelete(title, ID, URL){
	if(confirm("Уверены?")){
		var xmlhttp = getXmlHttp();
		xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&ID='+ID+'&delete='+title, true);
		xmlhttp.onreadystatechange = function(){
			if (xmlhttp.readyState == 4){
				//alert(xmlhttp.responseText);exit;
				if(xmlhttp.status == 200) window.parent.location.reload(true);
			}
		};
		xmlhttp.send(null);
	}else return false;
}

//BLOCK
function blockClose(ID){
	var div = document.getElementById(ID);
	div.className = 'blockClose';
}

function blockOpen(ID){
	var div = document.getElementById(ID);
	var sign = document.getElementById('sign'+ID);
	
	if(sign.firstChild.nodeValue == '+'){
		div.className = 'blockOpen';
		sign.innerHTML = '&mdash;';
		if(document.getElementById('notice'+ID)){
			document.getElementById('notice'+ID).className = 'blockClose';
		}
		value = 1;
	}else{
		div.className = 'blockClose';
		sign.innerHTML = '+';
		if(document.getElementById('notice'+ID)){
			document.getElementById('notice'+ID).className = 'blockOpen notice';
		}
		value = 0;
	}

	//write in session
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&setting='+ID+'&value='+value);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200) return true;
		}
	};
	xmlhttp.send(null);
}

function blockChange(current, change){
	if(document.getElementById(change)){
		if(document.getElementById('header'+change)) document.getElementById('header'+change).className = '';
		document.getElementById(change).className = 'blockClose';
	}
	if(document.getElementById(current)){
		if(document.getElementById('header'+current)){
			document.getElementById('header'+current).className = 'active';
		}
		document.getElementById(current).className = 'blockOpen';
	}

	//write in session
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&setting='+current+'&value=1&change='+change+'&valueChange=0');
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200) return true;
		}
	};
	xmlhttp.send(null);
}

function blockChangePanel(title){//TODO merdge
	panelUser(title);
	blockChange('panelUser', 'panelUserShort');
}

function blockMove(ID, direction, step){
	div = document.getElementById(ID);
	i = 0;
	if(direction == 'Rigth'){
		myInt = setInterval(
			function(){
				div.scrollLeft += step*i;
				i++;
			}, 50
		)
	}
	if(direction == 'Left'){
		myInt = setInterval(
			function(){
				div.scrollLeft -= step*i;
				i++;
			}, 50
		)
	}
}

function blockStop(){
	if(typeof myInt != "undefined"){
		  clearInterval(myInt);
		  myInt = null;
	};
}

function tableCatalog(ID){
	return '<table id="catalog" class="'+ID+'">'+block[ID]+'</table>';
}

//OPACITY
function setElementOpacity(oElem, nOpacity){
	var p = getOpacityProperty();
	(setElementOpacity = p=="filter"?new Function('oElem', 'nOpacity', 'nOpacity *= 100; var oAlpha = oElem.filters["DXImageTransform.Microsoft.alpha"] || oElem.filters.alpha;	if (oAlpha) oAlpha.opacity = nOpacity; else oElem.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity="+nOpacity+")";'):p?new Function('oElem', 'nOpacity', 'oElem.style.'+p+' = nOpacity;'):new Function)(oElem, nOpacity);
}

function getOpacityProperty(){
	var p;
	if (typeof document.body.style.opacity == 'string') p = 'opacity';
	else if (typeof document.body.style.MozOpacity == 'string') p =  'MozOpacity';
	else if (typeof document.body.style.KhtmlOpacity == 'string') p =  'KhtmlOpacity';
	else if (document.body.filters && navigator.appVersion.match(/MSIE ([\d.]+);/)[1]>=5.5) p =  'filter';
	return (getOpacityProperty = new Function("return '"+p+"';"))();
}

function blockFade(sElemId, sRuleName, bBackward){
	var elem = document.getElementById(sElemId);
	if (!elem || !getOpacityProperty() || !blockFade.aRules[sRuleName]) return;
	var rule = blockFade.aRules[sRuleName];
	var nOpacity = rule.nStartOpacity;
	if (blockFade.aProc[sElemId]) {clearInterval(blockFade.aProc[sElemId].tId); nOpacity = blockFade.aProc[sElemId].nOpacity;}
	if ((nOpacity==rule.nStartOpacity && bBackward) || (nOpacity==rule.nFinishOpacity && !bBackward)) return;blockFade.aProc[sElemId] = {'nOpacity':nOpacity, 'tId':setInterval('blockFade.run("'+sElemId+'")', blockFade.aRules[sRuleName].nDalay), 'sRuleName':sRuleName, 'bBackward':Boolean(bBackward)};
}

blockFade.addRule = function(sRuleName, nStartOpacity, nFinishOpacity, nDalay){blockFade.aRules[sRuleName]={'nStartOpacity':nStartOpacity, 'nFinishOpacity':nFinishOpacity, 'nDalay':(nDalay || 30),'nDSign':(nFinishOpacity-nStartOpacity > 0?1:-1)};};
blockFade.back = function(sElemId){blockFade(sElemId,blockFade.aProc[sElemId].sRuleName,true);};
blockFade.run = function(sElemId){
	var proc = blockFade.aProc[sElemId];
	var rule = blockFade.aRules[proc.sRuleName];
	proc.nOpacity = Math.round(( proc.nOpacity + .1*rule.nDSign*(proc.bBackward?-1:1) )*10)/10;
	setElementOpacity(document.getElementById(sElemId), proc.nOpacity);
	if (proc.nOpacity==rule.nStartOpacity || proc.nOpacity==rule.nFinishOpacity) clearInterval(blockFade.aProc[sElemId].tId);
}
//OPACITY//

//PRODUCT
function getProductNotice(ID, title){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&ID='+ID+'&productNotice', true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200) document.getElementById(title).innerHTML = xmlhttp.responseText;
		}
	};
	xmlhttp.send(null);
}

function checkSaleCount(val, productStatus){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&productStatus='+productStatus+'&saleCount='+val, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				if(xmlhttp.responseText != '') window.location.reload();
			}
		}
	};
	
	xmlhttp.send(null);
}

function confirmBuy(ID, productStatus, userID){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incBuy.php?rand='+Math.random()+'&ID='+ID+'&title='+productStatus, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				if(userID == '' && productStatus == 'wishlist'){
					blockChange('panelUser', 'panelUserShort');
					panelUser('Goods', xmlhttp.responseText);
					document.location.href = '#panelUser';
				}else{
					if(document.getElementById(productStatus+ID)){
						document.getElementById(productStatus+ID).className = 'blockClose';
						document.getElementById('checked'+ID).className = 'blockOpen';
					}
				}
				panelUser('Goods', xmlhttp.responseText);
				checkSaleCount(5, productStatus);
			}
		}
	};
	xmlhttp.send(null);
	
}

function cartRemove(ID, productStatus){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&ID='+ID+'&cartRemove='+productStatus, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				if(document.getElementById('remove'+ID)){
					document.getElementById(productStatus+ID).className = 'blockOpen';
					document.getElementById('checked'+ID).className = 'blockClose';
				}
				panelUser('Goods', xmlhttp.responseText);
				checkSaleCount(4, productStatus);
			}
		}
	};
	xmlhttp.send(null);
	
}

function blockOpenProduct(title, ID, i){
	var div = document.getElementById(title+'_'+i);
	var sign = document.getElementById(title+'Sign'+i).getElementsByTagName('span')[0];

	if(sign.firstChild.nodeValue == '+'){
		div.className = 'blockOpen';
		sign.innerHTML = '&mdash;';
		document.getElementById(title+'Image'+i).innerHTML = '<a href="#" onClick="openBigImage(\''+title+'\', '+ID+', '+i+');return false;"><img src="../../images/products/'+ID+'sm.jpg?issueType=" class="preveiw" alt="" /><span class="enlarge"><!-- --></span></a>';
		var notice = getProductNotice(ID, title+'Notice'+i);
	}else{
		div.className = 'blockClose';
		sign.innerHTML = '+';
	}
}

function openBigImage(title, ID, i){
	document.getElementById(title+'Image'+i).innerHTML = '<a href="#" onClick="openSmallImage(\''+title+'\', '+ID+', '+i+');return false;"><img src="/images/products/'+ID+'bg.jpg" class="big" alt="" /><span class="miniaturize"><!-- --></span></a>';
}

function openSmallImage(title, ID, i){
	document.getElementById(title+'Image'+i).innerHTML = '<a href="#" onClick="openBigImage(\''+title+'\', '+ID+', '+i+');return false;"><img src="../../images/products/'+ID+'sm.jpg" class="preveiw" alt="" /><span class="enlarge"><!-- --></span></a>';
}

function getCatalogMini(ID, direction){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&getCatalogMini='+ID+'&direction='+direction, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200) document.getElementById('catalogMini'+ID).innerHTML = xmlhttp.responseText;
		}
	};
	xmlhttp.send(null);
}

function listCatalogMini(ID, direction){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&listCatalogMini='+ID+'&direction='+direction, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200) document.getElementById('catalogMini').innerHTML = xmlhttp.responseText;
		}
	};
	xmlhttp.send(null);
}

function getCatalogMidi(ID, direction){
	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&getCatalogMidi='+ID+'&direction='+direction, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				div = document.getElementById('catalogMidi');
				div.className = 'catalogMidi'+ID;
				div.innerHTML = xmlhttp.responseText;
			}
		}
	};
	xmlhttp.send(null);
}

function listCatalogMidi(current, change, ID){
	document.getElementById(change).className = 'blockClose';
	document.getElementById(current).className = 'blockOpen';
	if(current == 'catalogMidi'){
		if(document.getElementById('quoterThree')) document.getElementById('quoterThree').className = 'pagePadding';
		getCatalogMidi(ID, '');
		//location.href = '#catalogMidi';
	}
	if(current == 'quoter'){
		listCatalogMini(ID, '');
		if(document.getElementById(current)) document.getElementById(current).className = 'quoter';
		if(document.getElementById('quoterThree')) document.getElementById('quoterThree').className = 'quoterThree';
	}
}

function blockProductTop(current, currNum){
	var ar = document.getElementById('blockProductTop');
	var contaner = ar.getElementsByTagName('div')[0];

	if(currNum > 20) currNum = 20;
	if(currNum < 0) currNum = 1;
	if(currNum == 1) f = 0;

	var xmlhttp = getXmlHttp();
	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&top25='+current+'&currNum='+currNum, true);

	xmlhttp.onreadystatechange = function(){
		//show progressbar
		var tmp = setTimeout(
			function(){
				if(xmlhttp.readyState != 4){
					contaner.innerHTML = showProgress();
					clearTimeout(tmp);
				}
			}, 250
		);

		if(xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				//link change
				arLink = ar.getElementsByTagName('a');
				for(i = 0; i < arLink.length; i++){
					arLink[i].className = '';
				}
				document.getElementById(current).className = 'active';

				if(xmlhttp.responseText == '') contaner.innerHTML = '<div class="error" id="error">Ничего не найдено</div>';
				else{
					//show table
					if(ar.getElementsByTagName('span')[0]){
						contanerMenu = ar.getElementsByTagName('span')[0];
						contanerMenu.innerHTML = '<a href="#" onClick="blockProductTop(\''+current+'\', '+((currNum - 5) == 0 ? 1 : (currNum - 5))+'); return false;">&laquo; предыдущие</a> | '+(currNum == 1 ? currNum : (currNum + 1))+' &mdash; '+(currNum + (currNum == 1 ? 4 : 5))+' из 25 | <a href="#" onClick="blockProductTop(\''+current+'\', '+(currNum + (currNum == 1 ? 4 : 5))+'); return false;">следующие &raquo;</a>';
					}
					contaner.innerHTML = '<table id="catalog">'+xmlhttp.responseText+'</table>';
				}
			}
		}
	};
	xmlhttp.send(null);
}

function blockProductWaited(current){
// put in head window
window.signal = 1;
//
	var ar = document.getElementById('blockProductWaited');
	var contaner = ar.getElementsByTagName('div')[0];
	//show progressbar
	if(!window.signal){ contaner.innerHTML = showProgress();}

	function getWaited(current){
		var xmlhttp = getXmlHttp();
		xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&current='+current+'&currNum=0', true);
		xmlhttp.onreadystatechange = function(){
			//show progressbar
			if(xmlhttp.readyState !== 4){
				var tmp = setTimeout(
					function(){
						if(xmlhttp.readyState != 4){
							contaner.innerHTML = showProgress();
							clearTimeout(tmp);
						}
					}, 250
				);
			}	

			if(xmlhttp.readyState == 4){
				if(xmlhttp.status == 200){
				//link change
					arLink = ar.getElementsByTagName('a');
					for(i = 0; i < arLink.length; i++){
						arLink[i].className = '';
					}
					document.getElementById(current).className = 'active';
					document.getElementById(current).blur();

				//show table
					if(ar.getElementsByTagName('span')[0]){
						var contanerMenu = ar.getElementsByTagName('span')[0];
						contanerMenu.innerHTML = '<a href="/catalog/?status='+current+'">полный список &raquo;</a>';
					}
					contaner.innerHTML = '<table id="catalog">'+xmlhttp.responseText+'</table>';
				}
			}
		};
		xmlhttp.send(null);/**/
	}

	var intervalID = setInterval(
		function(){
			if(window.signal){
				getWaited(current);
				clearInterval(intervalID);
			}
		}, 250
	);
}

function voteHoF(ID, userID){
	var xmlhttp = getXmlHttp();

	xmlhttp.open('GET', '../../includes/incGet.php?rand='+Math.random()+'&halloffame='+ID+'&userID='+userID, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			if(xmlhttp.status == 200){
				if(xmlhttp.responseText == 'vote_done') text = vote_done;
				if(xmlhttp.responseText == 'authorization_need') text = authorization_need;
				if(xmlhttp.responseText == 'error_vote') text = error_vote;
				alert(text);
			}
		}
	};
	xmlhttp.send(null);
}

function changeStyle(obj, val) {
	obj.style.backgroundImage = val == 1 ? 'url("../../images/utils/table/tdBackActive.png")' : '';
}
