var promo_timeout;

function constructLightBox()
{
	$("a[rel*=lightbox]").fancybox({
		'imageScale': false,
		'centerOnScroll': false,
		'callbackOnShow': function(){
				replaceFlash('hide');
		},
		'callbackOnClose': function(){
				replaceFlash('show');
		}
	});
}

function сarouselPromo( e, auto )
{
	e.each( function(i){
		if ( $(this).attr('class') == 'active' )
		{
			if ( e.length == i+1 )
			{
				$next = $(e[0]);
			}
			else
			{
				$next = $(e[i+1]);
			}
			
			$next.find('a.promo').click();
			
			if ( auto )	
				promo_timeout = setTimeout( "сarouselPromo($('ul li[rel=promo]'), true)", 10000);
				
			return false;
		}
	})
}

$(document).ready(
	function()
	{
		constructLightBox();
		
		$("a.external").each(function(){
			$(this).attr("href",$(this).attr("title"));
			$(this).removeAttr("title");
			$(this).removeAttr("class");
		});
		
		$("div.catalog_style a").bind("click", function(){
			$("div.catalog_style a").parent().removeClass("selected");
			$(this).parent().addClass("selected");
			$("#products-list").removeClass();
			$("#products-list").addClass($(this).attr("rel"));
			return false;
		});
		
		$(".js-hidden").hide();  // то что должно включаться Javascript'ом
		$(".js-visible").show(); // контроллер js, который переключает .js-hidden 
		
		$("div.faq dt").bind("click", function(){
			$(this).parent().toggleClass('active');
			$("#a"+$(this).attr("id")).toggle();

		});
		
		$("div.faq dt a").bind("click", function(){
			$(this).parent().click();

			return false;
		});

		$("#faq_control a").bind("click",function(){
			$("#faq_control a").toggle();
			$("div.faq dd").toggle();	

			return false;
		});
		
		$('a.update').live('click', function(e){
			randomFaq( $(this).attr('rel') );
			e.preventDefault();
		});
		
		$('#search-quick a').bind('click', function(e){
			$('#search-quick input.search-faq').attr('value', $(this).text());
			e.preventDefault();	
		});
		
	    $('a[href$="mp3"]').flash(
	        { src: '/-/plugins/jquery-flash/player.swf', height: 20, width: 450 },
	        { version: 7 },
	        function(htmlOptions) {
	            $this = $(this);
	            
	            htmlOptions.flashvars.file = $this.attr('href');
	            $this.before($.fn.flash.transform(htmlOptions));
	            
	            $this.hide();						
	        }
	    );

	    $('#video a[href$="flv"]').flash(
	        { src: '/-/plugins/jquery-flash/player.swf', height: 225, width: 400, allowfullscreen: true, flashvars: {skin: "/-/plugins/jquery-flash/modieus.swf", streamer: "lighttpd"} },
	        { version: 7 },
	        function(htmlOptions) {
	            $this = $(this);
	            
	            htmlOptions.flashvars.file = $this.attr('href');
	            $this.before($.fn.flash.transform(htmlOptions));
	            
	            $this.hide();						
	        }
	    );

	    $('a[href*="youtube.com"]').flash(
	        { src: '/-/plugins/jquery-flash/player.swf', height: 225, width: 400, allowfullscreen: true },
	        { version: 7 },
	        function(htmlOptions) {
	            $this = $(this);
	            
	            htmlOptions.flashvars.file = $this.attr('href');
	            $this.before($.fn.flash.transform(htmlOptions));
	            
	            $this.hide();						
	        }
	    );

	    $('a[href$="flv"]:visible').flash(
	        { src: '/-/plugins/jquery-flash/player.swf', height: 450, width: 600, allowfullscreen: true, flashvars: {skin:"/-/plugins/jquery-flash/modieus.swf", streamer: "lighttpd"} },
	        { version: 7 },
	        function(htmlOptions) {
	            $this = $(this);
	            
	            htmlOptions.flashvars.file = $this.attr('href');
	            $this.before($.fn.flash.transform(htmlOptions));
	            
	            $this.hide();						
	        }
	    );
		
		//сarouselPromo( $('ul li[rel=promo]') );
		$('img.play-pause').live('click', function(){
			if ( $(this).attr('rel') == 'pause' )
			{
				clearTimeout( promo_timeout );
				$(this).hide();
				$('img.play-pause[rel=play]').show();
			}
			else
			{
				сarouselPromo( $('ul li[rel=promo]'), true );
				$(this).hide();
				$('img.play-pause[rel=pause]').show();
			}			
		});
		$("#wrap-visual").css("height", $("#visual").css("height"));
	}
);

// ==================================================================
function find()
{
	var newsearch = $('#search').attr('value');

	if ( newsearch == '')
	{
		$('#search').focus();
		return false;
	}
	
	var url = '';
	var pagepattern = /(page\/\d+)/;
	var action = $('#searchform').attr('action');
	if ( pagepattern.test(action) )
	{
		action = replaceString(RegExp.$1, '', action);
	}
	
	$('#searchform').attr('action',action);

	return true;
}

function sendFeedback(e)
{
	$('div.message').remove();
	
    JsHttpRequest.query(
      '/ajax/feedback/send/',
      {
        'q': e
      },
      function(result, errors) {
      	if ( result['result'] )
      	{
      		$div = $('<div />').attr('class', 'message').html( result['result'] ).css('color','green').append('<br /><br />');
      		$('#feedback_form textarea').attr('value', '');
      	}
      	else
      	{
      		$div = $('<div />').attr('class', 'message').html( errors ).css('color','red').append('<br /><br />');
      	}
      	
      	$('#feedback_form').before( $div );
      },
      true
    );
    
    return false;
}

// ==================================================================
// ==================================================================
// ==================================================================

// -----------------------------------------------------------
document.onkeydown = function (e)
{
	if (!e)
	{
		e = window.event;
	}
	if (e.ctrlKey) //arrow navigation
	{
		var code = e.keyCode ? e.keyCode : (e.which ? e.which : 0);
		var arrow = code == 37 ? document.getElementById('prev_page') : (code == 39 ? document.getElementById('next_page') : 0);
		if (arrow)
		{
			location.href = arrow.href
		}
	}
}

function replaceString(oldS, newS, fullS) 
{
   if( fullS && fullS != '' )
   {
	   for (var i = 0; i < fullS.length; i++) 
	   {
	      if (fullS.substring(i, i + oldS.length) == oldS) {
	         fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
	      }
	   }
   	   return fullS;
   }
   return false;
}

function testKey(e,id)
{
	// Make sure to use event.charCode if available
	var key = (typeof e.charCode == 'undefined' ? e.keyCode : e.charCode);

	// Ignore special keys
	if (e.ctrlKey || e.altKey || key < 32)
		return true;

	key = String.fromCharCode(key);
	if (id)
	{
		var _str = document.getElementById(id).value;
		dot = /\./;
		if (dot.test(_str))
		{
			return /\d/.test(key);
		}
		else
		{
		return /[\d\.]/.test(key);     
		}
	}
	else
	{
		return /\d/.test(key);
	}
}

// -----------------------------------------------------------
function checkForm()
{
	for (i=0; i < arguments.length; i++)
	{
		if ( $('#'+arguments[i]).attr('value') == '')
		{
			$('#'+arguments[i]).addClass('warning');
			
			return false;
		}
	}
	
	return true;	
}

function registerForm()
{
	return true;
}

function loginForm()
{
	return true;
}

function passwordForm()
{
	return true;	
}

function profileForm()
{
	return true;
}

function forgetForm()
{
	return true;
}

function orderdetailsForm()
{
	return true;
}

function finishForm()
{
	return true;
}

function activateForm()
{
	return true;
}

function getForm( form, handler, referer, e)
{
    JsHttpRequest.query(
      '/ajax/'+handler+'/form/',
      {
        'form': form,
        'referer': referer
      },
      function(result, errors) {
      	$('#signin').empty();
      	$('#'+e.id).overlaySynthetic(function()	{
      		$("table.sign-form input:first").focus();
      	});
      	
      	$('#signin').append(result['result']);
      },
      true
    );
}

function getBlock( block, handler, referer, e )
{
    JsHttpRequest.query(
      '/ajax/'+handler+'/byname/',
      {
        'block': block,
        'referer': referer
      },
      function(result, errors) {
      	if ( result['result'].length > 0 )
      	{
      		$('#signin').empty();
      		$('#'+e.id).overlaySynthetic();

	      	$('#signin').append(result['result']);
      	}
      },
      true
    );
}

function randomFaq( node_id )
{
    JsHttpRequest.query(
      '/ajax/faq/random/',
      {
      	'node_id': node_id
      },
      function(result, errors) {
      	$('#question').empty().html( result['result'] );
      },
      true
    );	
}

function reloadPromo( title )
{
    JsHttpRequest.query(
      '/ajax/catalogue/promo/',
      {
      	'title': title
      },
      function(result, errors) {
      	$('div.shadow').fadeTo("slow", 0, function(){
			$('div.shadow').empty().html( result['result'] ).fadeTo("slow", 1);
		});
      }
    );
    
    return false;
}

function showVideo( videofile, videotitle, e )
{
    $('<a href="'+videofile+'" />').flash(
        { src: '/-/plugins/jquery-flash/player.swf', height: 300, width: 450, allowfullscreen: true, flashvars: {skin:"/-/plugins/jquery-flash/modieus.swf", streamer: "lighttpd", autostart: true} },
        { version: 7 },
        function(htmlOptions) {
            $this = $(this);
            
            htmlOptions.flashvars.file = $this.attr('href');
            $code = $.fn.flash.transform(htmlOptions);
        }
    );
	
	$('#signin').empty();
	$('#'+e.id).overlaySynthetic({
		'onLoad': function(){
				replaceFlash('hide');
			},
		'onClose': function(){
			replaceFlash('show');
		}
	});

  	$('#signin').append('<h1>Видео</h1>').append( $code ).append('<br /><strong>'+videotitle+'</strong>');
		
	return false;
}

function replaceFlash( how )
{
	if ( how == 'hide' )
	{
		$('#flow embed:visible').each(function(){
			$width = $(this).attr('width');
			$height = $(this).attr('height');
			
			$(this).hide().before( 
						$('<img />').attr('src', '/-/img/'+$width+'.png')
									.attr('width',$width)
									.attr('height', $height)
									.attr('rel', 'flashreplace')
								)
		})
	}
	else
	{
		$('img[rel=flashreplace]').remove();
		$('#flow embed:hidden').each(function(){
			$(this).show();
		});
	}
}
