function hsv2rgb (h, s, v)
{
	h /= 360;
	s /= 100;
	v /= 100;
	var m2 = v <= 0.5 ? v * (s + 1) : v + s - v * s;
	var m1 = v * 2 - m2;
    var r = norm2hex (hue2rgb (m1, m2, h + 1/3));
    var g = norm2hex (hue2rgb (m1, m2, h));
    var b = norm2hex (hue2rgb (m1, m2, h - 1/3));
    return r + '' + g + '' + b;
}
function hue2rgb (m1, m2, h)
{
	if (h < 0) h = h + 1;
	if (h > 1) h = h - 1;
	if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
	if (h * 2 < 1) return m2;
	if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;
	return m1;
} 
function norm2hex (value)
{
	return dec2hex (Math.floor (255 * value));
}
function dec2hex (dec)
{
	var hexChars = "0123456789ABCDEF";
	var a = dec % 16;
	var b = (dec - a) / 16;
	hex = '' + hexChars.charAt (b) + hexChars.charAt (a);
	return hex;
}

var logo_color=0;
function change_logo_color()
{
	h = Math.floor (360 * Math.random());
	s = 30 + Math.floor (70 * Math.random());
	v = 90 + Math.floor (5 * Math.random());
	logo_color='#'+hsv2rgb ( h, s,v);
	$('#logo').css('background-color',	logo_color);
}


function onLoad()

{
	
	
	 $('input[type="button"], input[type="submit"]').each(function(i){
            obj=$(this);
			
			var className = obj.attr('class');
			className=(className===undefined)?'':' '+className;
			
			
			var id=obj.attr('id');
			id=(id===undefined)?'':id;
			
			var name=obj.attr('name');
			name=(name===undefined)?'':name;
			
			if (id=='' && name!='') id='btn_'+name;
			else if (name=='') id='btn_'+i;
			
			if (id=='search_btn') rel='search';
			else rel='';
			
			var value=obj.val();
			
			var disabled=obj.attr('disabled');
			
			var title=obj.attr('title');
			title=(title === undefined)?value:title;
			
			var type=obj.attr('type');
			
			if (type=='submit') submitClass=' class="submit_btn" ';
			else submitClass='';
			if (disabled) obj.replaceWith('<div class="button_disabled'+className+'" id="'+id+'" title="'+title+'"><a '+((rel!='')?'rel="'+rel+'"':'')+'>'+value+'</a></div>');
            else 
			{
				obj.replaceWith('<div class="button'+className+'" id="'+id+'" title="'+title+'"><a href="#" '+((rel!='')?'rel="'+rel+'"':'')+submitClass+'>'+value+'</a></div>');
				//if ( type=='submit') $('#'+id).children('a').live('click',function() {$(this).parents('form').submit();return false;});
			}
			
        });
$('a.submit_btn').bind('click',function() {$(this).parents('form').submit();return false;});	



$("form div.category_div, #dialog_content").each(function (i){
												var max_width=0;
	$(this).find("label:not(.right)").each(function(i) {if ($(this).width()>max_width) {max_width=$(this).width();} });		
	
	$(this).find("label:not(.right)").each(function(i) {$(this).css("margin-left",max_width-$(this).width());});	
	});
	
}


$(function()
{
	window.___gcfg = {lang: 'ru'};
$('#gplus').html("<g:plusone annotation='none'></g:plusone>");
 var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
	//$('#gplus div').hide().fadeIn('slow');
	function check_gplus()
	{
		
		$gplusDiv=$('#gplus div');
		if ($gplusDiv.size()==0) setTimeout(check_gplus,100);
		else {$gplusDiv.hide().fadeIn(800);	}
		
	}
	check_gplus();
	
	$.openDialog = function(options){

  var options = jQuery.extend({
   'backgroundColor':'#FFF',
   'fadeInTime':500,
   'fadeOutTime':500,
   'width':800,
  	'opacity':'0.9',
	'loadUrl':'',
	'submitUrl':'',
	'data':{},
	'marginTop':10,
	'success':function(close_func){close_func();location.reload();},
	'error':function(close_func){$('#main_dialog_container').html('<div class="dialog_message">Возникла ошибка</div>');
			setTimeout(function(){close_func();},2000);},
  },options);

function closeDialog(func)
{
	$('#dialog_container, #dialog_div').animate({opacity:0},options.fadeOutTime,function()
	{
		$(this).remove();
		if (typeof func=='function') func();
	});
}

$.ajax({
    url: options.loadUrl,            
    dataType : "text", 
	type: 'GET',
	data:options.data,
	success: function (text) { 
	$('body').append('<div id="dialog_container"></div>').append('<div id="dialog_div"><div id="main_dialog_container"></div><iframe name="openDialog_iframe"></iframe></div>');
	
	var main_dialog_container=$('#main_dialog_container');
	main_dialog_container.width(options.width).html(text).find('form').attr('target','openDialog_iframe');
	$('#dialog_div').fadeIn(options.fadeInTime).find('iframe').bind('load',function()
	{
		if (this.contentWindow.document.body.innerHTML!='')
		{
		if (this.contentWindow.document.body.innerHTML=='ok' )
		options.success(closeDialog);
		else options.error(closeDialog);
		}
	});
	
	
	var window_height=$(window).height();
	var main_dialog_container_height=main_dialog_container.height();
	var new_main_dialog_container_height=window_height-options.marginTop*2;
	//alert(main_dialog_container_height);alert(new_main_dialog_container_height);
	if (main_dialog_container_height<new_main_dialog_container_height) main_dialog_container.css('margin-top',(new_main_dialog_container_height-main_dialog_container_height)/2+options.marginTop);
	else 
	{
		main_dialog_container.css('margin-top',options.marginTop);
	
$('#dialog_content').height(new_main_dialog_container_height-main_dialog_container_height+$('#dialog_content').height());
	main_dialog_container.height(new_main_dialog_container_height);
	}
	
$('#dialog_container').css('background-color',options.backgroundColor).animate({opacity:options.opacity},options.fadeInTime);
$('.exit_btn, .exit_btn a').live('click',function()
{
	closeDialog();
	return false;
});
onLoad();
	}
});

};

	$('#btn_contact').click(function()
	{
		url=window.location.href;
		name=$('*[itemprop=name]').text();
	$.openDialog({
		'loadUrl':'/site/contact/',
		'data':{'url':url,'name':name},
		'success':function(close_func)
		{
			$('#main_dialog_container').fadeOut('slow',function(){
				$(this).html('<div class="dialog_message"><div>Ваш вопрос был принят.</div><div>В ближайшее время Вы получите ответ.</div></div>').fadeIn('slow');
			});
			setTimeout(function(){close_func();},2000);
			
		},
			'error':function(close_func)
		{
			$('#main_dialog_container').fadeOut('slow',function(){
				$(this).html('<div class="dialog_message"><div>При отправке вопроса возникла неизвестная ошибка.</div><div>Пожалуйста, попробуйте еще раз.</div></div>').fadeIn('slow');
			});
			setTimeout(function(){close_func();},4000);
			
		}
		
	});
	return false;	
		
	});
	
	
	$('#btn_order, .btn_order').click(function()
	{
		url=window.location.href;
		name=$('*[itemprop=name]').text();
	$.openDialog({
		'loadUrl':'/site/order/',
		'data':{'url':url,'name':name},
		'success':function(close_func)
		{
			$('#main_dialog_container').fadeOut('slow',function(){
				$(this).html('<div class="dialog_message"><div>Ваша заявка была принята.</div><div>В ближайшее время Вы получите ответ.</div></div>').fadeIn('slow');
			});
			setTimeout(function(){close_func();},2000);
			
		},
			'error':function(close_func)
		{
			$('#main_dialog_container').fadeOut('slow',function(){
				$(this).html('<div class="dialog_message"><div>При подаче заявки возникла неизвестная ошибка.</div><div>Пожалуйста, попробуйте еще раз.</div></div>').fadeIn('slow');
			});
			setTimeout(function(){close_func();},4000);
			
		}
		
	});
	return false;	
		
	});
	
	
		$("img.category_img").each(function () {


	if (!this.complete) $(this).bind('load',function () {change_margin(this);$(this).unbind('load');});
	else change_margin(this);


});

	$('#logo').css('background-color',	'#EEE');

$('#logo').bind('mouseover',function()

{

	change_logo_color();

});

$('#top_link').bind('click',function()
{
window.scroll(0,0);
return false;	
});

onLoad();



//$('#content_container').css('min-height',$(window).height()-$('header').outerHeight()-$('footer').outerHeight());

$share_container=$('#share_container');
if ($share_container.size()==1)
{
	t=encodeURIComponent($share_container.attr('data-title'));
	
	u=encodeURIComponent(location.href);
	ud=encodeURIComponent(location.href+"\r\n"+$('meta[name=description]').attr('content'));
	var hrefs=new Array('http://vk.com/share.php?url='+u+'&title='+t,'http://www.facebook.com/sharer.php?u='+u+'&t='+t,'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st._surl='+u+'&title='+t,'http://twitter.com/share?text='+t+'&url='+u,'http://www.livejournal.com/update.bml?event='+ud+'&subject='+t,'http://connect.mail.ru/share?url='+u+'&title='+t,'#');
	$share_container.children('a').each(function(i)
	{
		$(this).attr('href',hrefs[i]).attr('target','_blank');
		
	});
	$('#share_container a.share_fv').click(function(){return fav(this);});
	$('#share_container a.share_vk').click(function(){openWindow(this.href,554,500);return false;});
	$('#share_container a.share_fb').click(function(){openWindow(this.href,700,400);return false;});
	$('#share_container a.share_tw').click(function(){openWindow(this.href,550,340);return false;});
	$('#share_container a.share_ok').click(function(){openWindow(this.href,550,440);return false;});
	$('#share_container a.share_mr').click(function(){openWindow(this.href,554,500);return false;});
}

});

function change_margin(obj)
{
	var obj1=$(obj);
	$category_text=obj1.parent().children('div.category_text');
	
	$category_text.css('margin-left',obj1.width()+parseFloat(obj1.css('margin-right'))+parseFloat($category_text.css('margin-left')));
obj1.css('margin-right',0);
var height_img=obj1.height();
var height_text=$category_text.height();
//alert ('height_img '+height_img);
//alert ('height_text '+height_text);
if (height_img>height_text) $category_text.css('margin-top',(height_img-height_text)/2+parseFloat($category_text.css('margin-top'))+parseFloat(obj1.parent().children('h2,h3').css('margin-bottom')));
else obj1.css('margin-top',(height_text-height_img)/2+parseFloat(obj1.css('margin-top')));

};

function openWindow(url,width,height)
{
	var left=(screen.width-width)/2;
	var top=(screen.height-height)/2;
	window.open(url, 'social', 'scrollbars=0, resizable=1, menubar=0, left='+left+', top='+top+', width='+width+', height='+height+', toolbar=0, status=0');
}

	function fav(a){
		title=document.title;url=document.location;
		try{window.external.AddFavorite(url,title);}
		catch(e){try{window.sidebar.addPanel(title,url,"");}catch(e){if(typeof(opera)=="object"){a.rel="sidebar";a.title=title;a.url=url;return true;}else{alert('Нажмите Ctrl-D, чтобы добавить страницу в закладки');}}}
	
	return false;
	
	};

