//Определение браузера
opera = (window.opera)? true : false;	
dom = (document.getElementById)? true : false;
ie4 = (document.all && !dom)? true : false;
nn4 = (document.layers)? true : false;

var iTmpUserfile=0,u,oCmp,oResize;

var $j = jQuery.noConflict();

function isset(oObj)
{
	return typeof oObj!='undefined';
}
function jisset(oObj)
{
	return oObj.size()!=0;
}
function inArray(aArray,mVal)
{
	if(isset(aArray))
	{
	for(var i=0;i<aArray.length;i++)
	{
		if(aArray[i]==mVal)
			return true;
	}
	}
	return false;
}

function setCookie(cookieName, cookieValue)
{
	var date = new Date();
	cookieValue=escape(cookieValue);
	date.setTime(date.getTime()+864000*1000);//+10d
	document.cookie=cookieName+"="+cookieValue+"; expires="+date.toGMTString()+';path=/';
}

function deleteCookie(name) 
{
	var exp = new Date();
	exp.setTime (exp.getTime() - 1); 
	var cval = getCookieValue (name);
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString() + "; path=/;";
}

function getCookieValue(cookieName)
{
	var cookieValue = document.cookie,u;
	var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
	if(cookieStartsAt == -1)
	{
		cookieStartsAt = cookieValue.indexOf(cookieName + "=");
	}
	if(cookieStartsAt == -1)
	{
		cookieValue = u;
	}
	else
	{
		cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
  		var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
  		if(cookieEndsAt == -1)
  		{
   			cookieEndsAt = cookieValue.length;
  		}
  		cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
 	}
 	return cookieValue;
}

function init(){
	$j('.ishops-offers a.other').click(
		function()
		{
			$j(this).hide();
			$j('.ishops-offers div.other').show();
			return false;
		}
	);
	oResize=new Resize();
	if(oResize.hasExec())
	{
		$j(window).resize(oResize.onResize);
		oResize.onResize();
	}
	oCmp=new Cmp();
	if(typeof initLightbox=='function')
		initLightbox();
	addSrt();

    $j('.ishop .submit').click(
    	function()
    	{
    		var iOfferId=$j(this).parents('.ishop').find('input[name=offer_id]').attr('value');
    		location = '/order/'+iOfferId+'/';
    	}
    )
}

$j(document).ready(init);


function googleMapLoad()
{
	var oDiv=$j('#sc .compMap div');
	if(jisset(oDiv))
	{
		if(oDiv.attr('title')!="")
		{
			if(GBrowserIsCompatible())
			{
				$j('#sc .compMap').css('display', 'block');
				var oMap = new GMap2(oDiv.get(0));
				//var oMapCtrl=new GLargeMapControl();
				//var oMapTypeCtrl=new GMapTypeControl();
				//var oMapScaleCtrl=new GScaleControl();
//				oMap.addControl(new GLargeMapControl());
//				oMap.addControl(new GMapTypeControl());
//				oMap.addControl(new GScaleControl());
				
				var oGeocoder = new GClientGeocoder();
				if(oGeocoder)
				{
					oGeocoder.getLatLng(
	          			oDiv.attr('title'),
	          			function(point)
	          			{
	            			if(point)
	            			{
								oMap.setCenter(point, 15);
	              				var oMarker = new GMarker(point);
								oMap.addOverlay(oMarker);
								oMarker.openInfoWindowHtml('<b>'+$j('#sc h1').html()+'</b>'+oDiv.attr('title'));
	            			}
	          			}
	          		);
				}
			}
		}
	}
}

// Объект обработки операций равномерного раскидывания контейнеров td по tr, 
// в зависимости от ширины ориентировочного объекта
// для работы необходимы 
// фунции:
//	isset(var) - является ли переменная undefined
// библиотека:
//	jquery - http://jquery.com/
function Resize()
{
	var t=this;
	t.hasExec=function()
	{
		if((jisset(t.table))&&(jisset(t.items))&&(jisset(t.orientir)))
			return true;
		else
			return false;
	}	
	t.table=$j('#goods');
	if(!jisset(t.table))
		return false;
	t.items=t.table.find('td');
	t.iCols=3;
	t.iWidthItem=200;
	t.iWidthSpace=5;
	t.orientir=$j('table#content_table td:eq(0)');
	// возможно ли выполнять методы объекта на этой странице

	// метод выстраивающий теги td внутри tr
	t.onResize=function()
	{
		var iCols=Math.floor((t.orientir.width()-30)/(t.iWidthItem+t.iWidthSpace));
		iCols=iCols>0?iCols:1;
		var ix,iy,iRows=Math.ceil(t.items.size()/iCols),iWidth=100/iCols;
		if(t.iCols==iCols)
			return;
		t.iCols=iCols;
		for(iy=0;iy<iRows;iy++)
		{
			var oRow=t.table.find('tr:eq('+iy+')');
			if(oRow.size()==0)
			{
				oRow=$j(document.createElement('tr'));
				oRow.appendTo(t.table.find('tr:eq(0)').parent());
			}
			for(ix=0;ix<iCols;ix++)
				t.items.filter('td:eq('+(iy*iCols+ix)+')').appendTo(oRow);
		}
		if(t.items.size()<iCols)
		{
			t.table.width((t.items.size()*iWidth)+'%');
		}
		t.table.find('tr:gt('+(iRows-1)+')').remove();
		t.table.find('td').width(iWidth+'%');
	}
}



// Объект обработки операций выделения и сравнения товаров
// для работы необходимы 
// фунции:
//	isset(var) - является ли переменная undefined
//	inArray(arr,var) - находится ли значение переменной в массиве
//	getCookieValue(name) - получить значение определенной куки
//	setCookie(name,value) - сохранить значение определенной куки
// библиотека:
//	jquery - http://jquery.com/
function Cmp(){
var t=this;
// Селектор для основного контейнера, в который заключен список
t.mainList=$j("#goods");
// возможно ли выполнять методы объекта на этой странице
t.hasExec=function()
{
	if((jisset(t.mainList))&&(isset(t.mainList.attr('class'))))
		return true;
	else
		return false;
}
if(!jisset(t.mainList))
	return false;
// Селектор относительно основного контейнера, для выбора чекбоксов выбора
t.checkBoxes=t.mainList.find("input[id^='ch']");
// Ссылки кнопки "Сравнить"
t.links=$j('.btn_compare');
// Сообщение об ошибке, если не выбран не один товар, и нажата кнопка сравнить
t.error='Выберите из списка интересующие Вас товары и нажмите сравнить';
// Название куки, в которой храниться будет инфа
t.cookieName='compare';
// Получаем id каталога, в данном случае из класса основного контейнера, начиная с 4 символа
t.iPrntCat=parseInt(t.mainList.attr('class').substr(3));
// метод для обновления ссылок у кнопок "сохранить"
t.setBtnHref=function(aIds)
{
	var aMtchs=t.links.get(0).href.match(/^(.*?\/compare\/)([\d\-]+)?(\/)?$/);
	t.links.attr('href',aMtchs[1]+aIds.join('-')+((aIds.length!=0)?'/':''));
}
// событие выбора конкретного товара нажатием на чекбоксе
t.onCheck=function(input)
{
	var id=parseInt(input.id.substr(2));
	var oIds=t.getIds();
	if(!oIds)
		oIds={};
	if(isset(oIds[t.iPrntCat]))
	{
		if(input.checked)
			oIds[t.iPrntCat][oIds[t.iPrntCat].length]=id;
		else
			oIds[t.iPrntCat]=jQuery.map(oIds[t.iPrntCat], "a=="+id+"?null:a");
	}
	else
	{
		oIds[t.iPrntCat]=[id];
	}
	t.updIds(oIds);
	t.setBtnHref(oIds[t.iPrntCat]);
}
// событие нажатия на кнопку "Сравнить"	
t.onBtnClick=function()
{
	if(!t.hasSelected())
	{
		alert(t.error);
		return false;
	}
}
// метод для получения из кук объекта с данными о выбранных товарах
t.getIds=function()
{
	var sCmp=getCookieValue(t.cookieName);
	eval('var oCmp='+(isset(sCmp)?'{'+sCmp+'}':sCmp)+';');
	if(isset(oCmp))
		return oCmp;
	else
		return false;
}
// метод определения выбран ли хотябы один товар текущего каталога
t.hasSelected=function()
{
	var oCmp=t.getIds();
	return isset(oCmp[t.iPrntCat])&&oCmp[t.iPrntCat].length!=0;
}
// метод сохранения информации о выбранных товарах
t.updIds=function(oIds)
{
	var sCmp="",index=0;
	for(var i in oIds)
	{
		if(index!=0)
			sCmp+=',';
		sCmp+="'"+i+"':[";
		for(var ii=0;ii<oIds[i].length;ii++)
		{
			if(ii!=0)
				sCmp+=',';
			sCmp+=oIds[i][ii];
		}
		sCmp+=']';
		index++;
	}
	setCookie(t.cookieName,sCmp);
}
// инициализирующие действия
var oIds=t.getIds();
if((oIds)&&(isset(oIds[t.iPrntCat])))
{
	// обновим ссылки кнопок "Сравнить"
	t.setBtnHref(oIds[t.iPrntCat]);
	// проставим выбранные чекбоксы
	t.checkBoxes.each(
		function(){
			var id=parseInt(this.id.substr(2));
			if(inArray(oIds[t.iPrntCat],id))
			{
				this.checked=true;
			}
		}
	);
}
}

function chImg(img_id)
{
	try
	{
		var img=document.getElementById('m_img_'+img_id);
		var wrap=document.getElementById('goodPicWrapp');
		if(wrap.childNodes[0].id!=img.id)
		{
			replaced=wrap.replaceChild(img, wrap.childNodes[0]);
			var lb_imgs=document.getElementById('lb_imgs');
			lb_imgs.appendChild(replaced);
		}
	}
	catch(e){}
	return false;
}

function addSrt()
{
	var nav=$j("div[class^='srt']"),iStr;
	if(jisset(nav))
	{
		iSrt=nav.attr('class').substr(3);
//	else
//		iSrt=Math.round(Math.random()*100);
		var links=$j('#pagger a');
//	if(!window.location.href.match(/srt\=/))
//	{
		links.each(
			function(){
				if(this.href.match(/^.*?\?.*?$/))
					this.href+='&srt='+iSrt+'#pdtlist';
				else
					this.href+='?srt='+iSrt+'#pdtlist';
			}
		);
	}
}

function notepad(id) 
{
	if(id=='0')
	{
		win_notepad=window.open('/notepad/','notepad','scrollbars=1,resizable=1,width=600, height=500,toolbar=0');
	}
	else{
    	win_notepad=window.open('/notepad/?product_id='+id,'notepad','scrollbars=1,resizable=1,width=600, height=500,toolbar=0');
  	}	 
	win_notepad.window.focus();
}

//описание характеристики 
 function hint(id)
 {
  win_hint=window.open('/catalog/hint/'+id+'/','hint','scrollbars=1,resizable=1,width=400, height=300,toolbar=0');
  win_hint.window.focus();
 } 

//описание характеристики 
 function info(id)
 {
  win_hint=window.open('/info/win/'+id+'.html','infopopup','scrollbars=1,resizable=1,width=600, height=500,toolbar=0');
  win_hint.window.focus();
 } 


 
function main(url)
{
  window.opener.location.href=url;
  window.opener.focus(); 
}

function basket_var(id) 
{
 sel='b_var'+id;
 element = document.getElementById(sel);
 
 for (i=0; i < element.length; i++) 
 {
   if (element.options[i].selected == true)
   { 
    select_id=element.options[i].value;
   } 
 }
   window.location.href='/user/basket/?add='+select_id; 
  
}

function act_submit(i_id,id) {
if(dom){
	def=document.getElementById(i_id);
	subm=document.getElementById(id);
	if(def.value.length>=0)
     subm.disabled=false; 
	else
     subm.disabled=true; 
	} 
	 
}


function email (login, serv)
{
 	var serv = new Array;
	if(serv=="") serv="risk.ru";
	eml = login +  "@" + serv;
	return eml;
}

function ml(sUser,sDomain,sText)
{
	var sAddr=sUser+'@'+sDomain;
	document.write('<a href="mailto:'+sAddr+'">'+((typeof sText=='undefined')?sAddr:sText)+'</a>');










}

function mylo (login, serv)
{
 document.write (email(login, serv));
}

function namylo (login, serv, subj)
{
eml = "mailto:" + email(login, serv);
re= /\s/;
while(subj.search(re)>0)
subj=subj.replace(re, "%20");

if (subj != "") eml += "?subject=" + subj;
window.location.href = eml;
}

function go_search(id) 
{
 var q;
 var url;
 q = document.getElementById(id).value;
 url='/search/index.php?str=1&q='+q;
 window.location=url;
 win=top.location.href=url;
// win.window.focus();
}

/*function init()
{
//	init_pagination();
	try{
		setProdHeight();
		showCommentForm();
		initLightbox();
	}catch(e){};
}*/

function showCommentForm()
{
	if(location.hash.match(/create\_reply/))
	{
		var aMatches=location.hash.match(/^(\#)?create\_reply(\d+)$/),iMessageId=aMatches[2];
		var oForm=document.getElementById('response_form');
		var iProductId=oForm.elements['product'].value;
		showResponseForm(iMessageId,iProductId);
		location.hash='reply'+iMessageId;
	}
}

function setProdHeight()
{
	var tag = 'li', // тег с товаром
	className = 'goodBlock', // класс тега с товаром
	tags = document.getElementsByTagName(tag), i, maxHeight = 0, gtags = [];
	for(i in tags)
	{
		if(typeof tags[i].className != 'undefined')
		{
			if(tags[i].className.substr(0,className.length) == className)
			{
				gtags[gtags.length] = tags[i];
				if(maxHeight < tags[i].offsetHeight)
				{
					maxHeight = tags[i].offsetHeight;
				}
			}
		}
	}
	if(gtags.length>0)
	{
		var dy=0;
		for(i in gtags)
		{
			var imgs=gtags[i].getElementsByTagName('img');
			if(typeof imgs[0]!='undefined')
			{
				dy=imgs[0].offsetHeight;
				break;
			}
		}
		if(dy == 40)
		{
			maxHeight-=dy;
		}
		for(i in gtags)
		{
			gtags[i].style.height = (maxHeight) + "px";
	//		gtags[i].style.minHeight = maxHeight + 100;
		}
	}
	
}
function actualCollection()
{
	var o_form=document.getElementById('scfilter');
	o_form.collection[0].checked=true;
	o_form.submit();
}
function archiveCollection()
{
	var o_form=document.getElementById('scfilter');
	o_form.collection[1].checked=true;
	o_form.submit();
}

function addFile(oContext)
{
	if(document.getElementById)
	{
		var oDivs=oContext.getElementsByTagName("div"),i;
		for(i in oDivs)
		{
			if(oDivs[i].className=='files')
			{
				oFiles=oDivs[i];
				break;
			}
		}
		var tpl=oFiles.firstChild,newNode=tpl.cloneNode(true);
		var aInputs = newNode.getElementsByTagName('input');
		for(i in aInputs)
		{
			if(aInputs[i].type=='file')
			{
				aInputs[i].name+=iTmpUserfile;
				iTmpUserfile++;
//				alert(aInputs[i].name);
				break;
			}
		}		
		oFiles.appendChild(newNode);
		checkEdge(oContext);
	}
}

function delFile(oBut, oContext)
{
	if(document.getElementById)
	{
		var tmp=oBut;
		while(tmp.tagName!="DIV")tmp=tmp.parentNode;
		tmp.parentNode.removeChild(tmp);
		checkEdge(oContext);
	}
}

function showResponseForm(iResponseId, iProductId)
{
	if(document.getElementById)
	{
		try
		{
			var oForm=document.getElementById("response_form");
			var oCloneForm = oForm.cloneNode(true);
			var oTmp;
			if(oTmp=getElementByClass(oCloneForm,'mark_block'))
			{
				oTmp.removeNode(true);
			}			
			if(oTmp=getElementByClass(oCloneForm,'responseLabel'))
			{
				oTmp.innerHTML='Новый комментарий:';
			}
			var sHtml=oCloneForm.innerHTML;
			sHtml+='<input type="hidden" value="'+iResponseId+'" name="response_id"/><input type="button" onclick="hideResponseForm('+iResponseId+')" value="Отмена">';
			oDest=document.getElementById('for_reply'+iResponseId);
			oDest.innerHTML = '<form method="post" onSubmit="return(validateResponse(this,'+iProductId+'));" id="response_form'+iResponseId+'" enctype="multipart/form-data">'+sHtml+'</form>';
			document.getElementById('responseBtn'+iResponseId).style.display='none';
		}
		catch(e){}
	}
}

function getElementByClass(oObj, sClass)
{
	if(typeof oObj!='object')
	{
		return false;
	}
	var oDivs=oObj.childNodes,i;
	for(i=0;i<oDivs.length;i++)
	{
		if(oRet=getElementByClass(oDivs[i], sClass))
		{
			return oRet;
		}
		if(oDivs[i].className==sClass)
		{
			return oDivs[i];
		}
	}
	return false;
}

function hideResponseForm(iResponseId)
{
	if(document.getElementById)
	{
		try
		{
			oForm=document.getElementById("response_form"+iResponseId);
			oForm.removeNode(true);
			document.getElementById('responseBtn'+iResponseId).style.display='';
		}
		catch(e){}
	}
}

function checkEdge(oContext)
{
	var aInputs=oContext.getElementsByTagName("input"),disValue,i,aAddBtns=[],aDelBtns=[];
	var oDivs=oContext.getElementsByTagName("div");
	for(i in oDivs)
	{
		if(oDivs[i].className=='files')
		{
			oFiles=oDivs[i];
			break;
		}
	}
	
	for(i in aInputs)
	{
		if(aInputs[i].className=='add_file')
		{
			aAddBtns[aAddBtns.length]=aInputs[i];
			continue;
		}
		if(aInputs[i].className=='del_file')
		{
			aDelBtns[aDelBtns.length]=aInputs[i];
			continue;
		}
	}
	
	if(oFiles.childNodes.length == 3)
	{
		disValue=true;
	}
	else
	{
		disValue=false;
	}
	for(i=0;i<aAddBtns.length;i++)
	{
		aAddBtns[i].disabled=disValue;
	}
	
	if(oFiles.childNodes.length == 1)
	{
		disValue=true;
	}
	else
	{
		disValue=false;
	}
	for(i=0;i<aDelBtns.length;i++)
	{
		aDelBtns[i].disabled=disValue;
	}
}

function markResponse(iResponseId,eMark)
{
    JsHttpRequest.query(
        '/mark_response.php', // backend
        {
            'iResponseId':iResponseId,
            'eMark':eMark
        },
        function(result, errors)
        {
            document.getElementById("response_mark"+iResponseId).innerHTML = result["iMark"]; 
            document.getElementById("mark_response_inc"+iResponseId).disabled = true;
            document.getElementById("mark_response_inc"+iResponseId).className += ' disabled';
            document.getElementById("mark_response_dec"+iResponseId).disabled = true; 
            document.getElementById("mark_response_dec"+iResponseId).className += ' disabled';
        },
        true  // disable caching
    );
}
function validateResponse(oForm, i_product_id)
{
	try
	{
		var sEmail=oForm.elements['email'].value;
		if((sEmail=='') || (!sEmail.match(/^.*?@.*?\..*?$/)))
		{
			alert('Поле Email содержит неверное значение');
			return false;
		}
		if(oForm.elements['text'].value == '')
		{
			alert('Поле Текст обязательно для заполнения');
			return false;
		}
		
		if(typeof oForm.elements['response_id'] == 'undefined')
		{
			if(
				(
					(typeof oForm.elements['type'][0] != 'undefined')
					&&
					(oForm.elements['type'][0].type == 'radio')
					&&
					(oForm.elements['type'][0].checked)
				)
				||
				(
					(oForm.elements['type'].type == 'hidden')
					&&
					(oForm.elements['type'].value == 2)
				)
			)				
			{
				if(oForm.elements['mark'].value == 0)
				{
					alert('Пожалуйста оцените товар');
					return false;
				}
			}
		}
		else
		{
			
			var oSend={
				'iResponseId':oForm.elements['response_id'].value,
		        'sEmail':oForm.elements['email'].value,
		        'sName':oForm.elements['name'].value,
		        'sText':oForm.elements['text'].value,
		        'iProductId':i_product_id
			};
			
			var oFiles=[];
			var aInputs = oForm.getElementsByTagName('input');
			var index = 0;
			for(i=0;i<aInputs.length;i++)
			{
				if(aInputs[i].type=='file')
				{
					oSend['file'+index]=aInputs[i];
					index++;
				}
			}
			
		    JsHttpRequest.query(
		        '/send_response.php', // backend
		        oSend,
		        function(result, errors)
		        {
		        	if(result['done'])
		        	{
		        		if(typeof result['location'] != 'undefined')
		        		{
		        			window.location = result['location'];
		        			window.location.reload(true);
		        			return;
		        		}
		        		hideResponseForm(result['response_id']);
		        		document.getElementById('for_reply'+result['response_id']).innerHTML = result['msg'];
		        	}
		        	else
		        	{
		        		alert(result['msg']);
		        	}
		        },
		        true  // disable caching
		    );
		    return false;
		}
		return true;
	}
	catch(e)
	{
		return true;
	}
}

if(window.HTMLElement)
{
	HTMLElement.prototype.removeNode = function(removeChildren) {
	  if (Boolean(removeChildren))
	    return this.parentNode.removeChild(this);
	  else {
	    var r=document.createRange();
	    r.selectNodeContents(this);
	    return this.parentNode.replaceChild(r.extractContents(),this);
	  }
	}
}
function show_all_brands(oThis)
{
	try
	{
		document.getElementById('brands_hide').style.display="block";
		oThis.style.display="none";
	}
	catch(e){};
}
