var is = 1;
var first = 0;
var system ='';
var currentID = 0; 
var C;
var cauto = true;

$(
	function()
	{
		$(".maximage").maxImage({
			isBackground: true
		});
		
		///////////////////////////////////
		(function($) {
  		$.fn.sorted = function(customOptions) {
    		var options = {
      		reversed: false,
      		by: function(a) { return a.text(); }
    		};
    		$.extend(options, customOptions);
    		$data = $(this);
    		arr = $data.get();
    		arr.sort(function(a, b) {
      		var valA = options.by($(a));
      		var valB = options.by($(b));
      		if (options.reversed) {
        		return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;				
      		} else {		
        		return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;	
      		}
    		});
    		return $(arr);
  		};
		})(jQuery);

		// DOMContentLoaded
		$(function() {

  		// bind radiobuttons in the form
  		var $filterType = $('#filter input[name="type"]');
  		var $filterSort = $('#filter input[name="sort"]');

  		// get the first collection
  		var $applications = $('#applications');

  		// clone applications to get a second collection
  		var $data = $applications.clone();

  		// attempt to call Quicksand on every form change
  		$filterType.add($filterSort).change(function(e) {
    		if ($($filterType+':checked').val() == 'all') {
      		var $filteredData = $data.find('li');
    		} else {
      		var $filteredData = $data.find('li[data-type=' + $($filterType+":checked").val() + ']');
    		}

    		// if sorted by size
    		if ($('#filter input[name="sort"]:checked').val() == "size") {
      		var $sortedData = $filteredData.sorted({
        		by: function(v) {
          		return parseFloat($(v).find('span[data-type=size]').text());
        		}
      		});
    		} else {
      		// if sorted by name
      		var $sortedData = $filteredData.sorted({
        		by: function(v) {
          		return $(v).find('strong').text().toLowerCase();
        		}
      		});
    		}   

    		// finally, call quicksand
    		$applications.quicksand($sortedData, {
      		duration: 800,
      		easing: 'easeInOutQuad'
    		});

  		});

		});
		
		///////////////
		
		
		
		$('.mini_bannerline').jcarousel({
			scroll: 1
		});
		
		$('.catalog_bannerline').jcarousel({
			scroll: 4,
			visible: 4,
			wrap:'both'
		});
		
		$('.product_bannerline').jcarousel({
			scroll: 3,
			visible: 3,
			wrap:'both'
		});
		
		$('.big_bannerline').jcarousel({
			scroll: 1,
			visible:1, 
			auto:5,
			wrap:'both',
			animation:1,
			itemVisibleOutCallback: {
		  		onBeforeAnimation: disappear
			},
			itemVisibleInCallback: {
				onAfterAnimation: appear
			}
		});
		
		$('.d_bannery .jcarousel-prev, .d_bannery .jcarousel-next').animate( { opacity:"0.0" }, {queue: false,duration: 500, easing: 'linear'});
		$('.d_mini_bannery .jcarousel-prev, .d_mini_bannery .jcarousel-next').animate( { opacity:"0.0" }, {queue: false,duration: 500, easing: 'linear'});
		$('.d_catalog_content .jcarousel-prev, .d_catalog_content .jcarousel-next').animate( { opacity:"0.0" }, {queue: false,duration: 500, easing: 'linear'});
		
    	$(".d_bannery").mouseenter(function(){
			$('.d_bannery .jcarousel-prev, .d_bannery .jcarousel-next').animate( { opacity:"1" }, {queue: false,duration: 500, easing: 'linear'});      
  		});

		$(".d_bannery").mouseleave(function(){		
			$('.d_bannery .jcarousel-prev, .d_bannery .jcarousel-next').animate( { opacity:"0.0" }, {queue: false,duration: 500, easing: 'linear'});
    	});
    	
    	$(".d_mini_bannery").mouseenter(function(){
			$('.d_mini_bannery .jcarousel-prev, .d_mini_bannery .jcarousel-next').animate( { opacity:"1" }, {queue: false,duration: 500, easing: 'linear'});      
  		});

		$(".d_mini_bannery").mouseleave(function(){		
			$('.d_mini_bannery .jcarousel-prev, .d_mini_bannery .jcarousel-next').animate( { opacity:"0.0" }, {queue: false,duration: 500, easing: 'linear'});
    	});
    	
    	$(".d_catalog_content").mouseenter(function(){
			$('.d_catalog_content .jcarousel-prev, .d_catalog_content .jcarousel-next').animate( { opacity:"1" }, {queue: false,duration: 500, easing: 'linear'});      
  		});

		$(".d_catalog_content").mouseleave(function(){		
			$('.d_catalog_content .jcarousel-prev, .d_catalog_content .jcarousel-next').animate( { opacity:"0.0" }, {queue: false,duration: 500, easing: 'linear'});
    	});
    	
    	
    	$(".d_catalog_menu ul li").mouseover(function()
    	{
    		$(this).find(".lvl_2").css("display", "block");
    	});
    	$(".d_catalog_menu ul li").mouseout(function()
    	{
    		$(this).find(".lvl_2").css("display", "none");
    	});
    	
    	$(".d_catalog_menu ul li .lvl_2 li").mouseover(function()
    	{
    		$(this).find(".lvl_3").css("display", "block");
    		$(this).find("a").addClass("highlight");
    	});
    	$(".d_catalog_menu ul li .lvl_2 li").mouseout(function()
    	{
    		$(this).find(".lvl_3").css("display", "none");
    		$(this).find("a").removeClass("highlight");
    	});
    	
    	$(".catalog_bannerline .a_img").mouseover(function()
    	{
    		$(this).find(".pic1").addClass("hidden");
    		$(this).find(".pic2").removeClass("hidden");
    	});
    	$(".catalog_bannerline .a_img").mouseout(function()
    	{
    		$(this).find(".pic2").addClass("hidden");
    		$(this).find(".pic1").removeClass("hidden");
    	});
    	
    	
    	
    	
    	var i = 0;
    	$(".rider_block").each(function()
    	{
    		$(this).attr("rel", i);
    		
    		var label = $(this).find("h2").html();
    		$(this).find("h2").remove();
    		
    		$(this).parent().append("<a class=\"a_label\" rel=\"" + i + "\" href=\"\" onclick=\"showRiderBlock(" + i + "); return false;\">" + label + "</a>");
    		
    		i++;
    	});
    	
    	$(".d_rider_info").find(".a_label:first").addClass("active");
    	$(".rider_block:first").css("display", "block");
    	var h = $(".rider_block:first").height();
    	if (h > 400)
    	{
    		$(".rider_block:first").css("overflow", "hidden");
    		$(".rider_block:first").css("overflow-y", "scroll");
    		$(".rider_block:first").css("padding-right", "50px");
    		$(".rider_block:first").css("width", $(".rider_block:first").width() - 50 + "px");
    		$(".rider_block:first").css("height", "400px");
    	}
    	
    	
    	$(".d_rider_info .a_gallery").colorbox({transition:"fade"});
    	$(".a_contest_pic").colorbox({transition:"fade"});
    	$(".d_gallery a").colorbox({transition:"fade"});
    	
    	var list = $("#team_list");
    	var data = list.clone();
    	$(".d_team_sorting a").click(function(e)
    	{
    		$(".d_team_sorting a").removeClass("selected");
    		$(this).addClass("selected");
    		
    		var $preferences = {
    			duration: 800,
    			easing: 'easeInOutQuad',
    			adjustHeight: false
  			};
    		
  			
    		
    		var sorting_kind = $(this).attr("data-value");
			if (sorting_kind == "all")
			{
 				var $filtered_data = data.find("li");
			}
			else
			{
 				var $filtered_data = data.find("li." + sorting_kind);
			}
			
			var $sorted_data = $filtered_data.sorted(
			{
				by: function(v)
				{
  					return $(v).find("strong").text().toLowerCase();
				}
			});
			
			list.quicksand($sorted_data, $preferences);
    	});
    	
    	
    	
    	
    	if ($("#birthday").length > 0)
		{
			var current_date = new Date();
			var day = current_date.getDate();
			var month = current_date.getMonth() + 1;
			if (month < 10)
			{
				month = "0" + month.toString();
			}
			var year = current_date.getFullYear();
			if ($("#birthday").val() == "")
			{
				$("#birthday").val(day + "." + month + "." + year);
			}
						
			$("#birthday").DatePicker({
				format:'d.m.Y',
				date: current_date,
				view: "years",
				position: 'bottom',
				onBeforeShow: function(){
					$("#birthday").DatePickerSetDate($("#birthday").val(), true);
				},
				onChange: function(formated, dates){
					$("#birthday").val(formated);
				}
			});
		}
    	
    	
    	$(".f-search .b-submit").click(function()
    	{
    		$(this).closest("form").submit();
    		return false;
    	});
    	$(".f-search .inp").keydown(function(p)
    	{
    		if(p.keyCode==13)
    		{
    			$(this).closest("form").submit();
    			return false;
    		}
    	});
    	$(".f-search .inp").focus(function()
    	{
    		$(this).parent().addClass("focusedinput");
    	});
    	$(".f-search .inp").blur(function()
    	{
    		$(this).parent().removeClass("focusedinput");
    	});
    	
    	
    	if ($("#map").length > 0)
    	{
    		
    		$("#map").goMap({
    			maptype: "ROADMAP",
    			address: "Москва", 
    			zoom: 10,
    			icon: "/style/roxy_marker.png",
    			oneInfoWindow: false
    		});
    		
    		$(".d_atlas span").each(function()
    		{
    			$.goMap.createMarker({
    				id: $(this).attr("id"),
    				//address: $(this).find("div[rel=geo]").html(),
    				latitude: $(this).find("div[rel=lat]").html(),
    				longitude: $(this).find("div[rel=lon]").html(),
    				html: { 
    					content: $(this).find("div[rel=info]").html()
    				}
    			});
    		});
    	}
    	
	}// function
);

function showRiderBlock(i)
{
	$(".rider_block").css("display", "none");
	var h = $(".rider_block[rel=" + i + "]").height();
	if (h > 400)
	{
		$(".rider_block[rel=" + i + "]").css("overflow", "hidden");
		$(".rider_block[rel=" + i + "]").css("overflow-y", "scroll");
		$(".rider_block[rel=" + i + "]").css("padding-right", "50px");
		$(".rider_block[rel=" + i + "]").css("width", $(".rider_block[rel=" + i + "]").width() - 50 + "px");
		$(".rider_block[rel=" + i + "]").css("height", "400px");
	}
	
	$(".rider_block[rel=" + i + "]").css("display", "block");
	$(".d_rider_info").find(".a_label").removeClass("active");
	$(".d_rider_info").find(".a_label[rel=" + i + "]").addClass("active");
}

function appear(carousel, item, idx, state)
{      
	idx --;
	currentID = idx;
	$(item).find("a").fadeOut(0); 
	$(item).find("a").fadeIn(1500);
} 

function disappear(carousel, item, idx, state)
{
	idx --;
	currentID = idx;

	$(item).find("a").fadeOut(0); 
}

function strReplace(s, r, w)
{
	return s.split(r).join(w);
}

function addslashes(str) 
{
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) 
{
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

function trim(str)
{ 
	str = str.replace(/&nbsp;/g, '');
	return str.replace(/(^\s+)|(\s+$)/g, '');
}



function makeRequest(url) 
{
	var http_request = false;

	if(document.all)
	{
		var yOffset = document.documentElement.scrollTop;
	}
	else
	{
		var yOffset = window.pageYOffset;
	}

	if (window.XMLHttpRequest) 
	{ // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) 
		{
			http_request.overrideMimeType('text/html');
			// Читайте ниже об этой строке
		}
	} 
	else if (window.ActiveXObject) 
	{ // IE
		try 
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) 
			{
			}
		}
	}


	if (!http_request) 
	{
		alert('Unfortunatly your browser doesn\'t support XMLHTTP.');
		return false;
	}

	http_request.onreadystatechange = function() 
	{ 
		if (http_request.readyState == 4)
		{
			if (http_request.status == 200)
			{
				//alert(http_request.responseText);
				var answer = eval('(' + http_request.responseText + ')');
				//alert(http_request.responseText);
				
				
				if (answer.callback[0] == "getCitySelect")
				{
					if (answer.system_error.length > 0)
					{	
						var error = "<ul>";	
						$.each(answer.system_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
						jAlert(error, "Системная ошибка");
					}
					else if (answer.user_error.length > 0)
					{
						var error = "<ul>";	
						$.each(answer.user_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
						jAlert(error, "Ошибка");
					}
					else
					{
						$("#city_select").html(answer.content[0]);
					}
				}
				
				else if (answer.callback[0] == "sendBonusForm")
				{
					if (answer.system_error.length > 0)
					{	
						var error = "<ul>";	
						$.each(answer.system_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
						jAlert(error, "Системная ошибка");
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$("#" + this[1]).html(this[0]);
						});
					}
					else
					{
						$("#bonus_form").html(answer.content[0]);
					}
					$("#bonus_form").find("input[type=\"button\"]").attr("disabled", "");
				}
				
				
				else if (answer.callback[0] == "findRegion")
				{
					if (answer.system_error.length > 0)
					{	
						var error = "<ul>";	
						$.each(answer.system_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
						jAlert(error, "Системная ошибка");
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$("#" + this[1]).html(this[0]);
						});
					}
					else
					{
						$("#region").html(answer.content[0]);
						$("#city").html("");
					}
				}
				
				
				else if (answer.callback[0] == "findCity")
				{
					if (answer.system_error.length > 0)
					{	
						var error = "<ul>";	
						$.each(answer.system_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
						jAlert(error, "Системная ошибка");
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$("#" + this[1]).html(this[0]);
						});
					}
					else
					{
						$("#city").html(answer.content[0]);
					}
				}
				
				else if (answer.callback[0] == "signup")
				{
					if (answer.system_error.length > 0)
					{	
						var error = "<ul>";	
						$.each(answer.system_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
						jAlert(error, "Системная ошибка");
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$("#" + this[1]).html(this[0]);
						});
					}
					else
					{
						$("#contest_form").html(answer.content[0]);
					}
					$("#contest_form").find("input[type=\"button\"]").attr("disabled", "");
				}
				
				
				else if (answer.callback[0] == "addVote")
				{
					if (answer.system_error.length > 0)
					{	
						var error = "<ul>";	
						$.each(answer.system_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
						alert(error, "Системная ошибка");
					}
					else if (answer.user_error.length > 0)
					{
						
					}
					else
					{
						$("#rate" + answer.id[0]).html(answer.content[0]);
					}
				}
				
				else if (answer.callback[0] == "addVote2")
				{
					if (answer.system_error.length > 0)
					{	
						var error = "<ul>";	
						$.each(answer.system_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
						alert(error, "Системная ошибка");
					}
					else if (answer.user_error.length > 0)
					{
						
					}
					else
					{
						$("#rate" + answer.id[0] + "_" + answer.pic).html(answer.content[0]);
						}
				}
			}
			else
			{
				alert("Не удалось получить ответ от сервера");
			}
		}
	};


	//************** ОБРАБАТЫВАЕМ КЛИКИ
	var args = "";
	for (var i = 0; i < arguments.length; i++)
	{
		args += "&p" + i + "=" + arguments[i];
	}
	
	http_request.open('POST', "/getAnswer.php", true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Connection", "close");	
	http_request.send("q=" + url + args);
}

/* конкурс*/
$(document).ready(function(){
	$('#konkurs div.navi span[class!=active]').live('click', function(){
	var span = $(this);
		$.ajax({
			url: '/handler.php',
			dataType: 'html',
			type: 'POST',
			data: {
				'page':span.html()
			},
			success: function(data) {
				$('#konkurs .d_team_wrapper').html(data);
				$('#konkurs div.navi span').removeClass();
				span.addClass('active');
			}
		});
	});
	
	$('#konkurs .ul_team a').unbind('click');
	
});
