function recalculate() {
  var sum_all = 0;
    $('#calculate :checkbox').each(
      function(){
        // внутри функции this указывает на текущий DOM-элемент
        if (this.checked) {
          sum_all += parseFloat(this.value);
          $('#tr_'+this.id).css({'backgroundColor' : '#ABD1ED'});
        } else {
          $('#tr_'+this.id).css({'backgroundColor' : ''});
        }
      }
     );
    sum_all = sum_all.toFixed(2);
   $('#sum_all').text(sum_all);
}
function recalculate_brief() {
  var in_textarea = '';
    $('#calculate :checkbox').each(
      function(){
        // внутри функции this указывает на текущий DOM-элемент
        if (this.checked) {
          in_textarea = in_textarea + document.getElementById('text_'+this.id).value+'\n';
          $('#tr_'+this.id).css({'backgroundColor' : '#ABD1ED'});
        } else {
          $('#tr_'+this.id).css({'backgroundColor' : ''});
        }
      }
     );

   $('#body').text(in_textarea);
}
function set_package (values) {
  var price_array = values.split(',');
    $('#calculate :checkbox').each(
      function(){
        if (in_array(this.id,price_array)) {
            $('#'+this.id).attr('checked' , 'checked');
        } else {
            $('#'+this.id).attr('checked' , '');
        }
      }
     );
  recalculate ();
}

function set_package_brief (values) {
  var price_array = values.split(',');
    $('#calculate :checkbox').each(
      function(){
        if (in_array(this.id,price_array)) {
            $('#'+this.id).attr('checked' , 'checked');
        } else {
            $('#'+this.id).attr('checked' , '');
        }
      }
     );
  recalculate_brief ();
}
function change_currency (elem) {
	var course = elem.value;
	if (course == '1.00') {
		$('#currency_name').attr('value','у.е.');
	}	else {
		$('#currency_name').attr('value','грн.');
	}
    $('#solution :checkbox,input:radio').each(
		function(){
			var tmp_id = this.id.split('_');
			var type = tmp_id[0]; 
			var id = tmp_id[1]; 
			var price = document.getElementById(type+'_hidden_price_'+id).value*course;
			price = (price).toFixed(2);
			document.getElementById(type+'_span_price_'+id).innerHTML = price;
			document.getElementById(type+'_price_'+id).value = price;

		}
    );
    recalculate_solution();  
}
function recalculate_solution() {
	var sum_1 = 0;
	var sum_2 = 0;
	var sum_3 = 0;
	var sum_all = 0;
	$('#solution :checkbox,input:radio').each(
		function(){
			var tmp_id = this.id.split('_');
			var type = tmp_id[0]; 
			var id = tmp_id[1];
			var price = document.getElementById(type+'_price_'+id).value;

			if ($('#'+this.id).attr('alt') != '') {
				var dependence_tmp = $('#'+this.id).attr('alt');
				var dependence = dependence_tmp.split('|');
				if ($('#'+type+'_'+dependence[1]).attr('checked') == true) {
					$('#'+type+'_'+dependence[0]).attr('checked',true);
					//сносим кол-во
					$('#'+type+'_count_'+dependence[0]).attr('value',$('#'+type+'_count_'+dependence[1]).attr('value'));
				} else {
					$('#'+type+'_'+dependence[0]).attr('checked',false);
					$('#'+type+'_count_'+dependence[0]).attr('value',1);
				}
			}
			if (this.checked) {
				$('#tr_'+id).addClass('selected');
				//суммируем сумму каждой строки
				var count = document.getElementById(type+'_count_'+id).value;
				if (count < 1 || count == '' || isNaN(count)) {
					count = 1;
					document.getElementById(type+'_count_'+id).value = 1;
				}
				var summa_row =  price*count;
				document.getElementById(type+'_summa_'+id).innerHTML = summa_row.toFixed(2);

			} else {
				$('#tr_'+id).removeClass('selected');
				var summa_row = 0;
				document.getElementById(type+'_summa_'+id).innerHTML = summa_row.toFixed(2);
			}
			//суммируем типы и общую сумму
			if (type == '1') {
				sum_1 += summa_row;
			}			
			if (type == '2') {
				sum_2 += summa_row;
			}
			if (type == '3') {
				sum_3 += summa_row;
			}
			sum_all += summa_row;				
		}
	);
	document.getElementById('1_summa_all').innerHTML = sum_1.toFixed(2);
	document.getElementById('2_summa_all').innerHTML = sum_2.toFixed(2);
	document.getElementById('3_summa_all').innerHTML = sum_3.toFixed(2);	
	document.getElementById('summa_all').innerHTML = sum_all.toFixed(2)+' '+$('#currency_name').attr('value');

}
function set_image (elem) {
	//alert($(elem).parent().prev().attr("src"));
	var img = $(elem).parent().prev();
	var src = $(elem).attr("href");
	
	/*Ищем id проекта*/
	var tmp = src.split('/');
	var tmp2 = tmp[tmp.length-1].split('-');
	var project = tmp2[0];
	/*Ищем id раздела*/
	tmp = $(elem).parent().attr("id");
	tmp2 = tmp.split("_");
	var category = tmp2[2];	
	//alert(category+"-"+project);
	/*Получаем данные*/
	var a_text = $("#name-"+category+"-"+project).val(); 
	var a_url = "/proekt/"+$("#name_url-"+category+"-"+project).val(); 
	var specification = $("#specification-"+category+"-"+project).val(); 

	
	var current = $(elem).attr("class");
	if (current == ""){
		$(elem).addClass("current");
		$(elem).siblings().removeClass("current");				
		$(img).animate({'opacity':'hide'},300,function(){//скрыли		
			$(img).attr("src",src);
			$(img).animate({'opacity':'show'},300,function(){
				$(elem).siblings().removeClass("current");
			});
		});
		/*проявляем скрытые данные*/
		$("#portfolio_"+category).find("label>a").animate({'opacity':'hide'},300,function(){//скрыли		
			$("#portfolio_"+category).find("label>a").text(a_text).attr("href",a_url);
			$("#portfolio_"+category).find("label>a").animate({'opacity':'show'},300);
		});
		$("#specification_"+category).animate({'opacity':'hide'},300,function(){//скрыли		
			$("#specification_"+category).find("div").html(specification);
			$("#specification_"+category).animate({'opacity':'show'},300);
		});
	}	
}

var timer_surfacing_run;
function surfacing_run (param,time,html) {//вывод данных в информ. окно
	if (param) {
		if (html && html !='') {
			if ($('#surfacing').css('position') == 'absolute'){
				var screen_width = $(window).width();
				var screen_height = $(window).height();
				var scroll =getScrollY();
				var left = screen_width/2 - 250/2;
				var top = screen_height/2 - 250/2 + scroll;

				$('#surfacing').css({
					'top'		:	top+'px',
					'left'		:	left+'px'
				});
			}
			$('#surfacing').html(html).css('display','block');

			if (!time && time != 0) {
				time = 5000;
			}
			if (time != 0) {
				clearTimeout(timer_surfacing_run);
				timer_surfacing_run=window.setTimeout('surfacing_run(false)',time);
			}
		}


	} else {
		$('#surfacing').empty().css('display','none');
	}
}
function info_in_surfacing (info,time,close) {
	if (info != '') {
		surfacing_run(true,time,'<div>'+info+'</div>');
	}
	if (close){
		$("#surfacing").attr("title","Убрать").die().live("click",function(){
			$("#surfacing").fadeOut(200);
		});
	}
}
 function getScrollY() {
    var scrollY = 0;
	if (typeof window.pageYOffset == "number") {
			scrollY = window.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
			scrollY = document.documentElement.scrollTop;
	}  else if (document.body && document.body.scrollTop) {
			scrollY = document.body.scrollTop;
	} else if (window.scrollY) {
			scrollY = window.scrollY;
	}
	return scrollY;
}
function zoom(elem) {
	
	var pos = $(elem).offset();
	
	$("#zoom").css({
		"top":(pos.top+10),
		"left":(pos.left+10)
	});
	$("#zoom").fadeIn(100,function(){
		$(elem).unbind().bind("mouseout",function(){
			zoom_out($(elem));
		});			
	});
}
function zoom_out(elem) {
	$("#zoom").fadeOut(100,function(){
		$(elem).unbind().bind("mouseover",function(){
			zoom($(elem));
		});		
	});
	
}
function ajax_run (param,text) {//вывод индикатора работы ajax
	/*if (param) {
		if (typeof(text) == "undefined"){
			var text = "работаю...";
		}
		if (!document.getElementById("ajax_run")){
			$('<div id = "ajax_run">'+text+'</div>').appendTo('body');
		}
	} else {
		$('#ajax_run').remove();
	}*/
}
function orig_screen(a_obj) {

	ajax_action(true);	
	var screen_img = $(a_obj).attr("href");
	var title = "Закрыть";
	var screen_width = $(window).width();
	var screen_height = $(window).height();

	var scroll = getScrollY();

	var top = ((screen_height - 21)/2)+scroll;
	var left = (screen_width - 42)/2;

	$.post("/json/orig_screen",{
		in_img : screen_img,
		in_width : screen_width,
		in_height : screen_height,
		in_scroll : scroll
		},function(data){

			if (data != ""){
				var img = data;
				if (document.getElementById("orig_screen")) {
					$("#orig_screen").fadeOut(500,function(){
						$("#orig_screen").empty().append("<div class=zoom_close><a href=# onclick='return false' title='Закрыть'>&nbsp;</a></div>");						
						$("#orig_screen").append(img[0]).css({
							width	:	img[1]+"px",
							height	:	img[2]+"px",
							top		:	img[3]+"px",
							left	:	img[4]+"px"
						}).fadeIn(500);					
					});
				} else {
					$("<div id =orig_screen><div class=zoom_close><a href=# onclick='return false' title='Закрыть'>&nbsp;</a></div>").appendTo("body");
					$("#orig_screen").live("click",function(){
						$("#orig_screen").fadeOut(500);
						return false;
					});
					$("#orig_screen").append(img[0]).css({
						width	:	img[1]+"px",
						height	:	img[2]+"px",
						top		:	img[3]+"px",
						left	:	img[4]+"px"
					}).fadeIn(500);
				}
				ajax_action(false);
			}
		}
	);
}
 function ajax_action (param,image) {
     if (param) {
		if (!image || image == '') {
			image = '<img src="/global/image/main/loading26.gif">';
		} else {
          image = '<img src="/local/image/main/'+image+'">';
        }
      if (!document.getElementById('ajax_action')) {
          var screen_width = $(window).width();
          var screen_height = $(window).height();
          var scroll =getScrollY();
          var top = ((screen_height - 21)/2)+scroll;
          var left = (screen_width - 42)/2;
          $('<div id = "ajax_action" " title = "Работаем">'+image+'</div>').appendTo('body');
            $('#ajax_action').css({
                'width' : '42px',
                'height' : '42px',
                'top' : top+'px',
                'left' : left+'px',
                'position': 'absolute',
                'z-index' : '4'
            });
      }
     } else {
         if (document.getElementById('ajax_action')) {
            $('#ajax_action').remove();
         }
     }
}
function posting (rnd, rules) {
    ajax_run(true);
	if (!document.getElementById("surfacing")) {
		$('<div id = "surfacing"></div>').appendTo('body');		
	}    
    var elem_string = '';
    $('#'+rnd+' :input').each(
      function(){
        // внутри функции this указывает на текущий DOM-элемент
        if (this.type == 'select-one' || this.type == 'textarea' || this.type == 'select-multiple') {//хак для селекта и текстареи
          this.alt = $(this).attr('alt');
        }
        var tmp_value =$(this).val();
        if (this.type == 'checkbox') {//хак для чекбокса
          tmp_value = '%/&&/%';
        }
        elem_string += this.name+'¤'+tmp_value+'¤'+this.checked+'¤'+this.alt+'§';
      }
     );
     
    $.post(
		'/ajax/posting',{
			'in_elem' : elem_string ,
			'in_rules' : rules,
			'in_rnd' : rnd
		},function(data){
			$("#surfacing").empty().html(data);		
		}
	);
}

function TranslitOnPage() {
	Translit.mapSpecials("«»'&?<> ","-");
	Translit.unmapSpecials("");
	document.getElementById("out_value").innerHTML = 
		document.getElementById("Ua2En").checked ? Translit.Ua2En(document.getElementById("in_value").value) : 
		Translit.Ru2En(document.getElementById("in_value").value);
};

