var show_e;
var show_img;

var flag=0;

var contentid;

function E(id) {
 	var e = document.getElementById(id);
 	if(e) return e;
 	return null;
}

function showHideElement(element_id) {
	var e = document.getElementById(element_id);
	if(e) {
		if(e.style.display == 'none') e.style.display = '';
		else e.style.display = 'none';
	}
}

function guestflash(name) {
	if(!contentid) {
		var img = document.getElementById('dummyflashimg' + name);
		var span = document.getElementById('dummyflashspan' + name);

		if(img && span) {
			var flashname = img.getAttribute('flashname');
			var width = img.getAttribute('width');
			var height = img.getAttribute('height');

			if(!width) width = img.getAttribute('flashwidth');
			if(!height) height = img.getAttribute('flashheight');

			AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0','width',width,'height',height,'src',flashname,'quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','movie',flashname );
		}
	}
}

function setflag(cur, flagname) {
	var status = cur.checked;

	var e = null;

	for(i=1;i<=1000;i++) {
		e = document.getElementById(flagname + i);
		if(!e) break;
		e.checked = status;
	}
}

function setRadio(radio, value) {
	for(var i=0;i<radio.length;i++) {
		if(radio[i].value == value) radio[i].checked = true;
	}
	return 0;
}

function itemTestForm(form) {
	var e = null;
	var res = '';
	var require;
	var mincount;
	var fieldname;

	if(form)
	for(var i=0;i<form.childNodes.length;i++) {
		e = form.childNodes[i];

		if(e.getAttribute && e.style.display!='none') {
			require = e.getAttribute('require');
			mincount = e.getAttribute('mincount');
			fieldname = e.getAttribute('fieldname');

			if(require) {
				if((e.value==0)||(e.value=='')) {
					res = res + 'не заполнено поле ' + require + '\n';
				}
			}

			if(mincount) {
				if((e.value.length<mincount)) {
					res = res + 'неверное количество символов в поле ' + fieldname + '\n';
				}
			}

			res = res + itemTestForm(e);
		}
	}

	return res;
}

function testForm(form) {
	var e = null;
	var res = '';
	var require;
	var mincount;
	var fieldname;

	res = itemTestForm(form);

	if(res) {
		res = 'Не верно заполнены поля:\n' + res;
		alert(res);
		return false;
	}

	return true;
}

function confirmQuery(text, url) {
	if(confirm(text)) location.replace(url);
}

function setSelect(name, value) {
	e = document.getElementById(name);
	if(e)
	for(var i=0;i<e.length;i++) {
		if(e.options[i].value==value) e.selectedIndex = i;
	}
}

function writeFlash(w, h, url) {
	document.write('<object id="flash_obj" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="' + w + '" height="' + h + '" id="final" align="middle">');
	document.write('<param name="allowScriptAccess" value="sameDomain" />');
	document.write('<param name="movie" value="' + url + '" />');
	document.write('<param name="loop" value="true" />');
	document.write('<param name="menu" value="false" />');
	document.write('<param name="quality" value="best" />');
	document.write('<param name="scale" value="noscale" />');
	document.write('<param name="wmode" value="transparent" />');
	document.write('<param name="bgcolor" value="#FFFFFF" />');
	document.write('<embed src="' + url + '" loop="true" menu="false" quality="best" scale="noscale" wmode="transparent" bgcolor="#000000" width="' + w + '" height="' + h + '" name="final" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	document.write('</object>');
}

function showFlashWin(x,y,flash,title) {
	if (flag == 1) {
		sw.close();
		flag=0;
	}

	//x = x + 20;
	//y = y + 20;


	eval("sw=window.open('',title,'top=20,left=220,width='+x+',height='+y+',scrollbars=no,resizable=no')");

	sw.document.write("<html><head><title>"+title);
	sw.document.write("</title></head><body leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>");
	sw.document.write("<center><table width='100%' height='100%' cellspacing=0 cellpadding=0 border=0><tr><td align=center>");
	sw.document.write("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0' width='"+x+"' height='"+y+"'><param name='movie' value='"+flash+"'><param name='quality' value='high'><embed src='"+flash+"' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='400' height='240'></embed></object>");
	sw.document.write("</td></tr></table>");
	sw.document.write("</center>");
	sw.document.write("</body></html>");
	sw.document.close();

	sw.focus();
	flag = 1;
}

function showwin(x,y,url) {
	showfoto(x, y, url);
}

function showfoto(x, y, url) {
	if (flag == 1) {
		sw.close();
		flag=0;
	}

	//x = x + 20;
	//y = y + 20;


	eval("sw=window.open('','Изображение','top=20,left=220,width='+x+',height='+y+',scrollbars=no,resizable=no')");

	sw.document.write("<html><head><title>Изображение");
	sw.document.write("</title></head><body leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>");
	sw.document.write("<center><table width='100%' height='100%' cellspacing=0 cellpadding=0 border=0><tr><td align=center>");
	sw.document.write("<img border='0' src='"+url+"'>");
	sw.document.write("</td></tr></table>");
	sw.document.write("</center>");
	sw.document.write("</body></html>");
	sw.document.close();

	sw.focus();
	flag = 1;
}

function showflash(page,x,y)
{
	eval("sf=window.open(Name=\""+page+"\",\"FLASH\",\"top=20,left=220,width="+x+",height="+y+",scrollbars=no,resizable=no\")")
}

function domenu(id,e,img) {
	if(id == pageid) {
		e = document.getElementById(e);
		img = document.getElementById(img);
		if(e&&img) {
			//show(e,img);
			show_e = e;
			show_img = img;
		} else alert("Ошибка");
	}
	return 0;
}

function showmenu() {
	if(show_e && show_img) show(show_e, show_img);
}

function catalog_bask(zena,count) {
	if(document.getElementById('catalog_count')) catalog_count.innerText = count;
	if(document.getElementById('catalog_zena')) catalog_zena.innerText = zena;
}

var ArrayBaskId = new Array();

function parce_baskinfo() {
	var s = document.getElementById('baskinfo').innerHTML;
	listID = s.split(';');
	for (var i = 0; i < listID.length; i++) {
		if(listID[i] != "") {
			m = listID[i].split(':');
			ArrayBaskId[m[0]] = m[1];
		}
	}
}

function catalog_check(id,e) {
	if(ArrayBaskId[id]!=null) {
		e = document.getElementById(e);
		/*if(e) e.checked = "true";
		else e.checked = "false";*/
		if(e) e.value = ArrayBaskId[id];
	}
}

function catalog_buy(cost, id) {
	return 0;
}

function catalog_col_keypres(id,onewcol,zena,ocol,ordertype) {
	if(event.keyCode==13) catalog_modify(id,onewcol,zena,ocol,ordertype);
	if((event.keyCode<48)||(event.keyCode>57)) event.keyCode = 0;
}

function catalog_newcol_keypres(zena,id,text_buy,ordertype) {
	if(event.keyCode==13) catalog_buy(zena,id,text_buy,ordertype);
	if((event.keyCode<48)||(event.keyCode>57)) event.keyCode = 0;
}

function catalog_modify(id,onewcol,zena,ocol,ordertype) {
	onewcol = document.getElementById(onewcol);
	ocol = document.getElementById(ocol);
	ordertype = document.getElementById(ordertype);

	if((onewcol==null)||(ocol==null)||(ordertype==null)) alert('Ошибка определения ID. \n Ваш браузер не поддрердивает JavaScript');

	if(ordertype.checked) ot = 1;
	else ot = 0;

	newcol = onewcol.value;
	if(newcol=="") newcol = 0;
	oldcol = ocol.value;
	ocol.value = newcol;

	/*var sum = document.all.catalog_sum.innerText;
	var nalcurs = document.all.catalog_nalcurs.innerText;
	var beznalcurs = document.all.catalog_beznalcurs.innerText;
	var nalitogo = document.all.catalog_nalitogo.innerText;
	var beznalitogo = document.all.catalog_beznalitogo.innerText;

	sum = parseInt(sum,10) + zena*(newcol-oldcol);
	nalitogo = parseInt(nalitogo,10) + zena*(newcol-oldcol)*nalcurs;
	beznalitogo = parseInt(beznalitogo,10) + zena*(newcol-oldcol)*beznalcurs;

	document.all.catalog_sum.innerText = sum;
	document.all.catalog_nalitogo.innerText = nalitogo;
	document.all.catalog_beznalitogo.innerText = beznalitogo;

	onewcol.select();

	if(document.all.doframe) document.all.doframe.src='./?act=modify&fast=1&id=' + id + '&center=buy&newcol='+newcol;
	else location.href='./?act=modify&id=' + id + '&center=buy&newcol='+newcol;*/

	location.href='./?act=modify&id=' + id + '&center=buy&newcol='+newcol+'&ordertype='+ot;
}

function getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {     
	    xScroll = window.innerWidth + window.scrollMaxX;
	    yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	    xScroll = document.body.scrollWidth;
	    yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	    xScroll = document.body.offsetWidth;
	    yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {     // all except Explorer
	    if(document.documentElement.clientWidth){
	         windowWidth = document.documentElement.clientWidth; 
	    } else {
	         windowWidth = self.innerWidth;
	    }
	    windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	    windowWidth = document.documentElement.clientWidth;
	    windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
	    windowWidth = document.body.clientWidth;
	    windowHeight = document.body.clientHeight;
	}     
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
	    pageHeight = windowHeight;
	} else { 
	    pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){     
	    pageWidth = xScroll;          
	} else {
	    pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};

function hideSubElements(element) {
	var childrens = element.childNodes;
	for(var i=0;i<childrens.length;i++) {
		if(childrens[i].getAttribute && childrens[i].style.display != 'none') {
	 		childrens[i].setAttribute('washided', true);
	 		childrens[i].style.display = 'none';
		}
	}
}

function showSubElements(element) {
	var childrens = element.childNodes;
	for(var i=0;i<childrens.length;i++) {
		if(childrens[i].getAttribute && childrens[i].style.display == 'none' && childrens[i].getAttribute('washided')) {
			childrens[i].setAttribute('washided', false);
	 		childrens[i].style.display = '';
		}
	}
}

function wrapSubElements(element, tagname) {
 	if(element.childNodes.length == 1) {
 	 	return element.childNodes[0];
	} else {
	 	var node = document.createElement(tagname);
	 	element.appendChild(node);
	 	
	 	var childrens = element.childNodes;
	 	for(var i=0;i<childrens.length;i++) {
	 	 	node.appendChild(childrens[i]);
		}
		
		return node;
	}
}

var g_dialogcount = 0;
var g_m_dialogconteiner = [];

// возвращает номер текущего диалога в глобальном массиве диалогов начиная с единицы
function currentDialogNum() {
	var root = getRootWindow();
	if(!root.g_m_dialogconteiner[0]) return -1;
 	for(var i=0;i<root.g_m_dialogconteiner.length;i++) {
 	 	if(root.g_m_dialogconteiner[i] && root.g_m_dialogconteiner[i].childNodes[0] && root.g_m_dialogconteiner[i].childNodes[0].contentWindow == window) return i;
	}
}

function getRootWindow() {
 	var win = window;
 	while(win.parent && win.parent != win) {
 	 	win = win.parent;
	}
	return win;
}

function getParentDialog() {
	var root = getRootWindow();
 	//var parentdiv = root.g_m_dialogconteiner[root.g_m_dialogconteiner.length-2];
 	var parentdiv = root.g_m_dialogconteiner[currentDialogNum()-1];
 	if(parentdiv && parentdiv.childNodes && parentdiv.childNodes[0]) {
 		var iframe = parentdiv.childNodes[0];
		return iframe.contentWindow;
	}
}

// закрытие диалога
function closeDialog() {
	var root = getRootWindow();
	
	// если первый диалог, то показываем все элементы, если нет, то показываем предыдущий диалог
	if(root.g_dialogcount == 1) {
		root.showSubElements(root.document.body);
		
		var node = root.g_m_dialogconteiner.pop();
		root.g_dialogcount--;
 		node.parentNode.removeChild(node);
	} else {
		root.g_m_dialogconteiner[root.g_m_dialogconteiner.length-2].style.display = '';
		
	 	var node = root.g_m_dialogconteiner.pop();
		root.g_dialogcount--;
 		node.parentNode.removeChild(node);
	}
}

function createDialog(pid) {
	mod = arguments[1];
	
 	// старый вариант
 	/*if(pid == 'mod') createWindow('dialog/?pid=' + pid + '&center=' + mod + '', 'dialog', 'width=800,height=500,status=no,toolbar=no,menubar=no,scrollbars=yes');
 	else createWindow('dialog/?pid=' + pid + '&mod=' + mod + '', 'dialog', 'width=800,height=500,status=no,toolbar=no,menubar=no,scrollbars=yes');*/
 	
 	var dialogurl = '';
 	if(!mod) {
 		dialogurl = '?pid=' + pid;
	} else {
 		if(pid == 'mod') dialogurl = '?pid=' + pid + '&center=' + mod + '';
 		else dialogurl = '?pid=' + pid + '&mod=' + mod + '';
	}
 	
 	view = arguments[2];
 	viewplace = arguments[3];
 	viewparam = arguments[4];
 	
 	if(view) {
 	 	dialogurl += '&view_name_'+viewplace+'='+view;
	}
	if(viewparam) {
 	 	dialogurl += '&view_param_'+viewplace+'='+viewparam;
	}
	
	createURLDialog(dialogurl);
}

// создания диалога
function createURLDialog(dialogurl) {
 	// новый вариант
 	var root = getRootWindow();
 	
 	dialogurl = '/dialog/' + dialogurl;
 	
 	root.g_dialogcount++;
 	var zindex = root.g_dialogcount + 1000;
	
	// если первый диалог, то скрываем все элементы, если нет, то скрываем все предыдущие диалоги
	if(root.g_dialogcount == 1) hideSubElements(document.body);
	else {
	 	for(var i=0;i<root.g_m_dialogconteiner.length;i++) {
	 	 	root.g_m_dialogconteiner[i].style.display = 'none';
		}
	}
 	
 	var width = '100%';
 	var height = '100%';
 	var framewidth = '100%';
 	var frameheight = '100%';
 	
 	/*if(testIE6()) {
 		var m = getPageSize();
 		var framewidth = m[0];
 		var frameheight = '100%';
	}*/
 	
 	var node = root.document.createElement('div');
 	node.style.width = width;
 	node.style.height = height;
 	node.style.position = 'absolute';
 	node.style.left = '0px';
 	node.style.top = '0px';
 	node.style.zindex = zindex;
 	node.style.backgroundColor = '#FFFFFF';
 	root.document.body.appendChild(node);
 	
 	root.g_m_dialogconteiner.push(node);
 	
 	node.innerHTML = '<iframe id="dialogframe" width="' + framewidth + '" height="' + frameheight + '" src="' + dialogurl + '" border="0" frameborder="0" style="overflow-x:hidden"></iframe>';
}

// Создание массива для хранения ссылок на дочерние окна.
/* Каждый член данного массива будет окном объекта, созданного
ниже с использованием метода createWindow. */
var windows = new Array();

function newWindow(url, wname) {
// Конструктор для окна
/* Данная функция может быть вызвана только функцией
   createWindow, которая приведена ниже. */
var features = "";
if (null != arguments[2])
   features = arguments[2];
return window.open(url, wname, features);
}

function createWindow(url, wname) {
// Добавление окна в семейство окон.
var features = arguments[2] == null ? "" : arguments[2];
windows[wname] = new newWindow(url, wname, features);
windows[wname].focus();
}

function closeWindows() {
// Закрытие всех окон, открытых методом addWindow.
/* Для закрытия окна вызывается его метод close. */
/* Данная функция может быть вызвана в ходе события onunload
   для автоматического закрытия всех открытых окон.  */
for (w in windows)
   if (!windows[w].closed)
	  windows[w].close();
}

window.onunload=closeWindows;

var m_goodsfotocont = [];

function addColorToGallery(foto1, foto2) {
	// проверяем последний элемент, если третий элемент истина, то это элемент цвета, заменяем его на новый, иначе добавляем новый цвет в конец
 	if(m_goodsfotocont && m_goodsfotocont[m_goodsfotocont.length-1] && m_goodsfotocont[m_goodsfotocont.length-1][2]) m_goodsfotocont[m_goodsfotocont.length-1] = [foto1, foto2, true];
 	else m_goodsfotocont.push([foto1, foto2, true]);
}

function goodsFotoClick(elm) {
	var srcbig = $(elm).attr('srcbig');
	var excludenum = parseInt($(elm).attr('num'));
	
	$('#goodsvideocont').addClass('hide');
	$('#videotext1').removeClass('hide');
	$('#videotext2').addClass('hide');
	
	$('#goodsbigfotocont').height($('#goodsbigfoto').height());
	$('#goodsbigfoto').fadeOut('fast', function() {$('#goodsbigfoto').load(function() {$(this).fadeIn('fast');}); $('#goodsbigfoto').attr('src', srcbig); });
	$('#goodsbigfotocont').height($('#goodsbigfoto').height());
	
	generateGoodsFotoGallery(excludenum);
}

function generateGoodsFotoGallery(excludenum) {
	if(m_goodsfotocont) {
		// создаем массив номеров фоток из которого потом будем выбирать номера, текущий номер в массив не попадает
		var m_num = [];
		var num = 0;
		var r = 0;
		var goodsfotonum = 0; // номер фотки для отображения

		for(var n in m_goodsfotocont) {
			if(n != excludenum) m_num.push(n);
		}
		
		$('#goodsfotocont').html('');
		
		for(var i=0;i<3;i++) {
			if(m_num.length <= 0) break;
			r = Math.random();
			num = Math.round(r*(m_num.length-1));
			goodsfotonum = m_num[num];
			m_num.splice(num, 1);
			if(m_goodsfotocont[goodsfotonum]) {
				$('#goodsfotocont').append('<div class="goodsfotocont_item"><img onclick="goodsFotoClick(this)" id="goodsfotocont_item_foto" src="pict/foto/'+m_goodsfotocont[goodsfotonum][0]+'" num="' + goodsfotonum + '" srcbig="pict/foto/'+m_goodsfotocont[goodsfotonum][1]+'" border=0 width=90></div>');
			}
		}
		
		$('#goodsfotocont').append('<div style="clear:both"></div>');
	}
}

function fakeselect(select, fakeid, hideid) {
 	var fake = document.getElementById(fakeid);
 	var hide = document.getElementById(hideid);
 	
	hide.value = select.options[select.selectedIndex].value;
	fake.innerHTML = select.options[select.selectedIndex].innerHTML;
}

var g_goods_m_colorfotourl = {};
var g_goods_m_colorfotourl_small = {};

function chColor(color_id) {
	var colorfotourl = g_goods_m_colorfotourl[color_id];
	var colorfotourlsmall = g_goods_m_colorfotourl_small[color_id];
	
	if(colorfotourlsmall && colorfotourl) addColorToGallery(colorfotourlsmall, colorfotourl);
	
	if(colorfotourl) {
		colorfotourl = 'pict/foto/' + colorfotourl;
		$('#goodsbigfotocont').height($('#goodsbigfoto').height());
		$('#goodsbigfoto').fadeOut('fast', function() {$('#goodsbigfoto').load(function() {$(this).fadeIn('fast');}); $('#goodsbigfoto').attr('src', colorfotourl); });
		$('#goodsbigfotocont').height($('#goodsbigfoto').height());
	}
	
	if(colorfotourlsmall && colorfotourl) generateGoodsFotoGallery(m_goodsfotocont.length-1);
	else generateGoodsFotoGallery(-1);
}

function testregform(form) {
	if(form.email.value.indexOf('@', 0) == -1) {
		alert('Не верный формат E-mail');
		return false;
	}
	
	/*if(document.getElementById('bdate3').value < 1900) {
		alert('Не верный год рождения');
		return false;
	}*/
	
	var ordersum = '{baskcost}';
	
	if(testForm(form)) {
		//if(ordersum<2000) return confirm('Уважаемый покупатель, напоминаем Вам о том, что сумма Вашего заказа менее 2000 руб и доставку Вы должны будете оплатить полностью. Если сумма Вашего заказа составит от 2 до 5 тыс. рублей, за доставку Вы оплатите только 50%. А если сумма заказа выше 5000 руб-то доставка для Вас будет бесплатна. Продолжить оформление?');
		//if(ordersum<5000) return confirm('Уважаемый покупатель, напоминаем Вам о том, что сумма Вашего заказа менее 5000 руб и доставку Вы должны будете оплатить на 50%. Если сумма заказа выше 5000 руб-то доставка для Вас будет бесплатна. Продолжить оформление?');
		
		return true;
	}
	
	return false;
}

function chWhere() {
	if(document.getElementById('where').value == 'другое') {
		document.getElementById('where2').value = '';
		document.getElementById('where2').style.display = '';
	} else {
		document.getElementById('where2').value = 'другое';
		document.getElementById('where2').style.display = 'none';
	}
}

function vidOplatiForRegion() {
	var vidoplregion = document.getElementById('vidoplregion');
	var vidopl = document.getElementById('vidopl');
	vidopl.disabled = 'disabled';
	vidopl.style.display = 'none';
	vidoplregion.disabled = '';
	vidoplregion.style.display = '';
}
function vidOplatiForMoscow() {
	var vidoplregion = document.getElementById('vidoplregion');
	var vidopl = document.getElementById('vidopl');
	vidoplregion.disabled = 'disabled';
	vidoplregion.style.display = 'none';
	vidopl.disabled = '';
	vidopl.style.display = '';
}

function zakazSelMoscow() {
	/*document.getElementById('city').style.display='none';
	document.getElementById('trmetro').style.display='';
	document.getElementById('trmetro2').style.display='';
	document.getElementById('trmetro3').style.display='';
	document.getElementById('trmetro4').style.display='';
	document.getElementById('trdostavkatime').style.display='';
	document.getElementById('trregion').style.display='none';
	E('trdaydostavka').style.display='';
	E('oformlenieform').sposob[0].disabled='';
	E('oformlenieform').sposob[1].disabled='disabled';
	E('oformlenieform').sposob[0].checked=true;
	vidOplatiForMoscow();*/
	dostavkacost();
}

function zakazSelRegion() {
 	/*document.getElementById('city').style.display='';
 	document.getElementById('trmetro').style.display='none';
 	document.getElementById('trmetro2').style.display='none';
 	document.getElementById('trmetro3').style.display='none';
 	document.getElementById('trmetro4').style.display='none';
 	document.getElementById('trdostavkatime').style.display='none';
 	document.getElementById('trregion').style.display='';
 	E('trdaydostavka').style.display='none';
 	E('oformlenieform').sposob[0].disabled='disabled';
 	E('oformlenieform').sposob[1].disabled='';
 	E('oformlenieform').sposob[1].checked=true;
 	vidOplatiForRegion();*/
 	dostavkacost();
}


var clientPC = navigator.userAgent.toLowerCase(); 
var clientVer = parseInt(navigator.appVersion); 

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
               && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
               && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

function mozillaWr(textarea, open, close) {
	var selLength = textarea.textLength;
	var selStart = textarea.selectionStart;
	var selEnd = textarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2)
	selEnd = selLength;
	
	var s1 = (textarea.value).substring(0,selStart);
	var s2 = (textarea.value).substring(selStart, selEnd)
	var s3 = (textarea.value).substring(selEnd, selLength);
	textarea.value = s1 + open + s2 + close + s3;
	
	textarea.selectionEnd = 0;
	textarea.selectionStart = selEnd + open.length + close.length;
	return;
}

function insert_into_position_cursor(text) {
	var textarea = document.form_newmsg.message;
	if (textarea.createTextRange && textarea.caretPos) 
	{
		var caretPos = textarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
	}
	else {
	if (is_nav && document.getElementById) 
	{
		mozillaWr(textarea, '', text);
	}
	else { textarea.value  += text; }
	}
	textarea.focus();
}

function copySelection() {
	if (window.getSelection)   { selection = window.getSelection().toString();}
	else if (document.getSelection) { selection = document.getSelection();}
	else if (document.selection) { selection = document.selection.createRange().text;}
}

function pasteHTML(html, win) {
 	if(win.getSelection) { // opera
		var selection = win.getSelection();
		var range = selection.getRangeAt(0);
		range.deleteContents();
		var newNode = win.document.createElement("span");
		newNode.innerHTML = html;
		range.insertNode(newNode);
	} else {
		if(win.document.selection.type!='Control') {
			var tr = win.document.selection.createRange();
			tr.pasteHTML(html);
		} else {
			var tr = win.document.selection.createRange();
			if(tr.item)
			if(tr.item(0)) {
				var tr2 = win.document.body.createTextRange();
				tr2.moveToElementText(tr.item(0));
				tr2.pasteHTML(html);
			}
		}
	}
}

function insertSmile(text) {
	/*text = '[smile' + text + ']';
	insert_into_position_cursor(text);*/
	E('messageframe').focus();
	pasteHTML('<img src="img/smiles/' + text + '.jpg" border="0" style="vertical-align:middle">', E('messageframe').contentWindow);
}

function insertSmile2(text) {
	text = '[smile' + text + ']';
	insert_into_position_cursor(text);
}

function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}


function animateAddToBask() {
	var img = E('goodsbigfoto');
	if (img) {
		var src = img.src;
		
		$(document.body).append('<img id="goodsbigfotoanimate" src="'+src+'">');
		
		$('#goodsbigfotoanimate').css('position', 'absolute');
		
		//$('#goodsbigfotoanimate').animate({'left':'500px'});
		//alert($('#goodsbigfoto').offset().left )
		var offset = $('#goodsbigfoto').offset();
		$('#goodsbigfotoanimate').css('top', offset.top + 'px');
		$('#goodsbigfotoanimate').css('left', offset.left + 'px');
		$('#goodsbigfotoanimate').css('z-index', '1000');
		
		var baskOffset = $('#topbask').offset();
		var baskX = baskOffset.left + $('#topbask').width() / 2;
		var baskY = baskOffset.top + $('#topbask').height() / 2;
		
		$('#goodsbigfotoanimate').animate({'left':baskX+'px', 'top':baskY+'px', 'opacity' : 0.5, 'width':'1px', 'height':'1px'}, 1200, function() {
			$('#goodsbigfotoanimate').remove();																							 
		});
		
	}
}
