var site='ru';
function setPrintStyle(p) {
	var links = $('head link');
	if (p === true) {
		var a = a || $('<a id="noPrintLink" href="#" />').text('Вернуться к обычному виду страницы'),
			btn = btn || $('<a id="printPage" class="btn" href="#" />').text('Распечатать').append('<i class="c l" /><i class="c r" />'),
			pgURL = pgURL || $('<p id="pageURL" />').text('Адрес страницы: ' + location.href.split('#')[0]);
		location.hash = 'print';
		a.click( function() { setPrintStyle(false); return !1; });
		btn.click( function() { window.print(); return !1; });
		
		if (window.printing === undefined || window.printing === false) {
			window.printing = true;
			$('#siteLogo').after(a, pgURL);
			$('#content').append(btn);
		}
	} else {
		location.hash = '';
		$('#noPrintLink, #printPage, #pageURL').remove();
		window.printing = false;
	}
	links.each(function() {
		if ($(this).attr('title') === 'printview') $(this).attr('disabled', !p);
	});
}

var placeholding = {
	focus: function() {
		this.label.addClass('hidden');
	},
	blur: function() {
		if ($(this).val() === '') {
			this.label.removeClass('hidden');
		} else if ($(this).val() === this.label.text()) {
			$(this).val('');
			this.label.removeClass('hidden');
		}
	},
	change: function() {
		if ($(this).val() !== '') {
			this.label.addClass('hidden');
		}
	}
}

var ArtImgCarousel = function(cArr, cContainer) {
	this.cArr = cArr;
	this.cContainer = cContainer;
	this.total = cArr.length;
	this.curr = 0;
	this.ctrlWrpr = $('p.ctrls', cContainer);
	this.init();
}
$.extend(ArtImgCarousel.prototype, {
	init: function() {
		this.imgCont = $('div.b-wrpr', this.cContainer);
		this.showCntr();
		this.initCtrls();
	},
	showLoader: function() {
		if ($('i.loader', this.imgCont).length) {
			$('i.loader', this.imgCont).show();
		} else {
			var loader = $('<i class="loader"/>');
			this.imgCont.append(loader);
		}
	},
	update: function(src) {
		$('img', this.imgCont).remove();
		$('i.loader').hide();
		var nextImg = $('<img src="'+ src +'" alt=""/>');
		nextImg.css('display', 'none');
		this.imgCont.append(nextImg);
		nextImg.fadeIn('600');
		this.showCntr();
	},
	createImg: function(src) {
		var self = this, img = new Image();
		$(img).load(function() {
			$(img).unbind('load');
			self.update(src);
		});
		img.src = src;
	},
	initCtrls: function() {
		var self = this;
		this.prev = $('a.lArw', this.ctrlWrpr);
		this.prev.idx = -1;
		this.prev.click(function() { self.showImg(-1); return !1; });
		this.next = $('a.rArw', this.ctrlWrpr);
		this.next.idx = 1;
		this.next.click(function() { self.showImg(1); return !1; })
	},
	showCntr: function() {
		var currNum = this.curr + 1;
		$('span.sn', this.ctrlWrpr).text(currNum);
		$('span.total', this.ctrlWrpr).text(this.total);
	},
	showImg: function(delta) {
		var self = this,
			idx = this.curr + delta < 0 ? this.total - 1 : this.curr + delta > this.total - 1 ? 0 : this.curr + delta;
		var nextImgSrc = this.cArr[idx];
		this.curr = idx;
		$('img', this.imgCont).fadeOut('550',
			function() {
				$(this).css({'display': 'block', 'visibility': 'hidden'});
				self.showLoader();
				self.createImg(nextImgSrc);
			}
		);
	}
	
});

var NewsSlider = function(news, prev, next) {
	this.running = false;
	this.news = news;
	this.curr = 0;
	this.size = $('li.b-itm', this.news).length;
	this.prev = prev;
	this.next = next;
	this.init();
}
$.extend(NewsSlider.prototype, {
		updateArwsStatus: function() {
			if (this.curr == 0) {
				this.prev.addClass('inactive');
			} else {
				this.prev.removeClass('inactive');
			}
			if (this.curr == this.size - 2) {
				this.next.addClass('inactive');
			} else {
				this.next.removeClass('inactive');
			}
			if (this.size <= 2) {
				(this.prev, this.next).addClass('inactive');
			}
		},
		moveTo: function(dest) {
			var self = this;
			if (!this.running) {
				this.running = true;
				var mv = dest * this.itmWidth;
				this.curr -= dest;
				if (this.curr < 0) this.curr = 0;
				if (this.curr > this.size) this.curr = this.size;
				var indent = parseInt(this.news.css('left'), 10);
				this.news.animate({'left': indent + mv +'px'}, 500,
					function() {
						self.updateArwsStatus();
						self.running = false;
					}
				);
			}
		},
		defindItmWidth: function() {
			var self = this,
				itm = $('li.b-itm:first', this.news);
			this.itmWidth = itm.outerWidth() + parseInt(itm.css('marginLeft'), 10);
			
			if (window.opera) {
				var visWidth = this.news.parent('#slideNews').outerWidth(),
					itmWidth = Math.ceil(visWidth * 0.46), // news item width is 46% of news slider
					itmMarginLeft = Math.ceil(visWidth * 0.04); // 4% of news slider is margin-left of news item
				this.itmWidth = itmWidth + parseInt(itmMarginLeft / 2, 10) + itmMarginLeft;
				$('li.b-itm', this.news).each(function() {
					$(this).css({'width': (itmWidth + parseInt(itmMarginLeft / 2, 10)) +'px', 'marginLeft': itmMarginLeft +'px'});
				});
				this.news.css({'width': (this.itmWidth * this.size) +'px', 'marginLeft': '-'+ itmMarginLeft +'px'});
			}
		},
		init: function() {
			var self = this;
			$(window).bind('resize.newsSlider', function() {
				self.defindItmWidth();
				self.news.css('left', '-' + (self.curr * self.itmWidth) + 'px');
				self.updateArwsStatus();
			});
			
			this.defindItmWidth();
			this.updateArwsStatus();
			this.moveTo(-4);
			this.prev.click(
				function() {
					if (!$(this).hasClass('inactive')) {
						self.moveTo(1);
					}
					return !1;
				}
			);
			this.next.click(
				function() {
					if (!$(this).hasClass('inactive')) {
						self.moveTo(-1);
					}
					return !1;
				}
			);
		}
	}
);

$(function() {
	if (location.hash == '#print') { setPrintStyle(true);}
	$('#printLink').click( function() { setPrintStyle(true); return !1; });
	$('#checklink').click( function() {
		$.getJSON("/"+site+"/myajax.php",{domain: $('#domainname').val(), ajax: 'true'}, function(j){
		  $("#domainmsg").removeClass('dhide');
		  $("#domainmsg").removeClass('red');
		  $("#domainmsg").removeClass('green');
		  if(j[0].result=='free')
		  {
			$("#domainmsg").addClass('green');
		  	$('#domainmsg').html("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Домен свободен");
		  }
		  else
		  {
			$("#domainmsg").addClass('red');
			$('#domainmsg').html("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Домен занят");
		  }
		  
		})
	});
	$('#clientPrefix').bind('click', function() {
		var list = list || $('#prefixesList'),
			fld = fld || $(this);
		list.slideDown(10, function() {
			$(document).bind('click.login', function(e) {
				var p = $(e.target).parents().andSelf().filter('#prefixesList');
				if (p.length === 0) {
					list.hide();
					$(document).unbind('click.login');
				}
			});
		});
		$('a', list).click( function() {
			fld.val($(this).text());
			var handler1='https://sydney.sarkor.com/cbuser/auth.jsp';
			if($(this).text()=='D')
			{
				handler1 = 'https://billing.sarkor.uz/user/auth.jsp';
			}
			$("#loginTopForm").attr("action",handler1);
			list.hide();
			$(document).unbind('click.login');
			return !1;
		});
		$("#loginTopForm").submit(function() {
			var testlogin = '';
			testlogin = $("#clientLogin").val().substring(1,2);
			if(testlogin=='-' || testlogin=='@')
			{
				testlogin = $("#clientLogin").val().substring(2,$("#clientLogin").val().length);
				$("#clientLogin").val(testlogin);
			}
			
			if($("#clientPrefix").val()=="C")
			{
				$("#clientLogin").val($("#clientPrefix").val().toLowerCase()+"@"+$("#clientLogin").val());
			}
			else
			{
				$("#clientLogin").val($("#clientPrefix").val().toLowerCase()+"-"+$("#clientLogin").val());
			}
			return true;
		});
	});
	$("#disrtictSel2").change(function(){
		if($(this).val()!=0)
		{
			$.getJSON("/"+site+"/myajax.php",{district2: $(this).val(), ajax: 'true'}, function(j){
			  var options = '<option value="0">Выберите ATC...</option>';
			  for (var i = 0; i < j.length; i++) {
				options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
			  }
			  $("select#atsSel").removeAttr('disabled');
			  $("select#atsSel").html(options);
			})
		}
		else
		{
			var options = '<option value="0">Выберите ATC...</option>';
			$("select#atsSel").html(options);
			$("select#atsSel").attr('disabled', true);
		}
	});
	$("#disrtictSel").change(function(){
		if($(this).val()!=0)
		{
			$.getJSON("/"+site+"/myajax.php",{district: $(this).val(), ajax: 'true'}, function(j){
			  var options = '<option value="0">Выберите улицу...</option>';
			  for (var i = 0; i < j.length; i++) {
				options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
			  }
			  $("select#streetSel").removeAttr('disabled');
			  $("select#streetSel").html(options);
			  options = '<option value="0">Выберите...</option>';
			  $("select#appartsSel").html(options);
			  $("select#appartsSel").attr('disabled', true);
			})
		}
		else
		{
			var options = '<option value="0">Выберите улицу...</option>';
			$("select#streetSel").html(options);
			$("select#streetSel").attr('disabled', true);
			options = '<option value="0">Выберите...</option>';
			$("select#appartsSel").html(options);
			$("select#appartsSel").attr('disabled', true);
		}
	});
	$("#streetSel").change(function(){
		if($(this).val()!=0)
		{
			$.getJSON("/"+site+"/myajax.php",{street: $(this).val(), ajax: 'true'}, function(j){
			  var options = '<option value="0">Выберите...</option>';
			  for (var i = 0; i < j.length; i++) {
				options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
			  }
			  $("select#appartsSel").html(options);
			  $("select#appartsSel").removeAttr('disabled');
			})
		}
		else
		{
			var options = '<option value="0">Выберите...</option>';
			$("select#appartsSel").html(options);
			$("select#appartsSel").attr('disabled', true);
		}
	});

	$('#clientsLoginForm').prepend('<i class="cw cwt"/>').append('<i class="cw cwb"/>');
	$('#servTitles, #servicesList i.cw, #headerTitle i.cw, #clientsLoginForm i.cw, a.btn, button.btn span.inbtn').append('<i class="c l"/><i class="c r"/>');
	$('div.b-inshdw').prepend('<i class="cw cwt"/>').append('<i class="cw cwb"/><i class="c tl"/><i class="c tr"/><i class="c bl"/><i class="c br"/>');
	$('.rndr').append('<i class="c lt"/><i class="c rt"/><i class="c lb"/><i class="c rb"/>');
	$('#btmBanners li.b-itm').append('<i class="cl l"/><i class="cl r"/>');
	$('.b-rnd, .b-rnd .title, .blue-rnd .b-inbg').prepend('<i class="ln tln"/>').append('<i class="ln bln"/>');
	$('#breadcrumbs > li').append('<i class="arw" />');
	$('table.plansGrid tr.row-sep td').append('<i class="cw" />')
	$('div.b-lshdw').append('<i class="cs tsh"/><i class="cs bsh"/>');
	$('div.b-tshdw').append('<i class="cs lsh"/><i class="cs rsh"/>');
	$('.icq-uin').append('<i class="icon" />');
	$('ul.dealersList a.lnk-pmap').append('<i class="icon" />');
	
	(function() {
		var opener = $('#clientsLoginForm i.inf'),
			prnt = prnt || $('#container'),
			tt = tt || $('#loginTT'),
			pos = {'top': 0, 'left': 0};
		function openTT() {
			opener.addClass('active');
			pos.top = Math.ceil(opener.offset().top) - 26;
			pos.left = Math.ceil(opener.offset().left - prnt.offset().left) + 8;
			tt.css({'top': pos.top + 'px', 'left': pos.left + 'px'});
			$(document).bind('mousedown', checkExternalClick);
		}
		function closeTT() {
			tt.css('top', '-1000px');
			opener.removeClass('active');
			$(document).unbind('mousedown', checkExternalClick);
		}
		function checkExternalClick(e) {
			var p = $(e.target).parents().andSelf().filter('#loginTT, i.inf');
			if(p.length > 0) {
				p.each(function () {
					if (this !== tt[0] && this !== opener[0]) {
						closeTT();
					}
				});
			} else {
				closeTT();
			}
		}
		opener.click(function() {
			if (!opener.hasClass('active')) {
				openTT();
			}
		});
		$('i.close', tt).click( closeTT);
	})();
	
	$('label.placeholder').each(function() {
		var fld = $('#'+ $(this).attr('for'));
		fld[0].label = $(this);
		fld.focus( placeholding.focus)
			.blur( placeholding.blur)
			.change( placeholding.change)
			.mouseover( placeholding.change)
			.change();
	});
	
	$('#mainPage #servTitles a').each(function(i) {
		var swtchr = $('#servTitles'),
			banners = $('#servItms');
		this.idx = i;
		$(this).click(function() {
			if (!$(this).hasClass('current')) {
				$('a.current', swtchr).removeClass('current');
				$(this).addClass('current');
				$('li.current', banners).stop().animate({'opacity': 0}, 400, function() { $(this).removeClass('current'); });
				$('li:eq('+ this.idx +')', banners).stop().animate({'opacity': 1}, 400, function() { $(this).addClass('current'); });
			}
			return !1;
		});
	});
	
	(function(p) {
		var slides = [],
			next = 0,
			running = false;
		$('dd.b-itm', p).each(function() { slides.push($(this)); });
		var l = slides.length;
		$('i.refresh', p).bind('click', function() {
			if (!running) {
				running = true;
				var curr = next;
				next = (curr + 1) % l;
				slides[curr].animate({'opacity': 0}, 500, function() { $(this).removeClass('current'); });
				slides[next].animate({'opacity': 1}, 500, function() { $(this).addClass('current'); running = false; });
			}
		});
	})($('#fnfBlock.sliding'));
	
	(function(p) {
		var list = list || $('div.ddList', p),
			lnk = lnk || $('a.lnk-js', p),
			adr = $('ul.contacts', p);
		lnk.click(function() {
			list.show(24, function() {
				$(document).bind('click.callcenter', function(e) {
					var p = $(e.target).parents().andSelf().filter('div.ddList');
					if (p.length === 0) {
						list.hide();
						$(document).unbind('click.callcenter');
					}
				});
			});
			$('a', list).each( function(i) {
				this.idx = i;
				$(this).click(function() {
					if (!$(this).parent().hasClass('current')) {
						$('li.current', list).removeClass('current');
						$('li.current', adr).removeClass('current');
						$(this).parent().addClass('current');
						$('li:eq('+ this.idx +')', adr).addClass('current');
						$('span', lnk).text($(this).text());
						list.hide();
						$(document).unbind('click.callcenter');
					}
					return !1;
				});
			});
			return !1;
		});
	})($('#callCenter'));
	
	if ($('#slideNews').length) {
		new NewsSlider($('#slideNews ul.newsList'),$('#slideNews a.lArw'),$('#slideNews a.rArw'));
	}
	
	(function(form) {
		$('#hostingCustSwtch input.boxFld', form).each(function(i) {
			var chbox = this;
			this.idx = i;
			$(this).click(function() {
				if ($(this).attr('checked') === true) {
					$('fieldset', form).addClass('dhide');
					$('fieldset:eq(' + chbox.idx + ')', form).removeClass('dhide');
				}
			});
		});
	})($('#hostingOrderForm'));
(function(form) {
		$('#custStatus input.boxFld', form).click(function(i) {
			if ($(this).attr('checked') === true && $(this).attr('id') === 'connection_pers') {
				$('#connection_pers1', form).removeClass('dhide');
			} else {
				$('#connection_pers1', form).addClass('dhide');
			}
			if ($(this).attr('checked') === true && $(this).attr('id') === 'connection_corp') {
				$('#connection_corp1', form).removeClass('dhide');
			} else {
				$('#connection_corp1', form).addClass('dhide');
			}
		});
	})($('#connectionForm'));
	
	
});
