$(function(){
	
	//menu
	var topMenu = $('#menu');
	topMenu.find('td').one('mouseenter',function(){
		var td = $(this)
		if (td.find('.submenu').length == 0){
			return;
		}
		var topMenuW = topMenu.outerWidth();
		var sub = td.find('.submenu');
		var list = sub.find('ul');
		var tail = topMenuW - (sub.position().left + list.outerWidth())
		if (tail < 0){
			list.css('left',Math.floor(tail) + 'px')
		}
	})

	// tabs
	startTabs();

	var yList = $(".yearList")
	if (yList.length != 0){
		yList.parent().tabs( "option", "selected", yList.find('li').length -1 );
	}
	
	// popup 
	$('.close').live('click',function(){
		$('body').removeClass('holded');
		$(this).closest('.popup').toggleClass('popup');
		return false;
	})
	
	$('#shop').find('.countItems').live('click',function(){
		$('body').addClass('holded');
		$(this).parent().addClass('popup');
		return false;
	})
	
	$('a > .zoom').parent().click(function(){
		openPopup();
	})
	if (navigator.platform == 'iPad' || navigator.platform == 'iPod'){
		$('a > .zoom').parent().mouseenter(function(){
			openPopup();
			$('iframe[name='+$(this).attr('target')+']').attr('src',$(this).attr('href'));
		})
	}
	function openPopup(){
		$('body').addClass('holded');
		$('#itemPrev').css({'left':'-1000px','top':'-1000px'}).addClass('popup');
	}
	$('body').append('<div id="holder"><!-- --></div>')
	$('#holder').css('opacity', 0.5);
	$('#holder').click(function(){
		$('body').removeClass('holded');
		$('.popup').removeClass('popup');
	})
	
	// slider 
	$('.slideBlock > .head').click(function(){
		$(this).parent().toggleClass('closed')
	})
	
	$('.galleryInfo .sliderLink').click(function(){
		if ($(this).hasClass('closed')){
			$(this).parent().prev().toggleClass('closed')
			$(this).parent().hide()
			return false;
		} else {
		}
	})
	
	// carousel 
	$('.lister').each(function(){
		var lister = $(this);
		var listBlocks = lister.parent().find('.g-list-block');
		var blocksCount = listBlocks.length;
		if (blocksCount == 0) return;
		var current = 0;
		listBlocks.eq(current).addClass('g-list-show');
		lister.find('a').click(function(){
			var dir = 1;
			if ($(this).attr('href') == '#left'){
				dir = -1;
			}
			listBlocks.eq(current).removeClass('g-list-show');
			current += dir;
			current = (current < 0) ? blocksCount -1 : (current >= blocksCount) ? 0 : current;
			listBlocks.eq(current).addClass('g-list-show');
			return false;
		})
	});
	
	//selectBox
	var selectBox = $('.selectBox');
	selectBox.each(function(){
		var select = $(this);
		select.find('.list span').live('click',function(){
			select.removeClass('noSelected');
			$(this).siblings().removeClass('selected').end().addClass('selected')
			select.find('.title').text($(this).text())
			select.css('overflow','hidden');
			setTimeout(function(){select.css('overflow','visible');},100);
		})
	})
	
	//toggle blocks on pages
	$('.toggleCont').click(function(){
		var head = $(this)
		var text = head.next();
		text.slideToggle(200,function(){
			if(text.css('display') == 'none'){
				head.addClass('closed');
			} else{
				head.removeClass('closed');
			}
		})
	})

    $(".f-sel select").live("click", function() {
      $(this).children("option:selected").attr('selected','selected')
      $(this).prev().html("<span>" + $(this).children("option:selected").text() + "</span>");
    });	
	
	$('a.ajax').live('click', function () {
		var container = $('#' + $(this).attr('rel'));
		if (!container.length) container = $('div.' + $(this).attr('rel'));
		if (!container.length) return true;
		var updateTabs = false;
		if ($(this).hasClass('updateTabs')) updateTabs = true;
		container.load($(this).attr('href'), function () {
			//if (updateTabs) startTabs();
			$('.hlpr').remove();
			$('body').append('<div style="display:none" class="hlpr">' + updateTabs + '</div>');
			if (updateTabs) {
				container.tabs('destroy').tabs();
				//$('.filters').find('.selectBox').each(function(i){
				container.find('span.selectBox').each(function(i){
					if ($(this).find('span.list').length == 0) $(this).addClass('empty-list');
				});				
			}				
		});
			
		return false;
	});
	if ($('.quickSearch').length != 0){
	var params = {
		changedEl: ".quickSearch select",
		visRows: 5,
		scrollArrows: true
	}
	cuSel(params);
	jQuery(".cusel").each(function(){
		var w = parseInt(jQuery(this).width()),
		scrollPanel = jQuery(this).find(".cusel-scroll-pane");
		if(w>=scrollPanel.width()) {
			jQuery(this).find(".jScrollPaneContainer").width(w);
			scrollPanel.width(w);
		}
	});
	}
	
	if($('#basket_form input[type="text"]').length != 0){
		$('#basket_form input[type="text"]').live('keyup',(function(){
			$('#recalc').css({'top':$(this).position().top,left:$(this).position().left,'display':'block'})
		}))
		$('#recalc').live('click',function(){
			$(this).parent().submit();
		})
	}
	if($('a[target="newItem"]').length!=0){
		$('a[target="newItem"]').each(function(){
			$(this).attr('href',$(this).attr('href') + '?frame=1')
		})
	}
	
})

function startTabs()
{
	if ($('.tabCont').length == 0){
		return;
	}
	$('.tabCont').each(function(i){
		$(this).find('> ul li > a').each(function(i2){
			$(this).attr('href','#tab_'+ i + '_' + i2);
		})
		$(this).find('> div.tabText').each(function(i2){
			$(this).attr('id','tab_'+ i + '_' + i2);
		})

		//console.log($(this).find('.selectBox .list').length);
		$(this).find('.selectBox').each(function(i){
			if($(this).find('.list span')){//console.log($(this).find('.list span').length);	
				if($(this).find('.list span').length == 0){
					$(this).addClass('empty-list');
				}
			}	
		});
		
	}).tabs( "destroy" ).tabs();
}

function resizeFrame(nFrame,fHeight){
  $('iframe[name='+nFrame+']').height(fHeight);
  $('#itemPrev').css({
    'top':(($('html').scrollTop() || $('body').scrollTop()) + ($(window).height() - $('#itemPrev').outerHeight())/2 + 'px'),
    'left':(($(window).width() - $('#itemPrev').outerWidth())/2 + 'px')
  });
}

function resizeFrameImage(nFrame,fHeight,fWidth){
  //console.log(new Date().getMilliseconds())
  $('iframe[name='+nFrame+']').height(fHeight).width(fWidth);
  $('#itemPrev').css({
    'top':(($('html').scrollTop() || $('body').scrollTop()) + ($(window).height() - $('#itemPrev').outerHeight())/2 + 'px'),
    'left':(($(window).width() - $('#itemPrev').outerWidth())/2 + 'px')
  });
}

function applyFilters(form)
{
	$('#ajax_list').load(document.location.href, $(form).serialize());
	return false;
}

function addBasket(el)
{
	$.post('/shop/basket/add', $(el).serialize(), function (result) {
		top.updateBlockShop(result);
		$('#basket').addClass('popup');
		if(!$('body').is('.popupFrame')){$('body').addClass('holded')};
	})
	return false;
}
function updateBlockShop(result){
	$('#shop').html(result)
}

function deleteBasket(el)
{
	$('#basket_form').load($(el).attr('href'));
	return false;
}

function updateBasket(el)
{
	$.post('/shop/basket', $(el).serialize(), function (result) {
		$('#basket_form').html(result);
	})
	return false;
}

function orderStep1(el)
{
	$(el).find('input[type="submit"]').attr('disabled','disabled');
	$.post('/shop/order/step1', $(el).serialize(), function (result) {
		$('#basket_form').html(result);
	})
	return false;
}

function orderStep2(el)
{
	$(el).find('input[type="submit"]').attr('disabled','disabled');
	$.post('/shop/order/step2', $(el).serialize(), function (result) {
		$('#basket_form').html(result);
	})
	return false;
}

function orderStep3(el)
{
	$(el).find('input[type="submit"]').attr('disabled','disabled');
	$.post('/shop/order/step3', $(el).serialize(), function (result) {
		$('#basket_form').html(result);
	})
	return false;
}

function searchCity()
{
	var city = $('#searchcity').val();
	if (!city) return false;
	$('#searchcity_results').load('/shop/order/searchcity?city=' + city);
	return false;
}

function checkBalance(el)
{
	$.post($(el).attr('action'), $(el).serialize(), function (result) {
		$('.checkBalance .inputBlock').hide();
		$('.checkBalance .rezBlock .rez').html(result).parent().show();
		$(el).find('input').val('');
		$('.checkBalance .rezBlock .escho').one('click',function(){
			$('.checkBalance .rezBlock').hide();
			$('.checkBalance .inputBlock').show();
		})
	});
	return false;
}

function subscribe(form)
{
	$.post('/subscription', $(form).serialize(), function (result) {
		if (result != '') alert(result);
		$(form).closest('.popup').find('.close').click();
	});
	return false;
}

function iagree(check){
	if(check.checked){
		$(check).closest('form').find('input[type="submit"]').attr('disabled','false').removeAttr('disabled')
	} else {
		$(check).closest('form').find('input[type="submit"]').attr('disabled','true')
	}
}

function orderLogin(form)
{
	$.post('/user/login', $(form).serialize(), function (result) {
		if (result != '') alert(result);
		else window.location.href = window.location.href;
	});
	return false;
}

function submitForm(form)
{
	$(form).find('input[type="submit"]').attr('disabled','disabled');
	$.post($(form).attr('action'), $(form).serialize(), function (result) {
		$('#' + $(form).attr('rel')).html(result);
	});
	return false;
}

function persOrderItemSelect(itemname)
{
	$('#itemname').val(itemname);
	$('.popup').find('.close').click();
	return false;
}

function updateFilters(form)
{
	$.post('/shop/updatefilters', $(form).serialize(), function(result) {
		if (result) {
			$(form).find('table.quickSearch span[val!=""]').each(function () {
				$(this).hide();
			});
			for (var filter_id in result) {
				var filter = result[filter_id];
				if (filter) for (var value_id in filter) {
					$('#cuselFrame-filter' + filter_id).find('span[val="' + value_id + '"]').show();
				}
			}
		} else {
			$(form).find('table.quickSearch span').each(function () {
				$(this).show();
			});
		}
		var selects = '';
		$(form).find('input').each(function (index) {
			if (index) selects += ',';
			selects += '#' + $(this).attr('id');
		});
		var params = {
			refreshEl: selects,
			visRows: 5,
			scrollArrows: true
		}
		cuSelRefresh(params);
	}, 'json');
}
