var criticalSection = false;

function _gel(id) { return document.getElementById(id);}

var BasketUpdateLinkClick = function(e) {
	if (!criticalSection) {
		criticalSection = true;
		
		$('#Basket').html("загрузка…");
		
		var updaterow = this.getAttribute('rowid');
		var action = this.getAttribute('action');
		var url = this.href + '&ajax=1';
		
		if (updaterow) {
			updaterow = '#BasketControls-' + updaterow;
			$(updaterow + ' .add').hide();
			$(updaterow + ' .del').hide();
			$(updaterow + ' .load').show();
			
			$('#Basket').load(url, {}, function() {
				$(updaterow+' .load').hide();
				if (action=='add') {
					$(updaterow + ' .add').hide();
					$(updaterow + ' .del').show();
				} else {
					$(updaterow + ' .add').show();
					$(updaterow + ' .del').hide();
				}
				$('#BasketList a.ajax').click(BasketUpdateLinkClick);
				criticalSection = false;
			});
		}

		e.preventDefault();
		e.stopPropagation();
	}
	return false;
}

var PopupWindowCount 		= 0;
var PopupWindowTop			= [];
var _hSubmitCallTimer 		= 0;
var	_hSubmitCallValidate 	= false;

function PopupWindow() {
	this._id = PopupWindowCount.toString() + "window";
	this._self = $("<table class='popup' id='" + this._id + "'><tbody><tr><td class='p11'></td><td class='p12'></td><td class='p13'></td></tr><tr><td class='p21'></td><td class='p22'></td><td class='p23'></td></tr><tr><td class='p31'></td><td class='p32'></td><td class='p33'></td></tr></tbody></table>");
	this._self.appendTo("body");
	this._self.css("z-index", 2000 + PopupWindowCount);
	this._content = this._self.children("tbody").children("tr").children("td.p22");
	PopupWindowCount++;
	
}

PopupWindow.prototype = {
	_is_display:		false,
	_is_opera:			(jQuery.browser.opera && jQuery.browser.version.substr(0,3) == "9.2"),
	_is_ie6:			(jQuery.browser.msie && parseInt(jQuery.browser.version) < 7),
	
	/*
		Показывает всплывающее окошко
		var speed 	- скорость в миллисекундах
	*/
	Display: function(speed) {
		if(!PopupWindow._is_display) {
			speed = parseInt(speed);
			this._self.show();
			if(speed > 0) {
				this._self.css({opacity: "0"});
				this._self.animate({opacity: "1"}, speed);
			}
			this._is_display = true;
		}
	},
	
	/*
		Прячет всплывающее окошко
		var speed 	- скорость в миллисекундах
	*/
	Hide: function(speed) {
		if(this._is_display) {
			this._self.hide();
			this._is_display = false;
		}
	},
	
	/*
		Закрывает окно
	*/
	Close: function()
	{
		this._self.remove();
		this._self = false;
		this._content = false;
		this._is_display = false;
	},
	
	/*
		Исправляет баг в 9 опере с прорисовкой окна
	*/
	FixOpera: function()
	{
		if(this._is_opera && this._self) {
			this.Hide();
			this.Display();
		}
	},
	
	/*
		Устанавливает контент в окне
		data	- данные
	*/
	SetContent: function(data)
	{
		if(data && this._self) {
			this._content.html(data);
			this.FixOpera();
		}
	},
	
	/*
		Показывает окно
		x	- координата x
		y	- координата y (от левого верхнего угла страницы)
		width - ширина контента
		height - высота контента
		speed - скорость, с которой показывать окно
		is_right - x отчитывается с правого края
		is_bottom - у отчитывается снизу
		is_fixed  - фиксированная позиция всплавающего окна 
		is_center - устанавливаем посередине окна
	*/
	DisplayTo: function(x, y, width, height, speed, is_right, is_bottom, is_fixed, is_center)
	{
		if(!this._self) {
			return;
		}
		
		if(is_center) {
			x = "50%";
			if(width.toString().indexOf("%") != -1) {
				this._self.css("marginLeft", "-" + (parseInt(width) / 2) + "%");
			} else {
				this._self.css("marginLeft", "-" + (parseInt(width) / 2) + "px");
			}
			
			y = "50%";
			if(height.toString().indexOf("%") != -1) {
				this._self.css("marginTop", "-" + (parseInt(height) / 2) + "%");
			} else if (height) {
				this._self.css("marginTop", "-" + (parseInt(height) / 2) + "px");
			}
		} else {
			this._self.css({marginLeft: "0", marginTop: "0"});
		}

		if(width) {
			this._self.css("width", width);
		}
		if(height) {
			this._self.css("height", height);
		}
		
		if(is_fixed) {
			if(this._is_ie6) {
				if(is_bottom) {
					this._self.addClass("popup_ie6_bottom");
				} else {
					if(is_center) {
						this._self.addClass("popup_ie6_center");
					} else {
						this._self.addClass("popup_ie6");
					}
				}
			} else {
				this._self.css("position", "fixed");
			}
		} else {
			this._self.css("position", "absolute");
			if(this._is_ie6) {
				this._self.removeClass("popup_ie6");
				this._self.removeClass("popup_ie6_center");
				this._self.removeClass("popup_ie6_bottom");
			}
		}
		
		if(is_right) {
			this._self.css({left: "auto", right: x});
		} else {
			this._self.css({left: x, right: "auto"});
		}
		
		if(is_bottom) {
			PopupWindowTop[parseInt(this._id)] = parseInt(y);
			if(!(is_fixed && this._is_ie6)) {
				this._self.css({top: "auto", bottom: y});
			}
		} else {
			PopupWindowTop[parseInt(this._id)] = parseInt(y);
			if(is_center) {
				PopupWindowTop[parseInt(this._id)] = 0;
			}
			if(!(is_fixed && this._is_ie6)) {
				this._self.css({top: y, bottom: "auto"});
			}
		}
		
		this.Display(speed);
		
		if(!is_bottom && is_fixed && is_center && !height) {
			this._self.css("marginTop", "-" + (parseInt(this._self.height()) / 2) + "px");
		}
	},
	
	/*
		Показывает окно с заданным заголовком и кнопкой закрыть
		header - заголовок окна
		is_close - показывать или нет кнопку закрытия окошка
		x	- координата x
		y	- координата y (от левого верхнего угла страницы)
		width - ширина контента
		height - высота контента
		speed - скорость, с которой показывать окно
		is_center - отображает окно по центру
		is_right - x отчитывается с правого края
		is_bottom - у отчитывается снизу
		is_fixed  - фиксированная позиция всплавающего окна 
		callback_on_close  - функция, которая вызывается при закрытии окна
	*/
	SimpleDisplayTo: function(header, content, x, y, width, height, speed, is_center, is_right, is_bottom, is_fixed, callback_on_close)
	{
		if(!this._self) {
			return;
		}

		this.SetContent("<a href='#' class='popup_simple_close'><img src='/irdm/popup/close.gif'></a><h3 class='popup_simple_h3'>" + header +"</h3><div class='popup_simple_content'>" + content + "</div>");
		$(this._content.children("a.popup_simple_close").get(0)).bind("click", (function(object, callback_on_close){
			return function(){
				if(typeof callback_on_close == "function") {
					callback_on_close.call(object);
				}
				object.Hide();
				return false;
			};
		})(this, callback_on_close));
		this.DisplayTo(x, y, width, height, speed, is_right, is_bottom, is_fixed, is_center);
		this.FixOpera();
	},
	
	/*
		Устанавливает контент, если ранее уже что-то было
	*/
	SimpleSetContent: function(content, header)
	{
		if(!this._self) {
			return;
		}
		
		if(content) {
			$(this._content.children("div.popup_simple_content").get(0)).html(content);
			this.FixOpera();
		}
		if(header) {
			$(this._content.children("h3.popup_simple_h3").get(0)).html(header);
			this.FixOpera();
		}
	}
}

	/*
		Отобразим приглашение в чат, если страница была загружена более 3-х раз 
		или пользователь находится на странице более 3-х минут
	*/
	
function LocalStorage() {
	
	var current_date 			= new Date();
	this._window				= false;
	this._cookie_name 			= "local_storage";
	this._LastTimeVisit 		= current_date.getTime();
	this._AllPagesVisited 		= 1;
	this._LastTimeDisplay		= 0;
	this.ps_Image				= new Image();
	this.ps_sid					= this.LiveChatGetTsid();
	this.ps_s				 	= (new Date()).getTime();
	this.ps_ol					= true;
	this.ps_op					= false;
	this.ps_Image.onload 		= (function(object1){
										return function() {
											object1.LiveChatGetInf(object1);
										}
									})(this);
	//this.ps_Image.onload 		= this.LiveChatGetInf;
	
	var cookie_value = " " + document.cookie + ";"
	var i = cookie_value.indexOf(this._cookie_name);
	if(i > -1) {
		i += (this._cookie_name.length + 1);
		var local_storage_data = unescape(cookie_value.substring(i, cookie_value.indexOf(";", i))).split(";");
		
		if(typeof local_storage_data[0] != "undefined") {
			local_storage_data[0] = parseInt(local_storage_data[0]);
			
			// Если с предыдущего посещения проло не больше 3х часов
			if(local_storage_data[0] < current_date.getTime() && local_storage_data[0] > current_date.getTime() - 10800000) {
				this._LastTimeVisit = local_storage_data[0];
				
				if(typeof local_storage_data[1] != "undefined") {
					local_storage_data[1] = parseInt(local_storage_data[1]);
					if(local_storage_data[1] > 0 && local_storage_data[1] < 50) {
						this._AllPagesVisited = local_storage_data[1];
					}
				}
				
				if(typeof local_storage_data[2] != "undefined") {
					local_storage_data[2] = parseInt(local_storage_data[2]);
					if(local_storage_data[2] < current_date.getTime() && local_storage_data[2] > current_date.getTime() - 10800000) {
						this._LastTimeDisplay = local_storage_data[2];
					}
				}
			}
		}
	}
	
	this.SaveData();
}

LocalStorage.prototype = {
	/*
		Сохряняет данные в кукисы 
	*/
	SaveData: function(is_display) {
		var current_date = new Date();
		if(is_display) {
			this._LastTimeDisplay = current_date.getTime();
		}
		document.cookie = this._cookie_name + "=" + escape(current_date.getTime() + ";" + (this._AllPagesVisited + 1) + ";" + this._LastTimeDisplay) + "; expires=Mon, 01-Jan-2038 00:00:00 GMT; path=/";
	},
	
	/*
		Отображает окно
	*/
	ShowWindow: function(header, content, always_display, callback_on_close, no_check) {
		if(!this._LastTimeDisplay || always_display) {
			// check, is operator online 
			if(!no_check && !always_display) {
				this.LiveChatCheckOnline( (function(header, content, callback_on_close, object){
					return function(){
						object.ShowWindow(header, content, 0, callback_on_close, 1);
					}
				})(header, content, callback_on_close, this) );
				return;
			}
			
			this.SaveData(true);
			
			if(!this._window) {
				this._window = new PopupWindow();
			}
			
			if(this._window._is_ie6) {
				this._window.SimpleDisplayTo(header, content, 40, 40, 300, 0, 800, 0, 1, 0, 1, callback_on_close);
			} else {
				this._window.SimpleDisplayTo(header, content, -300, 40, 300, 0, 0, 0, 1, 0, 1, callback_on_close);
				this._window._self.animate({right: "40px"}, "slow");
			}
			
			this._window._content.find("a.open").bind("click", (function(object){
				return function() {
					object.LiveChatOpenWindow(); 
					return false;
				}
			})(this));
		}
	},
	
	/*
		Отображает окно чата
	*/
	LiveChatOpenWindow: function() {
		this.SaveData(true);
		//var url = "http://messenger.providesupport.com/messenger/rdm-group.html?ps_s=" + this.ps_sid;
		var url = "http://messenger.providesupport.com/messenger/rdm-group.html";
		window.open(url, "_blank", "menubar=0,location=0,scrollbars=auto,resizable=1,status=0,width=500,height=460"); 
		if(this._window) {
			this._window.Hide();
		}
	},
	
	/*
		Проверка, онлайн поддержка или нет
		callback_online - функция вызывается, когда поддержка online
		callback_offline - поддержка offline
	*/
	LiveChatCheckOnline: function(callback_online, callback_offline) {
		$.get("/invite_online.php?ajax_no_cache" + Math.random(), (function(callback_online, callback_offline) {
			return function(data){
				if(data == "online") {
					if(typeof callback_online == "function") {
						callback_online.call();
					}
				} else {
					if(typeof callback_offline == "function") {
						callback_offline.call();
					}
				}
			}
		})(callback_online, callback_offline));
	},
	
	/*
		Обновляет информацию 
	*/
	LiveChatRefreshContent: function() {
		var ps_n = (new Date()).getTime();
		if ((ps_n - this.ps_s) < 7200000) {
			setTimeout((function(object){
				return function() {
					object.LiveChatRefreshContent();
				}
			})(this), 12000);
			if(this.ps_sid) {
				this.ps_Image.src = "http://image.providesupport.com/cmd/rdm-group?" + "ps_t=" + ps_n + "&ps_l=" + escape(document.location) + "&ps_r=" + escape(document.referrer) + "&ps_s=" + this.ps_sid + "&Title=" + escape(document.title) + "";
			}
		}
	},
	
	/*
		Получим идентификатор сессии
	*/
	LiveChatGetTsid: function() {
		var cookie_value = " " + document.cookie + ";"
		var i = cookie_value.indexOf("sid");
		if(i > -1) {
			i += 5;
			return unescape(cookie_value.substring(i, cookie_value.indexOf(";", i)));
		} else {
			// Сгенерируем новый sid и установим
			var sid = "";
			for(var i = 0; i <= 32; i++) {
				sid += String.fromCharCode( Math.floor(Math.random( ) * 26) + 65 )
			}
			document.cookie = "sid=" + escape(sid) + "; expires=Mon, 01-Jan-2038 00:00:00 GMT; path=/";
			return sid;
		}
	},
	
	/*
		Проверка информации, коотрая пришла после обновления
	*/
	LiveChatGetInf: function(object) {
		var w1 = object.ps_Image.width - 1;
		this.ps_ol = (w1 & 1) != 0;
		var h = object.ps_Image.height;
		if (h != 2) {
			object.ps_op = false;
		} else if ((h == 2) && (!object.ps_op)) {
			object.ps_op = true;
			$.getJSON("/invite_get.php?ps_s=" + object.ps_sid + "&ajax_no_cache" + Math.random(), (function(object) {
				return function(data) {
					var cd = new Date();
					var h = cd.getHours();
					var m = cd.getMinutes();
					h = (h > 9) ? h : "0" + h;
					m = (m > 9) ? m : "0" + m;
					m = h + ":" + m;
					object.ShowWindow("<div class='window_date'>" + m + "</div>Менеджер:", "<p>" + data.message + "</p><p><a href=\'#\' class='open'>Начать диалог</a></p>", 1, (function(sid, server_id){
						return function(){
							$.get("/invite_set.php?status=closed&server_id=" + server_id + "&wsid=" + sid + "");
						}
					})(data.wsid, data.server_id));
				}
			})(this));	
		}
	}
}

var LocalChatStorage = new LocalStorage();

$(function() {
	$('#TechList .basketControls a.ajax').click(BasketUpdateLinkClick);
	$('.by_childs .basketControls a.ajax').click(BasketUpdateLinkClick);
	$('#BasketList a.ajax').click(BasketUpdateLinkClick);
	
	var pop_window = new PopupWindow();
	
	$('#billboard').bind("click", function() {
		pop_window.SimpleDisplayTo($('#billboard span').html(), $('#billboard div').html(), 115, 170, 300, 0, 800, 0, 1);
		return false;
	});
	
	// Заказ звонка
	var image_input = new Image;
	image_input.src = "/irdm/input-tel-red.gif";
	if(jQuery.browser.opera) {
		$(".requestinput1").css({paddingTop: "2px", height: "21px"});
	}
	
	
	$(".requestinput1").bind("blur", function(e){
		return ValidateRequestCallSymbol(e);
	});
	$(".requestinput1").bind("keyup", function(e){
		return ValidateRequestCallSymbol(e);
	});
	$(".requestinput1").bind("keydown", function(e){
		return ValidateRequestCallSymbol(e);
	});

	$("#callrequest").bind("submit", function(){
		SubmitRequestCall();
		return false;
	});
	
	$("#inner-search").bind("submit", function(){
		if(!$("#inner-search input[@name='search']").attr("value")) {
			return false;
		}
	});
	
	if($("#content").length) {
		if($("div.support").length) {
			if($("div.support").attr("class").indexOf("hidden") != -1) {
				LocalChatStorage.LiveChatCheckOnline(function(){
					$(".support").removeClass("hidden");
					DisplayOnlineMessage();
				});
			} else {
				$(".support").removeClass("hidden")
				DisplayOnlineMessage();
			}
			
			$(".support a").bind("click", function(){
				LocalChatStorage.LiveChatOpenWindow();
				return false;
			});
			$("a.support").bind("click", function(){
				LocalChatStorage.LiveChatOpenWindow();
				return false;
			});
		}
		
		LocalChatStorage.LiveChatRefreshContent();
	}
});

function DisplayOnlineMessage() {
	var cd = new Date();
	var h = cd.getHours();
	var m = cd.getMinutes();
	h = (h > 9) ? h : "0" + h;
	m = (m > 9) ? m : "0" + m;
	m = h + ":" + m;
	var text2 = "";
	if(h < 6) { text2 = "Доброй ночи!";}
	if(h < 12 && h >= 6) { text2 = "Доброе утро!";}
	if(h < 18 && h >= 12) { text2 = "Добрый день!";}
	if(h >= 18) { text2 = "Добрый вечер!";}
	
	var header = "<div class='window_date'>" + m + "</div>Менеджер:";
	var content = "<p><br>"+ text2 +" Я ваш менеджер и готов ответить на все интересующие Вас вопросы.</p><p><a href='#' class='open'>Начать диалог</a></p>";
	
	var timeout = 300000;
	
	if(LocalChatStorage._AllPagesVisited > 2) {
		timeout = 15000;
	}
	
	setTimeout('LocalChatStorage.ShowWindow("' + header + '", "' + content + '", 0, 0, 1)', timeout);
}

function ValidateRequestCall()
{
	_hSubmitCallValidate 	= true;
	value = ($(".requestinput1").attr("value")).replace(/\s/ig, "")
	var validTel 			= /^[0-9]{10,21}$/i;

	if(validTel.exec(value)) {
		$(".requestinput1").removeClass("requestinputerror1");
		return true;
	} else {
		$(".requestinput1").addClass("requestinputerror1");
		return false;
	}
}

function ValidateRequestCallSymbol(e)
{
	if(_hSubmitCallValidate) {
		ValidateRequestCall();
	}
	
	value = $(".requestinput1").attr("value");
	var validCode = /^[0-9]{3}$/i;
	if(validCode.exec(value) && e.keyCode != 8 && e.keyCode != 46 && !jQuery.browser.opera) {
		$(".requestinput1").attr("value", value + " ");
	}
	
	return true;
}

function SubmitCallTimer()
{
	var time_seconds = parseInt($(".help-phone-send span").html()) - 1;
	if(!time_seconds) {
		clearInterval(_hSubmitCallTimer);
		$(".help-phone-send").css("paddingTop", "15px");
		$(".help-phone-send").html("Если Вам не дозвонились вы можете попробовать <a href='#' onclick='RepairRequestCall(); return false;'>исправить номер</a> или <a href='#' onclick='SubmitRequestCall(); return false;'>повторить запрос</a>.");
	} else {
		$(".help-phone-send span").html(time_seconds);
	}
}

function RepairRequestCall()
{
	$(".help-phone-send").css("paddingTop", "0px");
	$("#callrequest").css("display", "block"); 
	$(".help-phone-header").css("display", "block"); 
	$(".help-phone-bottom").css("display", "block");
	$(".help-phone-send").css("display", "none");
	$("#help-phone-icon").css("display", "block");
	$("#help-phone-flash").css("display", "none");
}

function SubmitRequestCall()
{
	if(!ValidateRequestCall()) {
		return false;
	}
	
	$(".help-phone-send").css("paddingTop", "0px");
	$("#callrequest").css("display", "none");
	$(".help-phone-header").css("display", "none");
	$(".help-phone-bottom").css("display", "none");
	$(".help-phone-send").css("display", "block");
	$("#help-phone-flash").css("display", "none");
	$("#help-phone-flash").css("display", "block");
	$("#help-phone-icon").css("display", "none");
	
	$(".help-phone-send").html("Вам перезвонят через:<br><div><span>60</span> сек</div>");
	$.post("/netcat/add.php", {catalogue: 2, cc: 137, sub: 426, posting: 1, Tel: ($(".requestinput1").attr("value")).replace(/\s/ig, ""), is_ajax: Math.random(), f_Link: location.pathname+location.search, template:'39' }, function(data){});
	
	_hSubmitCallTimer = setInterval("SubmitCallTimer();", 1000);
	
	return false;
}

function SubmitAJAX_Phone(form, auto) {
	if (auto) {
		if (!form.elements['is_ajax']) {
			$(form).append("<input type='hidden' name='is_ajax' value='1'>");
		}
	}
	$(form).ajaxSubmit(function(data){
		SelectPopup.SimpleSetContent(data, 0);
	}).find('input:submit').attr({disabled: '1'});
	return false;
}

function bookmark(a){
	var url = window.document.location;
	var title = window.document.title;
	if ($.browser.msie && parseInt($.browser.version) >= 4) window.external.AddFavorite(url,title);
		else if ($.browser.opera) {
			a.setAttribute('href',url);
			a.setAttribute('title',title);
			a.setAttribute('rel','sidebar');
			return true;
		}
	else if ($.browser.mozilla) window.sidebar.addPanel(title,url,"");
	else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки.");
	return false;
}
