
function doLoad() {
    JsHttpRequest.query(
        't_simple_loader.php',
        { q: document.getElementById('text').value },
        function(responseJS, responseText) {
            // This function is called on data ready (readyState=4).
            // Write result to page element ($_RESULT become responseJS).
            document.getElementById('result').innerHTML =
                '<b>MD5("'+responseJS.q+'")</b> = ' +
                '"' + responseJS.md5 + '"<br> ';
            // Write debug information too (output become responseText).
            document.getElementById('debug').innerHTML = responseText;
        },
        true // true = disable caching
    );
}

function clearSelect(oSelect) {
	oSelect.innerHTML = '';
}

function addToSelect(oSelect, name, value) {
	if(!oSelect.options) {
		oSelect = document.getElementById(oSelect);
	}

	if(oSelect.options) {
		var oOption = document.createElement("OPTION");
		oSelect.options.add(oOption);
		oOption.innerHTML = name;
		oOption.value = value;
	}
}

function fillSelect(oSelect, data) {
	var item;
	if(oSelect&&data) {
		var m = data.split('\n');
		for(i=0;i<m.length;i++) {
			item = m[i].split('\t');
			if(item.length==2) addToSelect(oSelect, item[0], item[1]);
		}
	}
}

function ajaxmod(elementid, mod, place, param) {
	var e = document.getElementById(elementid);
    e.innerHTML = '稍等...';

	JsHttpRequest.query(
        'ajax/mod.php',
        { mod: mod, place: place, param: param },
        function(responseJS, responseText) {
        	var e = document.getElementById(elementid);
        	if(responseText) alert(responseText);
            e.innerHTML = responseJS.data;
        },
        true
    );
}

function hidemain() {
	var mainplace = document.getElementById('mainplace');
	if(mainplace) mainplace.style.visibility='hidden';
}

function getFormField(form, m_post) {
	var e = null;

	if(form)
	for(var i=0;i<form.childNodes.length;i++) {
		e = form.childNodes[i];

		if(e.getAttribute && e.name) {
			if(e.type == 'checkbox') {
				if(e.checked) m_post[e.name] = e.value;
			} else
			if(e.type == 'radio') {
				if(e.checked) m_post[e.name] = e.value;
			} else
			if(e.type == 'file') {
				if(!m_post['fileinputs']) m_post['fileinputs'] = { };
				m_post['fileinputs'][e.name] = e;
			} else {
				m_post[e.name] = e.value;
			}
		}
		m_post = getFormField(e, m_post);
	}

	return m_post;
}

function ajaxSendForm(form) {
	if(testForm(form)) {
		var url = form.getAttribute('action');
		var m_post = getFormField(form, { });
		
		/*var ajaxhider = document.getElementById('ajaxhider');
		if(ajaxhider) {
			ajaxhider.style.display='';
		}*/
		showHider();
		
		var mainplace = document.getElementById('mainplace');
		if(mainplace) mainplace.style.visibility='hidden';
		
		var m_param = {url: url, post: m_post};
		
		if(m_post['fileinputs']) {
			for(var name in m_post['fileinputs']) {
			 	m_param[name] = m_post['fileinputs'][name];
			}
		}

		JsHttpRequest.query(
		    'index.php',
		    m_param,
		    function(responseJS, responseText) {
		        if(responseText) {
		        	eval(responseText);
		        	return 0;
		        }

		        var html = responseJS.html;
				if(html) {
					var mainplace = document.getElementById('mainplace');
					if(mainplace) {
						mainplace.innerHTML = html;
						mainplace.style.visibility='';
					} else {
					 	alert('No mainplace');
					}
				}
				
				var m_hide = [];
				var ee = null;

				var place = responseJS.place;
				if(place && place instanceof Object) {
					for (var key in place) {
						var val = place[key];
						if(val instanceof Function) continue;
						ee = document.getElementById(key);
						if(ee) {
							$(ee).hide();
							ee.innerHTML = val;
							m_hide.push(ee);
						}
					}
				}
				
				var ajaxhider = document.getElementById('ajaxhider');
				if(ajaxhider) ajaxhider.style.display='none';
		
				for (var i in m_hide) {
					if(!g_isdialog) $(m_hide[i]).show();
					else $(m_hide[i]).fadeIn(1000);
				}

				var ajaxeval = responseJS.ajaxeval;
				if(ajaxeval) {
					for (var key in ajaxeval) {
						var val = ajaxeval[key];
						if(val instanceof Function) continue;
						eval(val);
					}
				}
				
				if(place && place instanceof Object) {
					for (var key in place) {
						var val = place[key];
						if(val instanceof Function) continue;
						var ee = document.getElementById(key);
						if(!ee) continue;
						var m_elem = ee.getElementsByTagName('script');
						if(m_elem) {
							for(var i in m_elem) {
								if(m_elem[i] && m_elem[i].getAttribute && m_elem[i].innerHTML) {
									eval(m_elem[i].innerHTML);
								}
							}
						}
					}
				}
		    },
		    true
		);
	}
	return false;
}

var g_jurnalcounter = 0;

var g_curhiderid = 0;

function showHider() {
	g_curhiderid++;
	var ajaxhider = document.getElementById('ajaxhider');
	if(ajaxhider) {
		setTimeout("hideHider('" + g_curhiderid + "')", 10000);
		ajaxhider.style.display='';
	}
}

function hideHider(id) {
	if(id == g_curhiderid) {
		var ajaxhider = document.getElementById('ajaxhider');
		if(ajaxhider) {
			ajaxhider.style.display='none';
		}
	}
}

function ajaxgo(url) {
	/*var ajaxhider = document.getElementById('ajaxhider');
	if(ajaxhider) {
		ajaxhider.style.display='';
	}*/
	showHider();
	
	var mainplace = document.getElementById('mainplace');
	if(mainplace) mainplace.style.visibility='hidden';
	
	g_jurnalcounter++;
	//location.href = '#' + g_jurnalcounter;
	var url2 = url;
	/*for(var i=0;i<10;i++) {
		url2 = url2.replace('_', '.');
		if(url2.search('_')==-1) break;
	}*/
	
	current_loc = '#-' + url2;
	location.href = '#-' + url2;

    JsHttpRequest.query(
        'index.php',
        { url: url },
        function(responseJS, responseText) {
        	if(responseText) {
        		eval(responseText);
        		return 0;
        	}

            var html = responseJS.html;
			if(html) {
				var mainplace = document.getElementById('mainplace');
				if(mainplace) {
					mainplace.innerHTML = html;
					mainplace.style.visibility='';
				} else {
				 	alert('No mainplace');
				}
			}
			
			var m_hide = [];
			var ee = null;

			var place = responseJS.place;
			if(place && place instanceof Object) {
				for (var key in place) {
					var val = place[key];
					if(val instanceof Function) continue;
					ee = document.getElementById(key);
					$(ee).hide();
					ee.innerHTML = val;
					m_hide.push(ee);
				}
			}
			
			var ajaxhider = document.getElementById('ajaxhider');
			if(ajaxhider) ajaxhider.style.display='none';
			
			for (var i in m_hide) {
				if(!g_isdialog) $(m_hide[i]).fadeIn(1000);
				else $(m_hide[i]).show();
			}

			var ajaxeval = responseJS.ajaxeval;
			if(ajaxeval) {
				for (var key in ajaxeval) {
					var val = ajaxeval[key];
					if(val instanceof Function) continue;
					eval(val);
				}
			}
			
			if(place && place instanceof Object) {
				for (var key in place) {
					var val = place[key];
					if(val instanceof Function) continue;
					var ee = document.getElementById(key);
					if(!ee) continue;
					var m_elem = ee.getElementsByTagName('script');
					if(m_elem) {
						for(var i in m_elem) {
							if(m_elem[i] && m_elem[i].getAttribute && m_elem[i].innerHTML) {
								eval(m_elem[i].innerHTML);
							}
						}
					}
				}
			}
        },
        true
    );
}

var flag_flashsearch_key = Array();
var flag_flashsearch_time = Array();

function flashsearch_key(field, type) {
	var str = document.getElementById(field).value;
	if(str.length > 2) {
		flag_flashsearch_key[field] = 1;
		if(!flag_flashsearch_time[field]) flashsearch_time(field, type);
	}
}

function flashsearch_time(field, type) {
	if(flag_flashsearch_key[field]) {
		flag_flashsearch_time[field] = 1;
		flag_flashsearch_key[field] = 0;
		setTimeout("flashsearch_time('" + field + "', '" + type + "')", 300);
	} else {
		flag_flashsearch_time[field] = 0;
		flashsearch(field, type);
	}
}

function flashsearch(field, type) {
	var str = document.getElementById(field).value;

    JsHttpRequest.query(
        'ajax/flashsearch.php',
        { type: type, str: str },
        function(responseJS, responseText) {
        	if(responseText) {
        		alert(responseText);
        		return 0;
			}
			
        	if(responseJS.res!=0) {
        		var flashsearch = document.getElementById('flashsearch');
				if(flashsearch) {
					var e = document.getElementById(field);
					if(!e) return 0;
					
					var y = e.offsetTop;
					var x = e.offsetLeft;
					
					var ii = e.offsetParent;
					
					while(ii.tagName!='BODY') {
						y += ii.offsetTop;
						x += ii.offsetLeft;
						ii = ii.offsetParent;
					}
					
					y += e.offsetHeight;
					
					flashsearch.style.top = y + 'px';
					flashsearch.style.left = x + 'px';
					flashsearch.style.width = e.offsetWidth + 'px';
					flashsearch.style.height = '10px';

					flashsearch.innerHTML = '';
					for(i=0;i<responseJS.res.length;i++) {
						if(responseJS.res[i][2]) flashsearch.innerHTML += '<div class="flashsearch"><a href="#" onclick="document.getElementById(\'' + field + '\').value=\'' + responseJS.res[i][1] + '\';document.getElementById(\'' + field + '_id\').value=\'' + responseJS.res[i][0] + '\';document.getElementById(\'flashsearch\').style.display=\'none\';return false;">' + responseJS.res[i][2] + '</a></div>';
					}
					flashsearch.innerHTML += '<div class="flashsearch_bottom"><a href="" onclick="document.getElementById(\'flashsearch\').style.display=\'none\';return false;">закрыть</a></div>';
					flashsearch.style.display = '';
				}
        	} else {
				var flashsearch = document.getElementById('flashsearch');
				if(flashsearch) {
					flashsearch.style.display = 'none';
				}
        	}
        },
        false
    );
}

function setFilter() {
	var colection = $('.catalogfilter_canselect');
	var e = null
	var filter = document.getElementById('catalogfilter_filter');
	for(var i=0;i<colection.length;i++) {
		e = colection.eq(i);
		if(e.hasClass('selrow')) {
			if(filter.value) filter.value += '&';
			filter.value += e.attr('name')+'[]='+e.attr('value');
		}
	}
	
	if(filter.value) filter.value += '&';
	filter.value += 'mincost='+document.getElementById('costFrom').value+'&maxcost='+document.getElementById('costTo').value;
	
	/*if(filter.value) filter.value += '&';
	if(E('showcod').checked) filter.value += 'showcod=1';
	else filter.value += 'showcod=0';*/
	
	ajaxSendForm(document.getElementById('setFilterForm'));
}

function onDragCostLine(event, ui) {
	var linelength = 161;
	
	var pos1 = $('#costlinepoint1').position();
	var pos2 = $('#costlinepoint2').position();
	pos1 = pos1.left;
	pos2 = pos2.left;
	if(pos1 > pos2) {
		var t = pos1;
		pos1 = pos2;
		pos2 = t;
	}
	
	$('#costlinebg1').css('width', pos1+7);
	$('#costlinebg2').css('width', linelength-pos2);
	$('#costlinebg2').css('left', linelength-(linelength-pos2));

	var mincost = parseInt(document.getElementById('minCostLine').value);
	var maxcost = parseInt(document.getElementById('maxCostLine').value);
	var costval = (maxcost - mincost)/linelength; // цена деления
	
	var costFrom = Math.round(pos1*costval + mincost);
	var costTo = Math.round((pos2+7)*costval + mincost);
	
	var costToMax = Math.round((linelength)*costval + mincost);
	
	if(costFrom - Math.round(costFrom/100)*100 == 0) {
		
	} else
	if(costFrom - Math.round(costFrom/100)*100 <= 10) {
		costFrom = Math.round(costFrom/100)*100 + 90;
	} else {
		costFrom = Math.round(costFrom/100)*100 + 99;
	}
	
	if(costTo - Math.round(costTo/100)*100 <= 10) {
		costTo = Math.round(costTo/100)*100 + 90;
	} else {
		costTo = Math.round(costTo/100)*100 + 99;
	}
	
	if(costTo > costToMax) costTo = costToMax;
	
	$('#costLineFrom').text(costFrom);
	$('#costLineTo').text(costTo);
	
	document.getElementById('costFrom').value = costFrom;
	document.getElementById('costTo').value = costTo;
}

function setCostPos(cost1, cost2) {
	var mincost = parseInt(document.getElementById('minCostLine').value);
	var maxcost = parseInt(document.getElementById('maxCostLine').value);
	var linelength = 161;
	var costval = (maxcost - mincost)/linelength; // цена деления
	
	$('#costlinepoint1').css('left', Math.round((cost1-mincost)/costval));
	$('#costlinepoint2').css('left', Math.round((cost2-mincost)/costval)-7);
	
	$('#costlinebg1').css('width', Math.round((cost1-mincost)/costval+7));
	$('#costlinebg2').css('width', linelength-(Math.round((cost2-mincost)/costval)-7));
	$('#costlinebg2').css('left', linelength-(linelength-(Math.round((cost2-mincost)/costval)-7)));
}

var g_testie6 = null;
function testIE6() {
	if(g_testie6) {
	 	if(g_testie6 == 1) return true;
	 	else if(g_testie6 == 2) return false;
	}
	
	var browser=navigator.appName;
	var b_version=navigator.appVersion;
	
	var re = new RegExp('; MSIE 6\.*;', "gim");

	if(b_version.search(re) != -1) {
		g_testie6 = 1;
		return true;
	} else {
		g_testie6 = 2;
		return false;
	}
} 
function onScrollAjaxHider() {
	if(testIE6()) document.getElementById('ajaxhider').style.top = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}
window.onscroll = onScrollAjaxHider;

function goColor(sel, url) {
	var color = sel.value;
	if(color) {
		url = url.replace('colorparam', color);
		ajaxgo(url);
	}
}

function goSize(sel, url) {
	var size = sel.value;
	if(size) {
		url = url.replace('sizeparam', size);
		ajaxgo(url);
	}
}

function onEndSort(event, ui) {
	var m_pos = [];
	for(var i=0;i<$('.sortitem').length;i++) {
		var e = $('.sortitem').eq(i);
		var node_id = e.attr('nodeid');
		m_pos.push(node_id);
	}
	
	var cont = $('.sortitem').eq(0).parent();
	var backorder = cont.attr('backorder');
	
	if(m_pos.length > 0) {
		
		var ajaxhider = document.getElementById('ajaxhider');
		if(ajaxhider) {
			ajaxhider.style.display='';
		}
		
	 	JsHttpRequest.query(
	        '/ajax/setpos.php',
	        { m_pos: m_pos, backorder: backorder },
	        function(responseJS, responseText) {
	        	var ajaxhider = document.getElementById('ajaxhider');
				if(ajaxhider) {
					ajaxhider.style.display='none';
				}
	        	
	        	if(responseText) alert(responseText);
	            if(!responseJS.ok) alert('Ошибка установки позиции');
	        },
	        true
	    );
	}
}

function addtobask(id, col) {
	JsHttpRequest.query(
        '/addtobask.php',
        { id: id, col: col },
        function(responseJS, responseText) {
			if(responseText) {
				alert(responseText);
				return false;
			}
        	if(responseJS.res) {
				if (responseJS.success) animateAddToBask();
				else alert(responseJS.res);
				ajaxmod('topbask', 'topbask', 'topbask', null);
			}
        },
        true
    );
} 

// переход по якорю
function goToHash(hash, ajax) {
	if(hash.search('#-')!=-1) {
		var url = new String(hash).replace('#-','');
		
		// новый или старый вид URL адресов
		var f_newurl = false;
		if(url.indexOf('.html') > -1) f_newurl = true;
		
		if(f_newurl) url = url.replace('.html', '');
		else url = url.replace('.htm', '');
		/*for(var i=0;i<10;i++) {
			url = url.replace('\.', '_');
			if(url.search('.')==-1) break;
		}*/
		if(f_newurl) url += '.html';
		else url += '.htm';
		
		if(ajax) ajaxgo(url);
		else document.location.replace(url);
	}
}

var current_loc = location.hash;
function checkLocation () {
    var hash = document.location.hash;    
    if (hash != current_loc) {
        current_loc = hash;
        goToHash(hash, true);
    }
    setTimeout("checkLocation();", 500);
}
// запускаем проверку раз в половину секунды
setTimeout("checkLocation();", 500);

if(document.location.hash && document.location.hash.indexOf('#-') > -1) {
	goToHash(document.location.hash, false);
}

function loadColorFotoForm(goods_id, color_id) {
	if(goods_id && color_id) {
		var url = g_allgoods_loadColorFotoFormURL.replace('-color-', color_id);
		ajaxgo(url);
	} else {
		alert('не выбран цвет');
	}
}

function dostavkacost() {
	var oblastnumber = document.getElementById('region').value;
	var baskcost = document.getElementById('baskcost').value;
	
	JsHttpRequest.query(
        '/ajax/dostavkacost.php',
        { baskcost: baskcost, oblastnumber: oblastnumber, ves:document.getElementById('ves').value },
        function(responseJS, responseText) {
			if(responseText) {
				alert(responseText);
				return false;
			}
       		document.getElementById('costdostavka').value = responseJS.cost;
				
			if(responseJS.mess) document.getElementById('dostavkacost2').innerHTML = responseJS.mess;
			else document.getElementById('dostavkacost2').innerHTML = responseJS.cost + ' 元';
        },
        true
    );
} 

function orderpay_showorder(order_id) {
	var url = orderpay_showorder_url.replace('-orderid-', order_id);
	ajaxgo(url);
}

function signal() {
    JsHttpRequest.query(
        'ajax/signal.php',
        {  },
        function(responseJS, responseText) {
            if(responseJS.signal) {
            	//alert('New order');
            	window.open('/neworder.html','neworder','top=200,left=200,width=357,height=72,scrollbars=no,resizable=no');
			}
        },
        true
    );
    
    setTimeout("signal()", 30000);
}

