var isBorderRadiusSupported = function () {
    var s = document.documentElement.style;
    return typeof s.borderRadius === "string" ||
           typeof s.WebkitBorderRadius === "string" ||
           typeof s.KhtmlBorderRadius === "string" ||
           typeof s.MozBorderRadius === "string";
};

document.documentElement.className += isBorderRadiusSupported() ?
        " border-radius" : " no-border-radius";

$(function(){
	$('label.g_placeholder').placeholder();

	$('#index-gallery-container').indexGallery();

	$('#index-news').indexNewsList()

	balloon = new balloon()

	$('dl.g_taber').taber()

	$('dl.g_content-slider').contentSlider()

	$('select.b_select').customSelect();

	$('div.b_slideshow').ledSlideshow();

    $('a.b_product_buy').click(product_buy_handler)
})

/**
 * Дополним в jquery easing
 */
$.extend($.easing,
{
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	}
});

/**
 * Карта регионов
 */

function product_buy_handler(e){
    var product_buy = $("a.b_product_buy"),
        similar_products = $("ul.b_similar-products"),
        product_taber = $("dl.b_product-taber"),
        dealers_list = $("ul.b_dealers-list"),
        map_cont = $("#map-cont");

        similar_products.hide()
        product_taber.hide()
        map_cont.show()

    e.preventDefault();

}


/**
 * Placeholder
 */
$.fn.placeholder = function() {
	this.each(function() {
		var $label = $(this),
			$input = $('#' + $label.attr('for'));
		
		$input
			.css({backgroundColor:'transparent'})
			.bind('focus blur change', function(event) {
				$label.css('display', (event.type == 'blur' && !$input.val() ? '' : 'none'));
			})
			.trigger('blur');
	});
}


/**
 * Index gallery
 */
$.fn.indexGallery = function() {
	var t = this;
	if (!t.length) return;

	var total = t.find('li').length,
		current = 0,
		stepWidth = 640,
		gallery = t.find('#index-gallery'),
		leftArrow = t.find('#index-gallery-arrow-left'),
		rightArrow = t.find('#index-gallery-arrow-right'),
		disabledArrowClass = 'b_index-gallery_arrow_disabled'

	function arrowsHandler() {
		if (this.className.indexOf('left') > 0)
			slide(-1);
		else
			slide(1);

		return false;
	}

	function slide(v) {
		current += v;
		checkControls();
		gallery.animate({left: -current*stepWidth}, {
			duration: 600
			//,complete: afterSlide
			,easing: 'easeInQuint'
		})
	}

	function checkControls() {
		if (current == 0) leftArrow.addClass(disabledArrowClass)
		else {leftArrow.removeClass(disabledArrowClass)}

		if (current == total-1) rightArrow.addClass(disabledArrowClass)
		else {rightArrow.removeClass(disabledArrowClass)}
		
	}
	checkControls();

	leftArrow.add(rightArrow).bind('click', arrowsHandler)
	
}

/**
 * Index news list
 */

$.fn.indexNewsList = function() {
	var t = this;
	if (!t.length) return;

	var list = t.children('ul.b_index-news_list'),
		newsItems = list.children('li'),
		newsLength = newsItems.length,
		pages = Math.ceil(newsLength/2),
		step = 796,
		currentPage = 0;

	var newsSwitcher = '<ul class="b_dotted-switcher"><li class="b_dotted-switcher_item b_dotted-switcher_prev">&lt;</li>';
	for (var i = 0, activeClassname = ' b_dotted-switcher_item_active'; i < pages; i+=1) {
		newsSwitcher += '<li class="b_dotted-switcher_item'+activeClassname+'"></li>';
		activeClassname = '';
	}
	newsSwitcher+= '<li class="b_dotted-switcher_item b_dotted-switcher_next">&gt;</li></ul>';
	var newsSwitcherItems =
		$(newsSwitcher)
			.insertBefore(list)
			.click(switcherHandler)
			.children('li');

	function switcherHandler(e) {
		var li = $(e.target).closest('li');
		if (!li.length || li.hasClass('b_dotted-switcher_item_active')) return;

		var index = newsSwitcherItems.index(li);

		if (index == 0)
			currentPage -= 1;
		else if (index == (pages+1))
			currentPage += 1;
		else
			currentPage = index-1;

		if (currentPage < 0) currentPage = pages-1;
		if (currentPage > pages-1) currentPage = 0;

		newsSwitcherItems
				.removeClass('b_dotted-switcher_item_active')
				.eq(currentPage+1)
					.addClass('b_dotted-switcher_item_active')

		list.stop().animate({left:-step*currentPage}, 1100)
	}
}

/**
 * Balloon
 */

function balloon() {
	var t = this;
	var balloon = $('<div id="balloon" class="balloon"><i class="balloon_top-corners"></i><span id="balloon-content" class="balloon_content">Устойчивость к&nbsp;перепадам температуры</span><i class="balloon_bottom-corners"></i><i class="balloon_triangle"></i></div>').appendTo('body'),
		balloonContent = balloon.children('#balloon-content'),
		balloonWidth = balloon.width()+parseInt(balloon.css('paddingLeft'))+parseInt(balloon.css('paddingLeft')),
		docWidth = $(document).width();

	function inOutHandler(e) {
		var etype = e.type,
			$t = $(this),
			offset = $t.offset(),
			left = offset.left + 3,
			top = offset.top + $t.height() + parseInt($t.css('paddingTop')) + parseInt($t.css('paddingBottom')) + 8,
			ctitle = $t.attr('ctitle');

		if ((etype == 'mouseenter' || etype == 'mouseover') && ctitle) {
			setCord(left,top)
			setContent(ctitle)
			balloon.show()
		} else if (etype == 'mouseleave' || etype == 'mouseout') {
			balloon.hide()
		}
	}

	function setContent(string) {
		balloonContent.text(string)
	}

	function setCord(x,y) {

		if (balloonWidth + x > docWidth) 
			balloon.css({left:'auto',top:y, right:0})
		else
			balloon.css({left:x,top:y})
	}


	$('.custom-title').live('mouseenter mouseleave', inOutHandler).each(function() {
		var title = this.title;
		if (!title.length) return;

		this.ctitle = title || "";
		this.title = "";
	})

}

/**
 * Taber
 */

$.fn.taber = function(){
	var t = this;
	if (!t.length) return;
	var aClass = 'g_tab_active';
	return t.each(function() {
		var t = $(this);

		var dt = t.children('dt'),
			dd = t.children('dd');

		dt.filter('.'+aClass).next().show()

		dt.click(function() {
			var t = $(this);
			if (t.hasClass(aClass)) return;
			dd.hide()
			dt.removeClass(aClass)
			t.addClass(aClass).next().show()
			Cufon.refresh('.f_din-Display-Pro')
		})


	})
}

$.fn.contentSlider = function() {
	var dlNews = this;
	if (!dlNews.length) return;

	var dtTitle = dlNews.children('dt'),
		ddContent = dlNews.children('dd'),
		aClass = 'g_content-slider_active';

	dtTitle.filter("."+aClass).next().show()
	dlNews.click(function(e){
		var dt = $(e.target).closest('dt')
		if (!dt.length) return;
		dt.toggleClass(aClass).next().slideToggle()
		e.preventDefault()
	})

	return dlNews;
}

$.fn.customSelect = function() {
	var t = this;
	if (!t.length) return;
	var tmpl = {
		start: '<div class="b_custom-select"><i class="b_custom-select_button"></i><ul class="b_custom-select_list">',
		end: '</div>',
		openedClass: 'b_custom-select_opened',
		optionSelected: 'b_custom-select_selected'
	}

	$('div.b_custom-select')
			.live('click', customHandler);

	$(document).bind('click', function(e) {
		if ($(e.target).closest('div.b_custom-select').length) return;
		$('div.b_custom-select').removeClass(tmpl.openedClass)
	})

	function customHandler(e) {
		var custom = $(this),
			et = $(e.target),
			li = et.closest('li'),
			i = et.closest('i'),
			original = custom.prev(),
			allLi = li.parent().children('li');

		if (!custom.hasClass(tmpl.openedClass)) {
			custom.addClass(tmpl.openedClass)
		} else {
			if (!(i.length || li.length)) return;

			if (!li.hasClass(tmpl.optionSelected)) {
				li
					.siblings().removeClass(tmpl.optionSelected).end()
					.addClass(tmpl.optionSelected)

				original.children('option').eq(allLi.index(li))[0].selected = 'selected';
			}
			custom.removeClass(tmpl.openedClass)
		}
	}



	return t.each(function(){
		var select = $(this),
			options = select.children('option'),
			selectWidth = select.width();
			//if ($.browser.safari && !$.browser.webkit) selectWidth+=20

		options = $.map(options, function(el){
			var el = $(el);
			return {
				value: el.attr('value'),
				text: el.text(),
				selected: el.attr('selected')
			}
		})

		if(!options.length) return;

		var custom = tmpl.start;
		for (var i = 0, l = options.length;i<l;i++) {
			custom += '<li class="b_custom-select_option'+(options[i].selected?" b_custom-select_selected":"")+'" value="'+options[i].value+'">'+options[i].text+'</li>'
		}
		custom += tmpl.end;

		custom = $(custom).children('ul').andSelf().width(selectWidth).end().end()

		if (select.hasClass('b_select_dark')) custom.addClass('b_custom-select_dark')

		select.hide().after(custom)
	})
}

/**
 * Led slideshow
 */

$.fn.ledSlideshow = function() {
	var slideshowCont = this;
	if (!slideshowCont.length) return;

	var currentSlide = 0;

	var paginator = $('#slideshow-paginator'),
		paginatorItems = paginator.children('li'),
		firstPaginatorItem = paginatorItems.eq(0),
		lastPaginatorItem = paginatorItems.eq(-1);

	var step = 100;


	if (!paginator.length) return;

	var slidesCont = slideshowCont.children('ul.b_slides'),
		slides = slidesCont.children('li'),
		totalSlides = slides.length;

	paginator.click(function(e){
		var slide = $(e.target).closest('li');
		if (!slide.length || slide.hasClass('b_paginator_item_active') || slide.hasClass('b_paginator_item_disabled')) return false;
		paginatorItems.removeClass('b_paginator_item_active')

		if (slide.hasClass('b_paginator_prev'))
			currentSlide--;
		else if (slide.hasClass('b_paginator_next'))
			currentSlide++;
		else
			currentSlide = paginatorItems.index(slide)-1;

		checkCurrentSlide();
		e.preventDefault()
	})

	function checkCurrentSlide() {
		paginatorItems.eq(currentSlide+1).addClass('b_paginator_item_active')

		if (currentSlide == 0) firstPaginatorItem.addClass('b_paginator_item_disabled')
		else firstPaginatorItem.removeClass('b_paginator_item_disabled')

		if (currentSlide == totalSlides-1) lastPaginatorItem.addClass('b_paginator_item_disabled')
		else lastPaginatorItem.removeClass('b_paginator_item_disabled')

		slide();
		changeNumber(currentSlide+1)
	}
	checkCurrentSlide()

	function slide() {
		slidesCont.animate({left:-step*currentSlide+'%'}, 'slow')
	}

	var slideNumberNode = $('#slideshow-num');
	function changeNumber(n) {

	}

	
}


$.fn.paginator = function(getOptions){
	var paginator = this;
	if (!paginator.length) return;

	var paginatorItems = paginator.children('li'),
		totalItems = paginatorItems.length;

	var options = $.extend({
		url:'',
		resultContainer:'',
		currentPage:1,
		callback: function() {}
	}, getOptions);
	if (!options.resultContainer.length || !options.url.length) return paginator;
	var currentPage = options.currentPage,
		resultContainer = $('#'+options.resultContainer);

	if (!resultContainer.length) return paginator;



	paginator.click(function(e){
		var li = $(e.target).closest('li'),
			index = paginatorItems.index(li);

		if (!li.length || li.hasClass('b_paginator_item_disabled') || li.hasClass('b_paginator_item_active'))
			return false;

		if (index == 0) // prev
			currentPage -= 1;
		else if (index == totalItems-1)
			currentPage += 1;
		else
			currentPage = index;

		if (currentPage < 1) currentPage = 1;
		if (currentPage > totalItems-2) currentPage = totalItems-2;

		paginatorSwitchClasses(currentPage)
		$.get(options.url, {page:currentPage}, function(response){
			resultContainer.html(response)
			options.callback()
			paginatorItems.removeClass('b_paginator_loader')
		})
		e.preventDefault()
	})

	function paginatorSwitchClasses(index) {
		if (index == 1) {
			paginatorItems.eq(0).addClass('b_paginator_item_disabled')
		} else {
			paginatorItems.eq(0).removeClass('b_paginator_item_disabled')
		}

		if (index == totalItems-2) {
			paginatorItems.eq(-1).addClass('b_paginator_item_disabled')
		} else {
			paginatorItems.eq(-1).removeClass('b_paginator_item_disabled')
		}

		paginatorItems
				.removeClass('b_paginator_item_active b_paginator_loader')
				.eq(index)
					.addClass('b_paginator_item_active b_paginator_loader')
	}

	paginatorSwitchClasses(currentPage)
	paginatorItems.removeClass('b_paginator_loader')

	return paginator;
}
