var promo_timeout;

function constructLightBox()
{
	$("a[rel*=lightbox]").fancybox({
		'imageScale': false,
		'centerOnScroll': false
	});
}

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;
		}
	})
}

function trackView( u )
{
	pageTracker._trackPageview(u);
}

$(document).ready(
	function()
	{
		constructLightBox();
		
		$("a.external").each(function(){
			$(this).attr("href",$(this).attr("title"));
			$(this).removeAttr("title");
			$(this).removeAttr("class");
		});
		
		$(".js-hidden").hide();  // то что должно включаться Javascript'ом
		$(".js-visible").show(); // контроллер js, который переключает .js-hidden 
		
		$("#term-base li").bind("click", function(e){
			$("#a"+$(this).attr("id")).toggle();
			
			$(this).toggleClass("opened");
			
			trackView($(this).attr('href'));
		});
		
		$("#term-base h3 a").bind("click", function(){
			$(this).parent().parent().click();
			return false;
		});

		$("#faq_control a").bind("click",function(){
			$("#term-base li p").toggle();
			
			trackView($(this).attr('href'));	
			return false;
		});
		
		$('a.update').live('click', function(e){
			randomFaq( $(this).attr('rel') );
			
			trackView($(this).attr('href'));
			
			e.preventDefault();
		});

		$("#feedback_form input[type=submit]").attr("disabled", "disabled");
		$("#feedback_form textarea").bind("keyup",function(){
			if( $(this).val().length > 0 )
				$("#feedback_form input[type=submit]").removeAttr("disabled");
			else
				$("#feedback_form input[type=submit]").attr("disabled", "disabled");
		});

	    $('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();						
	        }
	    );

	    $('a[href$="flv"]').flash(
	        { src: '/-/plugins/jquery-flash/player.swf', height: 370, width: 450, allowfullscreen: true },
	        { 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: 370, width: 450, allowfullscreen: true },
	        { version: 7 },
	        function(htmlOptions) {
	            $this = $(this);
	            
	            htmlOptions.flashvars.file = $this.attr('href');
	            $this.before($.fn.flash.transform(htmlOptions));
	            
	            $this.hide();						
	        }
	    );
	    
	    $('div.hide-menu').bind('click', function(e){
	    	if ( $('#user-menu').is(':visible') )
	    	{
	    		$('#user-menu').slideUp();
	    		$.cookie('basket', 'hidden', {'path': '/'});
	    	}
	    	else
	    	{
	    		$('#user-menu').slideDown();
	    		$.cookie('basket', 'visible', {'path': '/'});
	    	}
    		$(this).toggleClass('show-menu');
	    	e.preventDefault();
	    });
	    
	    $('#select-material').bind('click', function(e){
	    	$('ul.types').slideToggle();
	    	$('span.type-description').slideToggle();
	    	trackView('/interface/select-material/');
	    	e.preventDefault();
	    });

	    $('#select-size').bind('click', function(e){
			$('#choose-size div.container').slideToggle();
			trackView('/interface/select-size/');	    	
	    	e.preventDefault();
	    });
	    
		$('a.material-select').bind('click', function(e){
			$('a.material-select').parent().removeClass("active");
			$(this).parent().addClass('active');
			
			$('div.type span').empty().text( $(this).text() );
			
			$material = $(this).attr('rel');
			$price = $('#material'+$material+' .'+$.cookie('size')).text();
			
			$('div.bl div.price span').empty().html( $price );
			
			$('#discount').empty().html(Math.round(parseFloat($price)*0.1));

			trackView('/interface/select-material/');
			
			e.preventDefault();
		});
		
		$('a.size-select').bind('click', function(e){
			trackView('/interface/select-size/');
			sizeSelect( $(this), e );
		});
		
	    $('a.selected-size').bind('click', function(e){
	    	$active = $(this).attr('rel');
	    	$sizes = $.makeArray( $('div.container ul li a').not('.disabled') );
	    	for(var i=0; i<$sizes.length; i++)
	    	{
	    		if ( $sizes[i].rel == $active )
	    		{
	    			if ( (i+1) == $sizes.length )
	    			{
	    				$next = $sizes[0].rel; 
	    			}
	    			else
	    			{
	    				$next = $sizes[i+1].rel;
	    			}
	    			$('a.size-select[rel='+$next+']').click();
	    		}
	    	}
			trackView('/interface/select-material/');
	    	e.preventDefault();
	    })

		$("div.container ul li.active a").click();

		$('img.hide').bind('click', function(){
			$class = $(this).attr('rel');
			
			if ( $('div.'+$class).is(":visible") )
			{
				$('div.'+$class).hide();
			}
			else
			{
				$('div.'+$class).show();
			}
			trackView('/interface/show-image/');
		});
		
		$('div.select-box img').bind('click', function(){
			$('ul.select-list').slideToggle();
			trackView('/interface/select-size-box/');
		});
		
		$('div.select-ok div.left').bind('click', function(){
			$('ul.select-list').slideUp();
		});
		
		$('ul.select-list li a').bind('click', function(e){
			$('div.active-size span').empty().html( $(this).text() );
			$.cookie('size', $(this).attr('rel'), {'path': '/'});
			$('ul.select-list').slideUp();
			trackView('/interface/select-size/');
			e.preventDefault();
		});
		
		$('img.play-pause').live('click', function(){
			
			trackView('/interface/slide-show/');
			
			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();
			}			
		});
		
		$('a.basket').bind('click', function(e){
			basket('basket', 'show')
			
			trackView('/interface/show-basket/');
			
			e.preventDefault();
		});
		
		
		$("#regions div").hide();
		
		$("#regions h2").each(function(i){
			$(this).wrapInner("<span></span>");
		});
		
		$("#regions h2").addClass("js-link");
		
		$("#regions h2").bind("click", function(){
			$("#regions div").hide();
			$("#"+$(this).attr("id")+"-region").show();
			$("#regions h2").addClass("js-link");
			$(this).removeClass("js-link");
			trackView('/interface/select-office/');
		});
		
		$("#imgmap area").bind("click", function(){
			$($(this).attr("href")).click();
			
			trackView('/interface/select-office/');			
		});
	}
);

// ==================================================================
// ==================================================================
// ==================================================================
// ==================================================================

function sizeSelect(o, e)
{
	if ( o.hasClass('disabled') )
	{
		e.preventDefault();
		return false;
	}
	
	$('a.size-select').parent().removeClass("active");
	o.parent().addClass('active');
	
	$.cookie('size', o.attr('rel'), {'path': '/'});
	$('#size-value').empty().html( o.text() );
	$('a.selected-size').empty().html( o.text() ).attr('rel', o.attr('rel'));

	$size = o.attr('rel').split('x');
	$('#size-front').removeClass().addClass('w'+$size[0]);
	$('div.horizontal div').removeClass().addClass('slider h'+$size[0])
	$('div.vertical div').removeClass().addClass('slider v'+$size[1])
	
	$('div.vertical span').empty().text( $size[1] );
	$('div.horizontal span').empty().text( $size[0] );
	
	$('ul.types li[class=active] a.material-select').click();
	
	e.preventDefault();
}

function showRatingStars()
{
	$("div.rating").each(function (i) {
		$('#'+$(this).attr("id")).rating('/ajax/catalogue/rate/',{maxvalue:5, curvalue:$(this).attr("title")});
    });
}

function getInventory( a )
{
	var viewtext = $.cookie("view-text");
	
	if ( viewtext == null )
	{
		viewtext = true;
	}

	$('#inventory').empty();
	$('#inventory').addClass("ajax-loading");
	
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/catalogue/property/',
      {
        'property_name': a,
        'viewtext': viewtext
      },
      function(result, errors) {
      	insertImage('eloading','none');
		$('#inventory').removeClass("ajax-loading");
      	$('#inventory').append(result['result']);
		showRatingStars();
		setInventoryAction();
      },
      true
    );
}

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 basket(node_id, type, material, size, price)
{
	trackView('/interface/basket/');
	if ( material === undefined )
	{
		material = $('ul.types li.active a').text();
	}
	if ( size === undefined )
	{
		size = $('#choose-size div ul li.active a').text();
	}
	if ( price === undefined )
	{
		price = $('div.bl div.price span').text();
	}
	
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/shop/add/',
      {
        'node_id': node_id,
        'type': type,
        'i-material': material,
        'i-size': size,
        'i-price': price,
        'qty': 1
      },
      function(result, errors) {
      	insertImage('eloading','none');
      	
      	$('div.close').click();
      	
		$('#overlay').empty();
		$('a.basket').overlaySynthetic({'zIndex': 15});
		$('#overlay').append( result['result'] );
      },
      true
    );
    
	return false;
}

function changeQty(node_id, symbol, total)
{
	var qty = $('#inv-'+node_id).attr('value');
	
	if ( symbol == '+' )
	{
		$('#inv-'+node_id).attr('value', ( Number(qty)+1 ) );
		$("#tr-"+node_id).css("opacity", 1);
	}
	else
	{
		if ( Number(qty) > 0 )
		{
			$('#inv-'+node_id).attr('value', ( Number(qty)-1 ) );
			
			if ( $('#inv-'+node_id).attr('value') == 0 )
			{
				$("#tr-"+node_id).css("opacity", .3);
			} 
		}
	}
	
	if ( total )
	{
		recountBasket();
	}
	
	return false;
}

function recountBasket()
{
	new Number();
	var total = 0.0;
	
	var prices = $.makeArray( $('table.order span.item-price') );
	var qty = $.makeArray( $('input[id^=inv]') );
	
	if ( qty.length != 0 && prices.length != 0 && qty.length == prices.length )
	{ 
		for( var i=0; i < prices.length; i++ )
		{
			var price = parseFloat( replaceString(',', '.', prices[i].innerHTML) );
			var q = parseFloat( replaceString(',', '.', qty[i].value) );
			
			if ( isNaN( q ) )
			{
				q = 0;
			}
			
			var sum = Math.round(price * q * 100)/100;
			
			$('#'+qty[i].id+'-sum em').text( replaceString('.', ',', sum.toString()) );
			
			total = total + sum;
		}
		
		total = Math.round(total * 100)/100;
		
		$('#basket-total em').text( replaceString('.', ',', total.toString()) );
	}
}

function deleteRow( node_id, material, size, row )
{
	trackView('/interface/basket-delete/');
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/shop/add/',
      {
        'node_id': node_id,
        'type': 'remove',
        'i-material': material,
        'i-size': size      
      },
      function(result, errors) {
			insertImage('eloading','none');
			$('#tr-'+node_id+'-'+row).fadeOut("slow", function()
			{
				$('#tr-'+node_id+'-'+row).remove();
				recountBasket();
				if ( $('tr[id*=tr]').length == 0 )
				{
					$('#basket_total').remove();
					
					$('#noorder').show();
					$('#order_button').attr('disabled', 'disabled');
				}
			});
      },
      true
    );
    
	return false;	
}

function checkQty( node_id )
{
	trackView('/interface/basket-quantity/');
	var qty = $('#inv-'+node_id).attr('value');
	
	if ( qty == 0 )
	{
		$("#tr-"+node_id).css("opacity", .3);
	}
	
	if ( qty > 0 )
	{
		$("#tr-"+node_id).css("opacity", 1);
	}
	recountBasket();
}

// ==================================================================

function sendResume(e)
{
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/vacancies/upload_resume/',
      {
        'q': e,
        'node_id': $('#node_id').attr('value')
      },
      function(result, errors) {
      	insertImage('eloading','none');
      	$('#wrapper').empty();
        $('#wrapper').append(result['result']);
      }
    );
}

function sendFeedback(e)
{
	trackView('/interface/send-feedback/');
	$('div.message').remove();
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/feedback/send/',
      {
        'q': e
      },
      function(result, errors) {
      	insertImage('eloading','none');
      	if ( result['result'] )
      	{
      		$div = $('<div />').attr('class', 'message').html( result['result'] ).css('color','green').append('<br /><br />');
      		$('#feedback_form input[type!=submit], textarea').attr('value', '');
      	}
      	else
      	{
      		$div = $('<div />').attr('class', 'message').html( errors ).css('color','red').append('<br /><br />');
      	}
      	
      	$('#feedback_form table').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 insertImage(area,display)
{
    document.getElementById(area).style.left = screen.width / 2 + 'px';
    document.getElementById(area).style.top = (screen.height / 2) + document.documentElement.scrollTop - 200 + 'px';    
    document.getElementById(area).style.display = display;
}

// -----------------------------------------------------------
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)
{
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/'+handler+'/form/',
      {
        'form': form,
        'referer': referer
      },
      function(result, errors) {
      	insertImage('eloading','none');
		$('#overlay').empty();
		$('#'+e.id).overlaySynthetic({'zIndex': 15});
		$('#overlay').append( result['result'] );
      },
      true
    );
}

function getBlock( block, handler, referer, e )
{
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/'+handler+'/byname/',
      {
        'block': block,
        'referer': referer
      },
      function(result, errors) {
      	insertImage('eloading','none');
      	if ( result['result'].length > 0 )
      	{
      		$('#'+e.id).overlaySynthetic();
			
	      	$('#signin form').remove();			
	      	$('#signin .form').remove();
	      	$('#signin div.byname').remove();

	      	$('#signin').append(result['result']);
      	}
      },
      true
    );
}

function randomFaq( node_id )
{
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/faq/random/',
      {
      	'node_id': node_id
      },
      function(result, errors) {
      	insertImage('eloading','none');
      	$('#faq-block').empty().html( result['result'] );
      },
      true
    );	
}

function reloadPromo( title )
{
	trackView('/interface/promo/');
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/catalogue/promo/',
      {
      	'title': title
      },
      function(result, errors) {
      	insertImage('eloading','none');
      	$rel = $('div.cols').attr('rel');
		$('div.promo-item').fadeOut('slow', function(){
	      	$('div.cols').removeClass( $rel )
	      				 .addClass( result['promo_class'] )
	      				 .attr( 'rel',result['promo_class'] );
	      	
	      	$('div.promo-item').empty().html( result['result'] ).fadeIn('slow');
		});
      }
    );
    
    return false;
}

function compareItem(node_id, group, action)
{	
	trackView('/interface/compare/');
	if( action != 'remove' )
	{
		action = 'add';
		if( $("a.tr strong").is(":visible") )
		{
			return true;
		}
	}
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/catalogue/compare/',
      {
      	'node_id': node_id,
      	'group': group,
		'action' : action
      },
      function(result, errors) {
      	insertImage('eloading','none');
      	
	  	if ( $("a.tr span").is(":visible") )
		{
			$("a.tr span").hide();
			$("a.tr strong").show();
		}		
		if( result['result'] == 'removed')
		{
			window.location.href = '/catalog/compare/';
		}
		else
		{
	      	$('#user-menu ul li a.compare span em').empty().text( result['result'] );
	      	
	      	$('#user-menu ul li a.compare').removeClass('nothing-compare');
		}
      }
    );
    
	return false;
}

function getMaterials( material )
{
	trackView('/interface/get-materials/');
	insertImage('eloading','block');
    JsHttpRequest.query(
      '/ajax/gallery/materials/',
      {
      	'material': material
      },
      function(result, errors) {
      	insertImage('eloading','none');
      	$('span.type-description').empty().html( result['result'] );
      	constructLightBox();
      }
    );
    
    return false;
}
	
function setPrintCSS(isPrint) 
{
	trackView('/interface/print/');
	if (document.getElementsByTagName)
	  x = document.getElementsByTagName('link');
	else if (document.all)
	  x = document.all.tags('link');
	else
	{
	  alert('Простите, этот скрипт не работает в вашем броузере');
	  return;
	}
	for (var i=0;i<x.length;i++) {
	  if(x[i].title == 'printview'){x[i].disabled = !isPrint;}
	  if(x[i].title == 'screenview'){x[i].disabled = isPrint;}
	}
}