function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = false;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}
function getBrowserInfo() {
 var t,v = undefined;
 if (window.opera) t = 'Opera';
 else if (document.all) {
  t = 'IE';
  var nv = navigator.appVersion;
  var s = nv.indexOf('MSIE')+5;
  v = nv.substring(s,s+1);
 }
 else if (navigator.appName) t = 'Netscape';
 return {type:t,version:v};
}

function bookmark(a){
 var url = 'http://planetashop.ru/';
 var title = 'Интернет-магазин Planetashop.ru';
 var b = getBrowserInfo();
 if (b.type == 'IE' && 7 > b.version && b.version >= 4) window.external.AddFavorite(url,title);
 else if (b.type == 'Opera') {
  a.href = url;
  a.rel = "sidebar";
  a.title = url+','+title;
  return true;
 }
 else if (b.type == "Netscape") window.sidebar.addPanel(title,url,"");
 else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки.");
 return false;
}

function submit_search() {
	url='/search/'+encodeURIComponent(document.srch.search.value)+'/index.html';
	document.location.href=url;
}

//	Сравнение товаров
function done_compare(){
	jQuery.post('/action/compare.php', {'action':'get_url'}, function(s){
		s=jsonDecode(s);
		if(s.status){
		//alert(s.url);			 window.open(s.url, '_self');}
		else{ jAlert(s.text, {'title':'Ошибка!'}); }
	});
}

function buildCompare(a){	buf='';
	for(i in a){		buf+='<font color="#658bc4" style="overflow:hidden;width:180px;display:block">'+a[i]+'</font> ';
		buf+='<a style="color:#900" href="javascript:delete_comp('+i+')">';
		buf+='<img src="/img/delete.gif" border="0" alt="удалить" align="right" /></a><hr style="color:#b1b1b1">';
	}
	if(buf) return buf; else return false;
}

function add_comp(id, o){
	if(o.checked) jQuery.post('/action/compare.php', {'ware':id, 'action':'add'}, function(s){
		s=jsonDecode(s);
		if(s.status){
			str=buildCompare(s.items);
			jQuery('#conter').html(str);
			jQuery('#compareTD').slideDown('slow');
		} else {			jAlert(s.text, {'title':'Ошибка!'});
			o.checked=false;
		}
	}); else delete_comp(id);
}

function delete_comp(id){
	jQuery.post('/action/compare.php', {'ware':id, 'action':'delete'}, function(s){
		s=jsonDecode(s);
		if(s.status){
			$('#compare'+id).attr('checked', '');
			if(s.numitems>0){				str=buildCompare(s.items);
				jQuery('#conter').html(str);
			} else jQuery('#compareTD').slideUp();
		} else jAlert(s.text, {'title':'Ошибка!'});
	});
	if(window.location.href.indexOf("compare")!=-1) done_compare();
}

function clear_comp(){
	jQuery.post('/action/compare.php', {'action':'clean'}, function(s){
		s=jsonDecode(s);
		if(s.status){			jQuery('#compareTD').slideUp();
			if(window.location.href.indexOf('compare')!=-1) document.location.replace('/');
				else jQuery('.compare').attr('checked', '');
		} else jAlert(s.text, {'title':'Ошибка!'});
	});
}
//-----------------------------------------------------------------------------------------------------------

//  jQuery функции
function jsonEncode(s){ return eval('('+s+')'); }
function jsonDecode(s){ return eval('('+s+')'); }

function checkForm(form, mustform){	error=0;
	if(mustform){
		for(i in mustform) if(form.elements[mustform[i]]){
			if(!form.elements[mustform[i]].value){
				error=1;
				jQuery(form.elements[mustform[i]]).next().remove();
				jQuery(form.elements[mustform[i]]).parent().append('<div style="color:red">поле обязательно к заполнению</div>');
			} else jQuery(form.elements[mustform[i]]).next().remove();
		}
		if(error>0) return false; else return true;
	} else return true;
}

// Отправка формы через AJAX
// !!! не сделан RADIO и FILE
function sendForm(url, form, callback){	if((url)&&(form)){		var param={};
		var k=0;
		$('input:checkbox:checked', form).each(function(){
			param[this.name.replace('[]', '['+k+']')]=this.value;
			k++;
		});
		$('input:radio:checked', form).each(function(){
			param[this.name]=this.value;
		});
		for(i in form.elements) if(form.elements[i] && form.elements[i].type) {
			if(form.elements[i].type!='checkbox' && form.elements[i].type!='radio'){
				param[form.elements[i].name]=form.elements[i].value;
			}
		}
		if(callback) jQuery.post(url, param, callback); else jQuery.post(url, param);
	}
}

// сохранение комментария к товару
function saveOpinion(form){
	error=0;
	if(!form) return false;
	if(!checkForm(form, ['wareid', 'nam', 'body_r'])) $('div:first', form).html('Вы не заполнили обязательные поля!'); else {
		sendForm('/action/save_opinion.php', form, function(s){
			s=jsonEncode(s);
			if(s.status){
				form.reset();
				$('div:first', form).html('');
				jAlert('<div style="padding:20px 0px 25px 0px">'+s.text+'</div>', {'lifetime':4, 'buttons':false});
			} else $('div:first', form).html(s.text);
		});
	}
	return false;
}

// отправка сообщения обратной связи
function sendFeedback(mustform, form){	error=0;
	if(!form) return false;
	if(!checkForm(form, mustform)) $('div:first', form).html('Вы не заполнили обязательные поля!'); else {
		sendForm('/action/feedback.php', form, function(s){			s=jsonEncode(s);
			if(s.status){				form.reset();
				$('div:first', form).html('');
				jAlert('<div style="padding:20px 0px 25px 0px">Ваше сообщение успешно отправлено менеджеру</div>', {'lifetime':4, 'buttons':false});
			} else $('div:first', form).html(s.text);
		});
	}
}

// переключение в режим Версия для печати и обратно
function printVersion(){	if($('#printVersion').length>0){		$('#printVersion').remove();
		$('body .hideBeforePrint').removeClass('hideBeforePrint').show();
	} else {
		$('body').children(':visible').addClass('hideBeforePrint').hide();
		tmp='<div id="printVersion"><table width="100%" cellspacing="0" cellpadding="0" style="background-color:#297FBA">';
		tmp+='<tr><td><h4 style="color:white; font-family:Arial; font-size:12pt">Версия для печати</h4></td>';
		tmp+='<td align="center" valign="middle" width="120">&nbsp;</td><td align="center" width="120">';
		tmp+='<a style="color:white; text-decoration:none" href="javascript:printVersion()">Вернуться на сайт</a>';
		tmp+='</td></tr></table><img src="/img/print_logo1.gif" style="margin-bottom:10px" hspace="20" /><div style="margin:0px 2% 0px 2%"></div></div>';
		$('body').append(tmp);
		$('.printVersion').clone().appendTo($('#printVersion div:first'));
		tmp='<br /><table cellspacing="0" cellpadding="0" bgcolor="#297FBA" align="center" width="130" height="20"><tr>';
		tmp+='<td align="center" valign="middle">';
		tmp+='<a style="color:white; text-decoration:none;" href="javascript:printVersion()">Вернуться на сайт</a>';
		tmp+='</strong></a></td></tr></table><br />';
		$('#printVersion').append(tmp);
		$('#printVersion .noPrintVersion').remove();
		setTimeout('window.print()', 200);
	}
}

// Добавление товара в корзину
function add2basket(ware){	if(ware) $.post('/action/basket.php', {'action':'add', 'ware':ware}, function(s){		s=jsonEncode(s);
		if(s.status){			tmp=s.name+'<br /><br /><table width="100%"><tr><td><a href="javascript://" onclick="$.alerts._hide()"><strong>Продолжить ';
			tmp+='покупки</strong></a></td><td align="right" nowrap="nowrap"><a href="/content/order/f_name/basket/index.html">';
			tmp+='<strong>Перейти в корзину и оформить заказ</strong></a></td></tr></table>';
			jAlert(tmp, {'title':'Товар добавлен в корзину', 'buttons':false, 'width':600});
			$.post('/action/basket.php', {'action':'refresh'}, function(s){ $('#basket').html(s); });
		} else jAlert(s.text, {'title':'Ошибка!'})
	});
}

//	добавление товара в блокнот
function add2note(ware, o, callback){
	if(ware) $.post('/action/note.php', {'action':'add', 'ware':ware}, function(s){
		s=jsonEncode(s);
		if(s.status){
			if(callback) callback(o);
			$('#cabinetlinks .note').show();
		} else jAlert(s.text, {'title':'Ошибка!'})
	});
}

//	рейтинг товара
function rateWareForm(ware){	var tmp='<center>Оцените, пожайлуста, этот товар по 5-бальной шкале<br /><br /><br />';
	for(var i=1; i<6; i++) tmp+='<img src="/img/star0.gif" onclick="rateWare('+ware+', '+i+')" onmouseover="rateRefresh(this)" onmouseout="rateRefresh(this)" />';
	tmp+='<br /><br /></center>';
	jAlert(tmp, {'buttons':false});
}
function rateRefresh(o){	var tmp=2;
	$('img', o.parentNode).each(function(){		this.src='/img/star'+tmp+'.gif';
		if(this==o) tmp=0;
	});
}
function rateWare(ware, rate){	$.post('/action/all.php', {'action':'rating', 'ware':ware, 'rate':rate}, function(s){		s=jsonDecode(s);
		if(s.status){			$('span.rating-card').html(s.html);
			$('tr.ware'+ware+' div.rating-list').html(s.html);
			jAlert(s.text, {'lifetime':3});
		} else jAlert(s.text, {'title':'Ошибка!'});
	});
}

//	изменение типа доставки
function changeDelivery(){
	$.post('/action/basket.php', {'action':'delivery_form'}, function(s){ jAlert(s, {'buttons':false, 'title':'Выбор доставки'}); });
}

// отправка сообщения об ошибке на сайте
function errorSend(form){
	sendForm('/action/feedback.php', form, function(s){
		s=jsonDecode(s);
		if(s.status) jAlert('Благодарим Вас за помощь в улучшении нашего сайта.', {'lifetime':4});
		else $('div.error', form).html(s.text);
	});
}

//-----------------------------------------------------------------------------------------------------------------------
var keypress=0;

document.onkeydown=function(s){
	if(s) event=s;

	// функция "Сообщите об ошибке"
	if(keypress==17 && event.keyCode==69){
		var txt = '';
		if(txt = window.getSelection) // Not IE, используем метод getSelection
			txt = window.getSelection().toString();
		else // IE, используем объект selection
			txt = document.selection.createRange().text;
		if(txt){
			while(txt.indexOf("\n")>-1) txt=txt.replace("\n", '<br />');
			var text='<form onsubmit="return false"><div class="error"></div>Исходный текст:';
			text+='<div style="overflow:auto; width:100%; height:150px; border:1px solid #666666; padding:3px 5px 3px 5px">';
			text+=txt+'</div><br />Комментарий к ошибке:<textarea name="comment" rows="4" style="width:100%"></textarea>';
			text+='<br /><br />Ваш Email (не публикуется):<br /><input type="text" name="email" size="55" />';
			text+='<textarea name="source" style="display:none">'+txt+'</textarea>';
			text+='<input type="hidden" name="action" value="error_save" />';
			text+='<input type="hidden" name="page" value="'+document.location.href+'" />';
			text+='<br /><br /><center><input type="button" value="Отправить сообщение" onclick="errorSend(this.form)" />';
			text+=' <input type="button" value="Отмена" onclick="$.alerts._hide()" /></center></form>';
			jAlert(text, {'buttons':false, 'title':'Сообщение об ошибке', 'width':500});
		} else jAlert('Вы не выделили текст, содержащий ошибку', {'title':'Ошибка!'});
	}
	keypress=event.keyCode;
};
document.onkeyup=function(){ keypress=0; };
