$(function(){
	SLiderUL();
	$.sifr({
		path: host + '/js/fonts/',
		save: true
	})
	
	$('#middle h1, #middle .h_1').sifr({
		font:'Calligraph'
	});
	$('#menu td').hover(
		function(){
			$(this).addClass('hover');
			$('>ul', this)
				.css({
					left: $(this).offset().left,
					top	: $(this).offset().top + $(this).height()
				})
				.show();
		},
		function(){
			$(this).removeClass('hover');
			$('>ul', this).hide();
		}
	).click(function(){
		var link = $('>a', this).attr('href');
		if (link) document.location.href = link;
	})
	
	$('#menu td li').hover(
		function(){
			$('>a',  this).addClass('hover');
			$('>ul', this).show();
		},
		function(){
			$('>a',  this).removeClass('hover');
			$('>ul', this).hide();
		}
	);
	
	// Left menu ajax
	$('#content .col_l .menu a').toggle(
		function (){
			carouselStartIndex = 1;
			var oUL = $('~ul', this);
			if (!oUL.length)
			{
				document.location.href = this.href;
				return true;
			}
			$('#content .col_l .menu ul').slideUp();
			oUL.slideDown();
			var wrapper = $('#content .col_r .content');
			var mask = $(document.createElement('div'))
					.css({
						width : wrapper.width(),
						height: wrapper.height(),
						left  : wrapper.offset().left,
						top	  : wrapper.offset().top,
						position: 'absolute',
						background: '#000000',
						opacity: '.8'
					});
			var maskImg = $(new Image())
					.css({
						position : 'absolute',
						width	 : 32,
						height	 : 32,
						left	 : wrapper.offset().left + (( wrapper.width() / 2) - 16),
						top		 : wrapper.offset().top + (( wrapper.height() / 2) - 16)
					}).attr('src', host + '/images/lightbox-ico-loading.gif');
			$('body')
				.append(mask)
				.append(maskImg)
			$.get(this.href + '?m=ajax', function(html){
				$('#content .col_r').html(html);
				Init();
				mask.remove(); maskImg.remove();
			});
			return false;
		},
		function (){
			$('~ul', this).slideUp();
		}
	);
	
	Init();
});

function Init()
{
	$('a.export').click(function(){
		var self  = $(this);
		var popup = $('#save_container');
		
		popup.css({
			left: self.offset().left - 58,
			top	: self.offset().top - 36
		}).show();
	});
	
	$('a.other-image').click(Preview)
	$('.add2basket').click(add2basket);
	
	// jQuery plugins
	$('a.light-box').lightBox();
	$('.jcarousel-skin-section, .jcarousel-skin-item').jcarousel({
		animation: 1000,
		start	 : ((window.carouselStartIndex != window.undefined) ? carouselStartIndex : 1),
		initCallback: carousel_initCallback,
		itemLoadCallback: carousel_itemLoadCallback
	});

	$('.preview').thumbPopup({
		popupCSS: {
			border : 'none',
			padding: 0,
			background: 'transparent'
			/*border: '1px solid #CCC',
			padding: '5px',
			background:'#333'*/
		},
		imgIcoHref	: host+'/images/zoom.' + (($.browser.msie && $.browser.version < 7) ? 'gif' : 'png') ,
		imgSmallFlag: '188_250',
		imgLargeFlag: '403_537',
		loadingHtml : '<img src="'+host+'/images/lightbox-ico-loading.gif">'
	});
	
	$('#dialog-window form').submit(function(){
		var $_this 	= $(this);
		var data 	= '';
		for (i = 0; i < this.elements.length; i++){
			data += (data != '' ? '&' : '')+ this.elements[i].name +'='+ $(this.elements[i]).val();
		}
		$.ajax({
			type	: $_this.attr('method'),
			url		: $_this.attr('action'),
			data	: data +'&ajax=Y',
			success	: function( responce ){
				try {
					var obj = eval('('+ responce +')');
					var text = '<p class="'+ (obj.status == 'OK' ? 'success' : 'error') +'">'+ obj.text +'</p>';
				} catch (e) {
					var text = '<p class="error">Не известная ошибка</p>';
				}
				if (obj.status == 'OK'){
					$('#dialog-window').dialog('close');
				}
				
				$('#dialog-error')
					.dialog('close')
					.empty()
					.html( text )
					.dialog('open');
			}
		});
		return false;
	});
	
	
	$('#dialog-window').dialog({
		autoOpen	: false,
		width		: 320,
		resizable	: false,
		modal		: true,
		buttons		: {
			'Отмена': function(){
				$('#request_price_id').val( 0 );
				$(this).dialog('close');
			},
			'Отправить': function(){
				$('form', this).submit();
			}
		}
	});
	$('#dialog-error').dialog({
		autoOpen	: false,
		modal		: true,
		buttons		: {
			'Ok'	: function(){
				$(this).dialog('close');
			}
		}
	})
	$.datepicker.setDefaults(
		$.extend($.datepicker.regional["ru"])
	);
	$('.date').datepicker({
		showOn			: "button",
		buttonImage		: "/css/ui-lightness/images/calendar.gif",
		buttonImageOnly	: true,
		buttonText		: 'Выбрать дату',
		showButtonPanel	: true
	});
	$('.btn_form_request').click(function(){
		$('#request_price_id').val( $(this).attr('data') );
		$('#dialog-window').dialog('open');
	});
	
}

function showRequestForm()
{
	
}

function carousel_itemLoadCallback(carousel, state)
{
	
	
	if (carousel.has(carousel.first, carousel.last)) {
        return;
    }
    var sectionId 	= $(carousel.list).attr('section-id');
    var is_small	= $(carousel.list).parents('div.jcarousel-skin-item').length > 0 ;
    
    $.ajax({
    	type: 'GET',
    	url	: host + '/js/ajax/carousel.php',
    	data: 'first=' + carousel.first + '&last=' + carousel.last + '&section=' + sectionId + '&is_small=' + is_small + '&cache=' + Math.random(),
    	success: function ( data ){
    		try
    		{
    			var arData 	= eval('('+ data +')');
    			var arItem	= null;
    			var first	= carousel.first;
    			carousel.size( arData.total );
    			
    			for(i = 0; i < arData.items.length; i++){
    				arItem = arData.items[i];
    				carousel.add(first + i, carousel_getHTML( arItem ));
    			}
    		} catch (e){
    		}
    	}
    });
}
function carousel_getHTML( arItem ){
	var st_return = "<table cellpadding='0' cellspacing='0' width='100%' height='100%'><tr><td align='center'>";
		st_return += "<a href='"+ arItem.url +"' title='"+ arItem.title.replace("'", '"') +"' class='catalog-list-item'>";
		st_return += "<img src='"+ arItem.image +"' alt='"+ arItem.title.replace("'", '"') +"'>";
		
		if (arItem.is_new)
			st_return += "<img src='"+ host +"/images/sticker_new.png' class='sticker new'>";
		if (arItem.discount != '')
			st_return += "<img src='"+ arItem.discount +"' class='sticker discount'>";
		
		st_return += "</a>";
		st_return += "</td></tr></table>";
	
	return st_return;
}
function carousel_initCallback(carousel, state)
{
	var total = carousel.list.attr('count-items');
	
	if (total > carousel.size()){
		carousel.size( total );
	}
}

function Preview()
{
	var mainImg = $('#mainImg');
	var $_this	= $(this);
	var cur_lnk_src = mainImg.parent().attr('href');
	var cur_lnk_alt = mainImg.parent().attr('title');
	var cur_img_src = mainImg.attr('src').replace('403_537', '115_150');
	var cur_img_alt = mainImg.attr('alt');
	
	var new_lnk_src = $_this.attr('href');
	var new_lnk_alt = $_this.attr('title');
	var new_img_src = $_this.find('img').attr('src').replace('115_150', '403_537');
	var new_img_alt = $_this.find('img').attr('alt');
	
	mainImg
		.attr('src', new_img_src)
		.attr('alt', new_img_alt)
		.parent()
			.attr('href', new_lnk_src)
			.attr('title', new_lnk_alt);
	
	$_this
		.attr('href', cur_lnk_src)
		.attr('title', cur_lnk_alt)
		.find('img')
			.attr('src', cur_img_src)
			.attr('alt', cur_img_alt);
	
	return false;
}


function add2basket()
{
	if (!this.form) return true;
	
	var data   = '';
	var oForm  = this.form;
	var oEl	   = null;
	
	oForm['item_form[action]'].value = 'add2basket_js';
	for(i = 0; i < oForm.elements.length; i++)
	{
		oEl  = oForm.elements[i];
		data = data + ( data != '' ? '&' : '' ) + oEl.name + '=' + oEl.value;
	}
	
	$.ajax({
		type   : 'POST',
		url    : document.location.href,
		data   : data,
		success: function (resp){
			var arResp = eval( '(' + resp + ')' );
			switch( arResp.status )
			{
				case 'success':
						$('#basket_count').html( arResp.count );
						$('#basket_price').html( arResp.price );
						$.prompt('<div class="success">Товар успешно добавлен в корзину</div>');
					break;
				case 'error':
						$.prompt('<div class="error">' + arResp.text + '</div>');
					break;
			}
		}
	})
	return false;
}
function SLiderUL()
{
	var oUL		= $('#middle ul');
	var oLIs	= oUL.find('li');
	
	if (!oLIs.length) return ;
	
	oUL.css({
		position: 'absolute',
		width		: oUL.parent().width(),
		height		: oUL.parent().height(),
		listStyle	: 'none',
		margin	: 0,
		padding : 0,
		overflow: 'hidden'
	});
	
	var wUL 	= oUL.width();
	var hUL 	= oUL.height();
	var left	= wUL - (oLIs.length * 20);
	var currIdx	= 0;
	for (i = 0; i < oLIs.length; i++)
	{
		oLI 	 = $(oLIs[i])
		maxLeft	 = i * 20;
		maxRight = (i == 0) ? 0 : left + (i * 20);
		
		oLIs[i].direct		= 'right';
		oLIs[i].show		= false;
		oLIs[i].slideToLeft	= function(left){
			return function(show){
				$(this).animate({
					left: left
				}, 1000, function(){this.show = show})
			}
		}(maxLeft)
		oLIs[i].slideToRight	= function(left){
			return function(show){
				$(this).animate({
					left: left
				}, 1000, function(){this.show = show})
			}
		}(maxRight)
		
		oLI.css({
			position: 'absolute',
			width	: wUL,
			height	: hUL,
			borderLeft: '3px solid #FFFFFF',
			top		: 0,
			left	: maxRight
		});
		oLI.hover(
			function(idx, maxRight){
				return function(){
					currIdx	= idx;
					oLI = this;
					if (oLI.show) return true;
					switch( oLI.direct )
					{
						case 'left':
							for (i = idx + 1; i < oLIs.length; i++)
							{
								$(oLIs[i]).stop();
								oLIs[i].direct = 'right';
								oLIs[i].show = false;
								oLIs[i].slideToRight();
							}
						break;
						case 'right':
							for (i = 0; i <= idx; i++)
							{
								$(oLIs[i]).stop();
								oLIs[i].direct = 'left';
								oLIs[i].show = false;
								oLIs[i].slideToLeft();
							}
						break;
					}
					this.show = true;
				}
			}(i, maxRight)
		)
		oLI.find('.text').css({
			width: oLI.width() - (oLIs.length * 16),
			display:'block'
		})
	}
	
	
	var slideTimeout = null;
	var fn_slideTimeout = function(){
		currIdx++;
		if (currIdx >= oLIs.length)
		{
			currIdx = 0;
			for(i = 1; i < oLIs.length; i++)
				oLIs[i].slideToRight();
		}
		oLIs[currIdx].slideToLeft();
		slideTimeout = setTimeout(fn_slideTimeout, 4000);
	}
	oUL.hover(
		function(){
			clearTimeout(slideTimeout);
		},
		function(){
			slideTimeout = setTimeout(fn_slideTimeout, 4000);
		}
	);
	slideTimeout = setTimeout(fn_slideTimeout, 4000);
}
