﻿function setCookie(name, value)
	{
	var valueEscaped = value;
	var expiresDate = new Date();
	expiresDate.setTime(expiresDate.getTime() + 3 * 24 * 60 * 60 * 1000);
	var expires = expiresDate.toGMTString();
	var newCookie = name + "=" + valueEscaped + "; path=/; expires=" + expires;
	if (valueEscaped.length <= 4000) document.cookie = newCookie + ";";
	}
function getCookies(name)
	{
    var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"))
    return matches ? decodeURIComponent(matches[1]) : undefined
	}
function deleteCookie(name, path, domain) 
	{
	if (getCookies(name)) 
		{
		document.cookie = name + "=" + 
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT"
		}
	}

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

function get_search()
	{
	var len_t = $('input[name="sr_title"]');
	$('ul.serch_list').remove();
	if(len_t.val().length>=3)
		{
		$('ul.serch_list').remove();
		$('<ul class="serch_list" style="display: block;"><li>загрузка...<img src="/static/dis/ajax-loader_min.gif"></li></ul>').insertAfter('input[name="sr_title"]');
		tid = setTimeout(function()
			{
			var len = $('input[name="sr_title"]');
			if (len.val()==len_t.val()) 
				{
				$.post("/ajax/1/", {"sr_title": $('input[name="sr_title"]').val() }, function(data)
					{
					$('ul.serch_list').remove();
					date = eval(data);
					if(date!="")
						{
						$('<ul class="serch_list">').insertAfter('input[name="sr_title"]');
						for (var key in date)
							{
							$('ul.serch_list').append('<li>'+"<a href='"+date[key].url+"'>"+decodeURIComponent(escape(date[key].title))+"</a>"+'</li>');
							}
						$('ul.serch_list').fadeIn(100);
						}
					})
				}
			}, 760);
		}
	}
function valid_email(input)
	{
	var reEmail = new RegExp(	'^[a-z0-9\._-]+@[a-z0-9][a-z0-9_-]*(\.[a-z0-9_-]+)*'+
								'\.([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|'+
								'int|mil|museum|name|net|org|pro|travel)$', 'i')
	if (reEmail.test(input))
		return true;
	else
		return false;
	}
function set_time_interval()
	{
	for (var i = 1; i<=3; i++)
			{
			$('#time'+i).removeAttr('disabled');
			}
	var string_dat = $("select[name='date_s'] option:selected").val().split(".")
	var cart_sel_dat = new Date(string_dat[2], string_dat[1]-1, string_dat[0]);
	var now_date = new Date();
	if (cart_sel_dat.getDate() == now_date.getDate() && cart_sel_dat.getMonth() == now_date.getMonth() && cart_sel_dat.getFullYear() == now_date.getFullYear())
		for (var i = 1; i<=3; i++)
			{
			if (now_date.getHours() >= $('#time'+i).val().split('-')[1].split(":")[0])
				$('#time'+i).attr('disabled', 'disabled');
			}
		console.log(cart_sel_dat.getDate() == now_date.getDate() && cart_sel_dat.getMonth() == now_date.getMonth() && cart_sel_dat.getFullYear() == now_date.getFullYear());
	}
$(document).ready(function ()
	{
	if ($("select[name='date_s']").length)
		{
		set_time_interval();
		$("select[name='date_s']").bind('change', function()
			{
			set_time_interval();
			});
		}
	$("form[name='recover']").submit(function()
		{
		if(!valid_email($('input[name="email"]').val()))
			{
			alert("Не правильный адрес электронной почты!");
			return false;
			}
		});
	$('.bonus_help').hover(function()
		{
		$('<div class="bonus_balloon">'+bonus_info+'</div>').appendTo($(this));
		$('.bonus_balloon').show('fast');
		}
	,function()
		{
		$('.bonus_balloon').remove();
		});
	doc_c=1;
	$('.togler').bind('click', function(e)
		{
		e.preventDefault();
		$(this).parent().next().toggle();
		});
	$('#auth_url').bind('click', function(e)
		{
		doc_c=0;
		e.preventDefault();
		$('#auth_form').show();
		});
	$('#auth_form').bind('click',function(e)
		{
		doc_c=0;
		});
	$(document).bind('click', function(e)
		{
		doc_c+=1;
		if(doc_c>1)
			$('#auth_form').hide();
		});
	$('form[name="private_info"]').bind('submit', function(e)
		{
		if ($('.user_info input[name="e-mail"]').val() && !valid_email($('.user_info input[name="e-mail"]').val()))
			{
			alert('Не правельный адрес электронной почты!')
			e.preventDefault();
			}
		if ($('.user_info input[name="pass"]').val() && $('.user_info input[name="pass"]').val().length<6)
			{
			alert('Слишком короткий пароль! Не мение 6 символов')
			e.preventDefault();
			}
		});
	$('form[name="order"]').bind('submit', function(e)
		{
		if ($('input[name="NAME"]').val().length<2)
			{
			alert('Введите имя!')
			e.preventDefault();
			}
		if ($('input[name="PHONE"]').val().length<6)
			{
			alert('Слишком короткий номер телефона! Не мение 7 символов')
			e.preventDefault();
			}
		});
	$('form[name="reg_user"]').bind('submit', function(e)
		{
		if (!valid_email($('.user_info input[name="e-mail"]').val()))
			{
			alert('Не правельный адрес электронной почты!')
			return false;
			}
		if ($('.user_info input[name="pass"]').val().length<=6)
			{
			alert('Слишком короткий пароль! Не мение 6 символов')
			return false;
			}
		});
	/*var timer_a;
	$('.user_info input[name="e-mail"]').bind('keyup', function()
		{
		if ($(this).val().length>4 && valid_email($(this).val()))
			{
			var input = $(this);
			clearTimeout(timer_a);
			timer_a = setTimeout(function()
				{
				$.post('/ajax/1/', {'login_test': input.val()}, function(data)
					{
					if(data=="1")
						input.css('background-color', 'red');
					else
						input.css('background-color', 'green');
					});
				}, 1000);
			};
		});*/
	if ($('.sumer.cart').length)
		get_cart_sum();
	if ($('#items_on_page').length)
		{
		$('#items_on_page').change(function()
			{
			setCookie('items_on_page', $(this).val());
			location.href = "../1/"
			});
		}
	if ($('#map1').length)
		{
		set_canv($("#sheme"), "/static/dis/ne.gif", 'span.cat_title');
		}
	$(".cart_count").change(function()
		{
		if (parseInt($(this).val()))
			{
			if ($(this).attr('name')=="price")
				cange_ord($(this).attr('id').replace("cat_", ""), 1, parseInt($(this).val()))
			else if ($(this).attr('name')=="user")
				cange_ord($(this).attr('id').replace("cat_", ""), 2, parseInt($(this).val()))
			}
		});
	$('#add_cart').submit(function(e)
		{
		var col = 0;
		$('.price_inp').each(function()
			{
			col+= $(this).val()*1;
			});
		if (!col)
			{
			e.preventDefault();
			alert('Введите количество билетов!');
			}
		if ($('input[name="name_cat"]').length && !$('input[name="name_cat"]').val())
			{
			e.preventDefault();
			alert('Введите название категории!');
			}
		});
	$('input[name="sr_title"]').css({"color": "#aaa", "font-style": 'italic'})
	$('input[name="sr_title"]').val('Быстрый и умный поиск');
	$('a.del_href').click(function(e)
			{
			e.preventDefault();
			var no_ord = $(this).attr('id').replace('del_', '');
			setCookie('ord_'+no_ord, '');
			deleteCookie('ord_'+no_ord);
			$('#ord_'+no_ord).remove();
			document.location = "";
			});
	if ($('.dat_list .unwrap').length)
		{
		$('input[name="dat_list"]').change(function()
			{
			$('.dat_list .selected').removeClass('selected');
			$('input[name="dat_list"]').filter(':checked').parent().addClass('selected');
			$('#price table').animate({opacity: 0}, 500);
			var id = $('input[name="dat_list"]').filter(':checked').val();
			$('#select_time').val(id);
			setTimeout(function()
				{
				$.post("/ajax/"+ $('#event').val() +"/", { sel_dat: id },
				function(data)
					{
					unset_canv();
					$('#price table').html(data);
					$('#price table').css('opacity','0');
					table_wrap($('div.order #price table'));
					$('#price table').animate({opacity: 1}, 500);
					set_canv($("#sheme"), "/static/dis/ne.gif", 'span.cat_title');
					});
				}, 500);
			});
		}
	if ($('#price input').length)
		{
		$('#cleaner').click(function(e)
			{
			e.preventDefault();
			$('#price input.price_inp').each(function()
				{
				$(this).val("0");
				});
			get_sum();
			});
		$('#price input.price_inp').each(function()
			{
			$(this).val("0");
			});
		get_sum();
		}
	$('div.mini_block').click(function()
		{
		location.href=$(this).find('a').eq(0).attr('href');
		});
	addlis();
	$('.cal input[type="radio"]').eq(0).click(function()
		{
		set_filter()
		});
	$('.cal input[type="radio"]').eq(1).click(function()
		{
		set_filter(2)
		});
	$('code.list a').each(function()
		{
		$(this).addClass($(this).attr("id")==getCookies("sort_type")?"selected":"");
		});
	$('code a').click(function(e)
		{
		setCookie("sort_type", $(this).attr('id'));
		});
	$('input[name="sr_title"]').blur(function(){
		if (!$('input[name="sr_title"]').val())
			{
			$('input[name="sr_title"]').css({"color": "#aaa", "font-style": 'italic'})
			$('input[name="sr_title"]').val('Быстрый и умный поиск');
			}
		$('ul.serch_list').fadeOut(200, function(){$('ul.serch_list').remove()});
		});
	$('input[name="sr_title"]').focus(function()
		{
		$('input[name="sr_title"]').css({"color": "", "font-style": ''})
		if ($('input[name="sr_title"]').val()=='Быстрый и умный поиск')
			$('input[name="sr_title"]').val('');
		$(this).keyup(function(event) 
			{
			event.preventDefault();
			});
		});
	$('input[name="sr_title"]')[0].onkeydown = function(event)
		{
		if (!event) event = window.event;
		keycode = event.keyCode ? event.keyCode : event.which ? event.which : null;
		if (keycode == 0x26)
			{
			pde(event);
			}
		}
	$('input[name="sr_title"]')[0].onkeyup = function keyPress(event)
		{
		try
			{clearTimeout(tid);}
		catch(e)
			{}	
		if (!event) event = window.event;
		keycode = event.keyCode ? event.keyCode : event.which ? event.which : null;
		if (keycode != 0x25 && keycode != 0x27 && keycode != 0x26 && keycode != 0x28)
			{
			var len_t = $('input[name="sr_title"]');
			$('ul.serch_list').remove();
			if(len_t.val().length>=3)
				{
				$('ul.serch_list').remove();
				$('<ul class="serch_list" style="display: block;"><li>загрузка...<img src="/static/dis/ajax-loader_min.gif"></li></ul>').insertAfter('input[name="sr_title"]');
				tid = setTimeout(function()
					{
					var len = $('input[name="sr_title"]');
					if (len.val()==len_t.val()) 
						{
						$.post("/ajax/1/", {"sr_title": $('input[name="sr_title"]').val() }, function(data)
							{
							$('ul.serch_list').remove();
							date = eval(data);
							if(date!="")
								{
								$('<ul class="serch_list">').insertAfter('input[name="sr_title"]');
								for (var key in date)
									{
									$('ul.serch_list').append('<li>'+"<a href='"+date[key].url+"'>"+decodeURIComponent(escape(date[key].title))+"</a>"+'</li>');
									}
								$('ul.serch_list').fadeIn(100);
								}
							})
						}
					}, 760);
				}
			}
		else if (keycode == 0x28 && $('ul.serch_list').length)
			{
			$('input[name="sr_title"]').val($('input[name="sr_title"]').val());
			var old = $('ul.serch_list li').filter(".selected");
			if(old.length)
				{
				old.next().addClass("selected");
				old.removeClass("selected");
				}
			else
				{
				$('ul.serch_list li').eq(0).addClass("selected");
				}
			}
		else if (keycode == 0x26 && $('ul.serch_list').length)
			{
			$('input[name="sr_title"]').val($('input[name="sr_title"]').val());
			var old = $('ul.serch_list li').filter(".selected");
			if(old.length)
				{
				old.prev().addClass("selected");
				old.removeClass("selected");
				}
			else
				{
				$('ul.serch_list li').last().addClass("selected");
				}
			}
		else if (keycode == 0x27 && $('ul.serch_list').length)
			{
			
			}
		}
	$('form[name="serch"]').submit(function(e)
		{
		var old = $('ul.serch_list li').filter(".selected");
		if(old.length)
			{
			if($('input[name="sr_title"]').val() == 'Быстрый и умный поиск')
				$('input[name="sr_title"]').val('');
			e.preventDefault();
			document.location = old.find('a').attr("href");
			}
		});
	document.onkeyup = function keyPress(event)
		{
		if (!event) event = window.event;
		if(event.ctrlKey)
			{
			keycode = event.keyCode ? event.keyCode : event.which ? event.which : null;
			if (keycode == 0x25 && $('div.navi a.select').index()!=0)
				{
				go_page($('div.navi a.select').prev())
				}
			else if (keycode == 0x27 && ($('div.navi a.select').index() != $('div.navi a').length-1)) 
				{
				go_page($('div.navi a.select').next())
				}
			}
		}
	// скоро устареет!!!
	$('select[name="cat_sel"]').change(function()
		{
		if ($(this).attr('id')=="top")
			$('form[name="top_cat_filter"]').attr('action', "/cat/"+$(this).val()+"/1/")
		else
			document.location = '../../'+$(this).val()+'/1/';
		});
	// ------------------
	$('select[name="pf_city"]').change(function()
		{
		document.city_filter.submit();
		});
	$('div.serch div p a').eq(0).click(function(){
		$('input[name="sr_title"]').val($(this).text());
		$('input[name="sr_title"]').focus();
		get_search();
		
		return false;
		});
	$('div.serch div p a').eq(1).click(function(e){
		e.preventDefault();
		$srech = $('div.serch .h_add_serch');
		$srech.css("display")!="none"?$srech.hide():$srech.show();
		})
	$('div.serch div.sity_list>a').click(function()
		{
		$('div.serch div>a').each(function()
			{
			$(this).removeClass('select');
			});
		$(this).addClass('select');
		$('#tel').html($(this).attr('tels'));
		setCookie("city", $(this).attr('id'))
		return false;
		})

	$("input.data_pick")
	.datePicker
		({
		startDate:'01/01/2010',
		createButton:false,
		displayClose:true,
		showYearNavigation: false,
		closeOnSelect:true
		})
	.bind
		(
		'click',
		function()
			{
			$(this).dpDisplay();
			this.blur();
			return false;
			}
		);
	if($.browser.msie)
		{
		if($.browser.version<8)
			{
			$('div#ie7').css('display', 'none');
			}
		}
	if ($('#cal').length)
		{
		$("span#cal")
			.datePicker
				({
				startDate:'01/01/2010',
				createButton:false,
				inline:true,
				showYearNavigation: false,
				closeOnSelect:true,
				renderCallback:
					function($td, thisDate, month, year)
					{
					$td.addClass('disabled');
					for (dat in dates)
						{
						if (thisDate.asString() == format_dat(dates[dat].fields.d).asString() && $td.is('.disabled'))
							{
							$td.removeClass('disabled');
							$td.click(function()
								{
								var date = dates[dat].fields.d;
								$("span#cal").dpSetSelected(thisDate.asString());
								var post_d = deformat_dat(thisDate);
								$('#price table').animate({opacity: 0}, 500);
								setTimeout(function()
									{
									$.post("/ajax/"+ $('#event').val() +"/", { dat: post_d },
									function(data)
										{
										unset_canv();
										$('#price table').html(data);
										$('#price table').css('opacity','0');
										table_wrap($('div.order #price table'));
										$('#price table').animate({opacity: 1}, 500);
										set_canv($("#sheme"), "/static/dis/ne.gif", 'span.cat_title');
										});
									}, 500);
								$.post("/ajax/"+ $('#event').val() +"/", { date: post_d },
								function(data)
									{
									$('div.cal ul').html(data);
									addlis();
									$('#select_time').val($('a.oc_select').attr('id'));
									});
								});
							}
						}
					}
				})
			.dpSetSelected(format_dat(dates[0].fields.d).asString());
		}
	$('div.w_block>div').hover
		(
		function ()
			{
			$(this).animate({backgroundPosition: '-617px 0px'}, 200);
			},
		function ()
			{
			$(this).animate({backgroundPosition: '30px 0px'},  10);
			}
		);
	$('#towns').addClass('h_add_serch');
	$('#cats').addClass('h_add_serch');
	$('select[name="p_"]').change(function(e)
		{
		var ofst = $(this).offset()
		get_count_event("", ofst.top);
		});
	$('#towns input, #cats input').click(function(e)
		{
		var ofst = $(this).offset()
		get_count_event("", ofst.top);
		});
	$('#towns_s').click(function()
		{
		$('#towns').toggleClass('h_add_serch');
		return false;
		});
	$('#cats_s').click(function()
		{
		$('#cats').toggleClass('h_add_serch');
		return false;
		});
	$('#set_filter').click(function(e)
		{
		$('form[name="filter_form"] input[type="hidden"]').each(function()
			{
			if ($(this).attr("name")!="url")
				$(this).remove();
			});
		for (var key in $('#filter_cal').dpGetSelected())
			$('form[name="filter_form"]').append('<input name="d_'+key+'" type="hidden" value="'+ deformat_dat($('#filter_cal').dpGetSelected()[key]) +'"> ');
		});
	$('.cal input[type="radio"]').eq(0).attr('checked', 'checked');
	set_filter();
	try 
		{
		setFilter(filter);
		}
	catch(v)
		{
		$('div.navi a').unbind();
		}
	try 
		{
		if(typeof(top_serch))
			setSerch(top_serch)
		}
	catch(e)
		{
		e;
		}
	if ($('div.slider div').length)
		{
		slider_eve();
		}
	all_wrap($(this));
	table_wrap($('div.order #price table'));
	});
function setSerch(filter)
	{
	if($('input[name="sr_title"]').val() == 'Быстрый и умный поиск')
		$('input[name="sr_title"]').val('');
	$('div.navi a').click(function(e)
		{
		e.preventDefault();
		document.serch.action = $(this).attr("href");
		document.serch.submit();
		});

	$('code a').click(function(e)
		{
		e.preventDefault();
		setCookie("sort_type", $(this).attr('id'));
		document.serch.action = $(this).attr("href");
		document.serch.submit();
		});
	if (filter.sr_cat)
		{
		$('div.serch .h_add_serch').show();
		$("div.serch select[name='sr_cat'] option[value='"+filter.sr_cat+"']").attr("selected", "selected");
		}
	if (filter.sr_place)
		{
		$('div.serch .h_add_serch').show();
		$("div.serch select[name='sr_place'] option[value='"+filter.sr_place+"']").attr("selected", "selected");
		}
	if (filter.dat_end)
		{
		$('div.serch .h_add_serch').show();
		$("div.serch input[name='dat_end']").val(filter.dat_end);
		}
	if (filter.dat_start)
		{
		$('div.serch .h_add_serch').show();
		$("div.serch input[name='dat_start']").val(filter.dat_start);
		}
	if (filter.sr_title)
		{
		$("div.serch input[name='sr_title']").val(decodeURIComponent(escape(filter.sr_title)));
		}
	}
function setFilter(filter)
	{
	$('div.navi a').click(function(e)
		{
		e.preventDefault();
		document.filter_form.action = $(this).attr("href");
		for (var key in $('#filter_cal').dpGetSelected())
			$('form[name="filter_form"]').append('<input name="d_'+key+'" type="hidden" value="'+ deformat_dat($('#filter_cal').dpGetSelected()[key]) +'"> ');
		document.filter_form.submit();
		});
	$('code a').click(function(e)
		{
		e.preventDefault();
		setCookie("sort_type", $(this).attr('id'));
		document.filter_form.action = $(this).attr("href");
		for (var key in $('#filter_cal').dpGetSelected())
			$('form[name="filter_form"]').append('<input name="d_'+key+'" type="hidden" value="'+ deformat_dat($('#filter_cal').dpGetSelected()[key]) +'"> ');
		document.filter_form.submit();
		});
	if (filter.date!="")
		{
		if (filter.date_type=="range")
			{
			set_filter(2);
			$('div.cal input[value="range"]').attr('checked', 'checked');
			}
		for (var fil in  filter.date)
			{
			var DateArray = filter.date[fil].split("-");
			var theDate = new Date(DateArray[0], DateArray[1]-1, DateArray[2]);
			console.log(theDate);
			$('#filter_cal').dpSetSelected(theDate.asString());
			}
		}
	if (filter.town!="")
		{
		$('#towns').removeClass('h_add_serch');
		for (var fil in  filter.town)
			{
			$('div.cal input[name="'+filter.town[fil]+'"]').attr('checked', 'checked');
			}
		}
	if (filter.cat!="")
		{
		$('#cats').removeClass('h_add_serch');
		for (var fil in  filter.cat)
			{
			$('div.cal input[name="'+filter.cat[fil]+'"]').attr('checked', 'checked');
			}
		}
	if (filter.place!="")
		{
		$('div.cal option[value="'+filter.place+'"]').attr("selected", "selected");
		}
	if (filter.url!="")
		{
		$('div.cal input[name="url"]').val(filter.url);
		}
	}

(function($) {
    if(!document.defaultView || !document.defaultView.getComputedStyle){ // IE6-IE8
        var oldCurCSS = $.curCSS;
        $.curCSS = function(elem, name, force){
            if(name === 'background-position'){
                name = 'backgroundPosition';
            }
            if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
                return oldCurCSS.apply(this, arguments);
            }
            var style = elem.style;
            if ( !force && style && style[ name ] ){
                return style[ name ];
            }
            return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
        };
    }

    var oldAnim = $.fn.animate;
    $.fn.animate = function(prop){
        if('background-position' in prop){
            prop.backgroundPosition = prop['background-position'];
            delete prop['background-position'];
        }
        if('backgroundPosition' in prop){
            prop.backgroundPosition = '('+ prop.backgroundPosition;
        }
        return oldAnim.apply(this, arguments);
    };

    function toArray(strg){
        strg = strg.replace(/left|top/g,'0px');
        strg = strg.replace(/right|bottom/g,'100%');
        strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
        var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
        return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
    }

    $.fx.step. backgroundPosition = function(fx) {
        if (!fx.bgPosReady) {
            var start = $.curCSS(fx.elem,'backgroundPosition');
            if(!start){//FF2 no inline-style fallback
                start = '0px 0px';
            }

            start = toArray(start);
            fx.start = [start[0],start[2]];
            var end = toArray(fx.end);
            fx.end = [end[0],end[2]];

            fx.unit = [end[1],end[3]];
            fx.bgPosReady = true;
        }
        //return;
        var nowPosX = [];
        nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
        nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
        fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

    };
})(jQuery);

function cange_ord(no_ord, no_var, val)
	{
	var ord_arr = getCookies('ord_'+no_ord).split("|");
	var ord_str = ""
	ord_arr[no_var] = val;
	for (var i = 0; i<ord_arr.length; i++)
		{
		ord_str = ord_str + (i?"|":"") +  encodeURIComponent(ord_arr[i])
		}
	setCookie('ord_'+no_ord, ord_str);
	}

function all_wrap($obj)
	{
	$obj.find('input[type=checkbox]').each(function() {
		$(this).wrap(function() {
			var lm = $(this).css("margin-left");
			var rm = $(this).css("margin-right");
			var tm = $(this).css("margin-top");
			var bm = $(this).css("margin-bottom");
			$(this).css("margin-left", "0px");
			$(this).css("margin-right", "0px");
			$(this).css("margin-top", "0px");
			$(this).css("margin-bottom", "0px");
			return ($(this).is(':checked')) ? '<span id="ch" class="selected" style="margin-left: '+lm+'; margin-right: '+rm+'; margin-top: '+tm+'; margin-bottom: '+bm+';"/>' : '<span id="ch" style="margin-left: '+lm+'; margin-right: '+rm+'; margin-top: '+tm+'; margin-bottom: '+bm+';"/>';
		});
	});
	$obj.find('input[type=radio]').each(function() {
		if (!$(this).is('.unwrap'))
			$(this).wrap(function() {
				return ($(this).is(':checked')) ? '<span id="ra" class="selected" style="margin: '+$(this).css("margin")+'"/>' : '<span id="ra" style="margin-left: '+$(this).css("margin-left")+'; margin-right: '+$(this).css("margin-right")+'; margin-top: '+$(this).css("margin-top")+'; margin-bottom: '+$(this).css("margin-bottom")+';"/>';
			});
	});
	$obj.find('input[type=radio]').click(function()
		{
		if (!$(this).is('.unwrap'))
			{
			$cli=$(this);
			$obj.find('input[type=radio]').each(function() {
				if($(this).prop('name')==$cli.prop('name'))
					$(this).parent().removeClass('selected');
			});
			$(this).parent().addClass('selected');
			}
		});
	$obj.find('input[type=checkbox]').click(function()
		{
		if($('div.order table').find($(this)).length)
			{
			return false;
			}
		else
		$(this).parent().toggleClass('selected');
		});
	}
function table_wrap($obj)
	{
	$('input.price_inp').keyup(function()
		{
		get_sum();
		});
	$("img.p").click(function()
		{
		var no = $(this).attr('id').replace('pimg_', '')
		var input = $("#cat_"+no);
		input.val(input.val()*1+1);
		if ($('.sumer.cart').length)
				{
				var price_keeper = $(this).parent().prev()
				price = price_keeper.attr('id').replace('price_', '')
				var price_text = price_keeper.text();
				curency = price_text.replace(parseInt(price_text), "");
				price_keeper.text(price*input.val()*1 + curency)
				}
		if (input.is(".cart_count"))
			{
			if (input.attr('name')=="price")
				cange_ord(no, 1, input.val());
			else if (input.attr('name')=="user")
				cange_ord(no, 2, input.val());
			}
		if ($('.sumer.cart').length)
			get_cart_sum();
		else
			get_sum();
		});
	$("img.m").click(function()
		{
		var no = $(this).attr('id').replace('mimg_', '')
		var input = $("#cat_"+no);
		if (input.val() && input.val()*1>0)
			{
			if ($('#cart').length)
				{
				if (input.val()*1>1)
					{
					input.val(input.val()*1-1);
					}
				}
			else
				input.val(input.val()*1-1);
			if ($('.sumer.cart').length)
				{
				var price_keeper = $(this).parent().prev()
				price = price_keeper.attr('id').replace('price_', '')
				var price_text = price_keeper.text();
				curency = price_text.replace(parseInt(price_text), "");
				price_keeper.text(price*input.val()*1 + curency)
				}
			}
		if (input.is(".cart_count"))
			{
			if (input.attr('name')=="price")
				cange_ord(no, 1, input.val());
			else if (input.attr('name')=="user")
				cange_ord(no, 2, input.val());
			}
		if ($('.sumer.cart').length)
			get_cart_sum();
		else
			get_sum();
		});
	$('#price input.price_inp').each(function()
			{
			$(this).val("0");
			});
	get_sum()
	}
function get_cart_sum()
	{
	var sum = 0;
	var bonus_sum = 0;
	var count = 0;
	var info="";
	$('td.price_keeper').each(function()
		{
		if (parseInt($(this).text())*1>0)
			{
			var input = $(this).next().find('input');
			var nober = input.attr('id').replace('cat_','');
			count+=input.val()*1;
			var price_text = $(this).text();
			price = parseInt(price_text);
			if(price)
				{
				curency = price_text.replace(price, "").slice(2);
				sum+= price;
				bonus_sum+= $('#ord_'+nober+' .title_cat').attr('alt').replace('bonus_','')*input.val()*1;
				}
			}
		});
	if (sum)
		{
		if (count==1 && curency.search(/руб./)!=-1)
			{
			sum_int=sum*1+300;
			sum+="+300";
			info=" (доставка одного билета платная)"
			$('#cart_sum').show();
			}
		else
			sum_int=sum*1;
		$('input[name="cart_sum"]').val(sum_int);
		$('.sumer.cart div .count_price').html('Вами выбрано <strong>билетов - '+count+' </strong> на сумму <strong>'+sum+' '+curency+'</strong>'+info);
		$('.sumer.cart div p.bonus strong').html(bonus_sum);
		}
	}
function get_sum()
	{
	if($('div.sum').length)
		$('#sum').fadeOut(function()
			{
			var count = 0;
			var price = 0;
			var sum = 0;
			var cats = "";
			var bonus_sum = 0;
			$('#price input').each(function()
				{
				if ($(this).val()*1>0)
					{
					$(this).css({'color': '#d3374c', 'font-weight': 'bold'});
					$(this).parent().parent().addClass('selected');
					var no = $(this).attr('id').replace('cat_', '')
					cats += cats?", "+$("#title_cat_"+no).text().slice(0, -2):""+$("#title_cat_"+no).text().slice(0, -2);
					var price_text = $("#pr_"+no).text();
					if (price_text.search("-")!= -1)
						count=-1000;
					count+=$(this).val()*1;
					price = parseInt(price_text);
					if(price)
						{
						curency = price_text.replace(price, "");
						sum+= $(this).val()*1*price;
						bonus_sum+= $('#title_cat_'+no).attr('alt')*$(this).val()*1;
						}
					}
				else
					{
					$(this).parent().parent().removeClass('selected');
					$(this).css({'color': '', 'font-weight': ''});
					}
				});
			if (sum && count>0)
				{
				console.log(sum);
				if (count==1 && curency.search(/руб./)!=-1)
					{
					sum_int=sum*1
					$('#sum').show();
					}
				else
					sum_int=sum*1;
				$('input[name="sum"]').val(sum_int);
				$('div.sumer div').html("");
				$("<p>Вами выбранно <strong>билетов - "+count+'</strong> ('+ cats +') на '+ $('div.dat_list li.selected').text() +' на сумму: <strong>'+sum+curency+"</strong></p>").appendTo($('.sumer div'));
				$("<p>С этим заказом вам будет начислено <strong>"+ bonus_sum +"</strong> бонусых рублей.</p>").appendTo($('.sumer div'));
				}
			else
				{
				$('input[name="sum"]').val(0);
				$('div.sumer div').html("");
				}
			});
	}
function addlis()
	{
	if ($('#cal').length)
		{
		$('div.cal li a').click(function()
			{
			$('div.cal li a').removeClass("oc_select");
			$(this).addClass("oc_select");
			var id = $(this).attr("id");
			$('#select_time').val(id);
			$('#price table').animate({opacity: 0}, 500);
			setTimeout(function()
				{
				$.post("/ajax/"+ $('#event').val() +"/", { sel_dat: id },
				function(data)
					{
					unset_canv();
					$('#price table').html(data);
					$('#price table').css('opacity','0');
					table_wrap($('div.order #price table'));
					$('#price table').animate({opacity: 1}, 500);
					set_canv($("#sheme"), "/static/dis/ne.gif", 'span.cat_title');
					});
				}, 500);
			return false;
			});
		}
	}
function css_width($inp)
	{
	if($inp.length)
		return $inp.css('width').replace('px', '')*1
	+$inp.css('padding-left').replace('px', '')*1
	+$inp.css('padding-right').replace('px', '')*1
	+$inp.css('margin-left').replace('px', '')*1
	+$inp.css('margin-right').replace('px', '')*1+3;
	}
function set_filter(num)
	{
	if ($('#filter_cal').length && num)
		{
		$('#filter_cal').datePicker
			({
			startDate:'01/01/2010',
			createButton:false,
			inline:true,
			showYearNavigation: false,
			closeOnSelect:false,
			selectMultiple:true,
			numSelectable: num
			}).dpClear();
		}
	else if ($('#filter_cal').length)
		{
		$('#filter_cal').datePicker
			({
			startDate:'01/01/2010',
			createButton:false,
			inline:true,
			showYearNavigation: false,
			closeOnSelect:false,
			selectMultiple:true
			}).dpClear();
		}
	}
function get_count_event(td, top)
	{
	if ($('#filter_cal').find(td).length || td=="")
		{
		$('event_counter').remove();
		$('div.con_left').append("<div class='event_counter'></div>");
		info = $('div.event_counter');
		info.css({"right": "-78px"});
		info.offset({ top: (top*1) });
		info.html('<a style="text-decoration: none;">Поиск <img src="/static/dis/ajax-loader_2.gif"></a><div>&nbsp;</div>');

		out={};
		if ($('#filter_cal').dpGetSelected())
			{
			out.date_type=$('div.cal input[name="r_"]:checked').val();
			out.dates=[];
			for (var key in $('#filter_cal').dpGetSelected())
				out.dates.push(deformat_dat($('#filter_cal').dpGetSelected()[key]))
			}
		if ($('#towns input:checked').length)
			{
			out.towns=[]
			$('#towns input:checked').each(function()
				{
				out.towns.push($(this).attr("name"));
				});
			}
		if ($('#cats input:checked').length)
			{
			out.cats=[]
			$('#cats input:checked').each(function()
				{
				out.cats.push($(this).attr("name"));
				});
			}
		if ($('select[name="p_"] option:selected').val())
			out.place=$('select[name="p_"] option:selected').val();
		$.post("/ajax/90/", {filter: JSON.stringify(out)},
			function(data)
				{
				info.html();
				info.html("<a href='/' onclick='submit_filter(event)'>мероприятий: "+data+"</a><div>&nbsp;</div>");
				try
					{clearTimeout(to);}
				catch(e)
					{}
				to = setTimeout(function()
					{
					info.remove();
					}, 30000)
				});
		}
	}
function submit_filter(e)
	{
	pde(e);
	$("#set_filter").click();
	}
function pde(e)
{
    if(e.preventDefault)
        e.preventDefault();
    else
        e.returnValue = false;
}
function go_page($linc)
	{
	$linc.click()
	}
function deformat_dat(d)
	{
	mon=d.getMonth()+1+"";
	if(mon.length<=1) mon="0"+mon;
	day=d.getDate()+"";
	if(day.length<=1) day="0"+day;
	return d.getFullYear() + "-" + mon +"-"+day;
	}
function format_dat(str)
	{
	var date_time = str.split(" ");
	var date = date_time[0].split("-");
	var time = date_time[1].split(":");
	var out = new Date(date[0]*1, date[1]*1-1, date[2]*1, time[0]*1, time[1]*1, time[2]*1);
	return out;
	}
