function init_contact_button(button, url) {
	button.click(function(){
		var $checkboxes = $('.contact-item input.checkbox:checked');		
		if ($checkboxes.length == 0) {
			$.SaexPopup({
				message: 'Выберите хотя бы один контакт',
				buttons: [{
				    title: "Ok",
				    handler: function() {
				    	return true;				    
				    }
				}]			
			});			
			return false;
		}
		var array = '';
		$.each($checkboxes, function(i, item){
			var id = item.getAttribute('name').replace('id_', '');
			if (i == 0) {
				array += (id);
			} else {
				array += "," + (id);
			}
		});
		window.location.href = url + array;
		return false;
	});
}

function declination(num, expressions) {
    var result;
    var count = num % 100;    
    var result = '';
    if (count >= 5 && count <= 20) {
        result = expressions[2];
    } else {
        count = count % 10;
        if (count == 1) {
            result = expressions[0];
        } else if (count >= 2 && count <= 4) {
            result = expressions[1];
        } else {
            result = expressions[2];
        }
    }
    return result;
}

var need_mass_select_confirm_selected = true;
var need_mass_select_confirm_unselected = true;
//selected_count и unselected_count используется для подсчета 
//количества выделенных чекбоксов для того, чтобы вывести попап, не показывает 
//реального кол-ва выделенных
var selected_count = 0;
var unselected_count = 0;
var item_that_was_selected = '0';
var contacts_selected;
var contacts_price

$(function(){
	var $opaco = $("#opaco");
	//реальное кол-во выделенных контактов	
	if ($("#selected_contacts_count").size()>0)
		contacts_selected = parseInt($("#selected_contacts_count").text());
	else
		contacts_selected = 0;
	//цена выделенных контактов		
	if ($("#selected_contacts_price").size()>0)
		contacts_price = parseInt($("#selected_contacts_price").text());
	else
		contacts_price = 0;
	//можно конечно забирать их из базы, это сделано для скорости
	//при покупке контактов для получения кол-ва и стоимости выделенных
	//идет запрос в базу в любом случае
	init_contact_button(
		$(".contact-copy-button"),
		"/index.php?mod=contacts&cmd=copy&id="
	);
	init_contact_button(
		$(".contact-to-archive-button"),
		"/index.php?mod=contacts&cmd=toArchive&id="
	);
	init_contact_button(
		$(".contact-to-contacts-button"),
		"/index.php?mod=contacts&cmd=toContacts&id="
	);
		
	$('.buy-selected').live('click', function(){
		jQuery.ajax({
			url: '/index.php?mod=my_contacts',
			type:'GET',
			data: {cmd: 'getSelectedCountAndPrice',ajax:1},
			beforeSend: function() {$("#ico-loading").show();},
			success: function(data) {
				$("#ico-loading").hide();
				var message = "Вы покупаете "+data.count+" "+declination(data.count, ['контакт','контакта','контактов']);
				message+=" на сумму "+data.price+" "+declination(data.price, ['балл','балла','баллов'])+'?';				
				if (data.count > 0) {	
					$.SaexPopup({
						message: message,
						buttons: [{
						    title: "Да",
						    cssClass: 'buy_popup_ok buy_popup_all',
						    handler: function() {
						    	item_that_was_selected = '-1';
						    	return false;				    
						    }
						},
						{
							title: "Нет",							
							handler: function() {						
								return true;
							}
						}]
					});
				} else {
					$.SaexPopup({
						message: 'Выберите хотя бы один контакт',
						buttons: [{
						    title: "Ok",
						    handler: function() {
						    	return true;				    
						    }
						}]			
					});			
				}
			}		
		}); 
	});	

	$('.contact-item input.checkbox').live("change", function() {
		//hide notice with contacts' count and price		
		if ($(this).hasClass('noTrigger'))
			return;
		var id = $(this).attr('id');
		id = id.replace('cb_id_','');
		var action = ($(this).attr('checked')==true)?1:0;
		var cmd;
		if ($(this).hasClass('my_favorites'))
			cmd = 'selectAllFavorites';
		else if ($(this).hasClass('cb_catalogue'))
			cmd = 'selectAllCatalogue';
		else cmd = 'selectAllSearchResults';
		var f1 = (cmd=='selectAllFavorites')?'избранные ':'';
		var f2 = (cmd=='selectAllFavorites')?'избранных ':'';
		jQuery.ajax ({
			url: '/index.php?mod=my_contacts',
			type : 'GET',
			data: {cmd: 'setSelected', id: id, action:action, ajax:1}			
		});				
		if (!$(this).hasClass('noPopup')) {			
			var price = parseInt($(this).parent().parent().find('input[type=hidden]').val());			
			if (action == 1) {
				selected_count++;
				contacts_selected++;
				contacts_price += price;
			} else {
				unselected_count++;
				contacts_selected--;
				contacts_price -= price;
			}
			if (contacts_selected<=0)
				$('.notice_green').hide();
			else {
				var notice_message = declination(contacts_selected,['Выбран ','Выбраны ','Выбрано '])+contacts_selected+declination(contacts_selected,[' контакт',' контакта',' контактов'])+' на сумму '+contacts_price+declination(contacts_price,[' балл',' балла',' баллов']);
				notice_message += '. <a href="javascript:void(0);" class="clear-selected-button red">Снять выделение</a>';				
				$('.notice_green').find('.notice_text').html(notice_message);
				$('.notice_green').show();
			}
			if ((need_mass_select_confirm_selected && selected_count > 2) || (need_mass_select_confirm_unselected && unselected_count > 2 && contacts_selected > 0)) {
				var message;
				if (action == 1) {
					message = 'Вы хотите выделить все '+f1+'контакты?';
				} else {
					message = 'Вы хотите снять выделение со всех '+f2+'контактов?';
				}			
				$.SaexPopup({
					message: message,
					buttons: [{
						title: "Да, на странице",				
						handler: function() {
							if (action==1) {
								need_mass_select_confirm_selected = false;
								$('.contact-item input.checkbox').each(function() {
									if ($(this).attr("checked")==false) 
										$(this).attr("checked", true).trigger("change");										
								});															
							} else {
								need_mass_select_confirm_unselected = false;
								$('.contact-item input.checkbox').each(function() {
									if ($(this).attr("checked")==true) 
										$(this).attr("checked", false).trigger("change");										
								});								
								contacts_selected = 0;
								contacts_price = 0;
							}
							return true;
						}
					},
					{
						title: (action == 1)?"Да, весь список":"Да, со всего списка",
						handler: function() {
							if (action == 1) {
								need_mass_select_confirm_selected = false;
								$('.contact-item input.checkbox').each(function() {
									if ($(this).attr("checked")==false) 
										$(this).attr("checked", true).trigger("change");
								});	
							} else {
								need_mass_select_confirm_unselected = false;
								$('.contact-item input.checkbox').each(function() {
									if ($(this).attr("checked")==true) 
										$(this).attr("checked", false).trigger("change");										
								});						
							}	
							jQuery.ajax({
								url:'/index.php?mod=my_contacts',
								type: 'POST',
								data: {cmd:cmd,action: action, ajax:1,q:$('#search_conditions').val(),c:$('#catalogue_conditions').val()},
								beforeSend:function(){
									$('#xxSaexPopupxx').find('#xxSaexPopupxx-message').text("Пожалуйста, подождите несколько секунд...");
									$('#xxSaexPopupxx').find('input[type=button]').hide();
								},
								success: function(data){								
									if (data.success == 1) {
										$('#xxSaexPopupxx .display_all').hide();
										if (action==1) {											
											var notice_message = declination(data.count,['Выбран ','Выбраны ','Выбрано '])+data.count+declination(data.count,[' контакт',' контакта',' контактов'])+' на сумму '+data.price+declination(data.price,[' балл',' балла',' баллов']);
											notice_message += '. <a href="javascript:void(0);" class="clear-selected-button red">Снять выделение</a>';
											$('.notice_green').find('.notice_text').html(notice_message);
											$('.notice_green').show();
											contacts_selected = data.count;
											contacts_price = data.price;
										} else {
											$('.notice_green').hide();
											contacts_selected = 0;
											contacts_price = 0;
										}										
									} else {
										$('#xxSaexPopupxx').find('#xxSaexPopupxx-message').text("Ошибка!");
										return false;
									}
								}	
							});					
						}
					},				
					{
						title: "Нет",						
						handler: function() {							
							need_mass_select_confirm_selected = false;							
							need_mass_select_confirm_unselected = false;
							return true;
						}
					}
					]
				});
			}
		}	
		//return false;
	});

	$('.buy_current').live('click', function(){
		/*var $checkboxes = $('.contact-item input.checkbox:checked');
		$.each($checkboxes, function(){
			$(this).attr('checked', false).trigger("change");;
			$(this).parents('.ez-checkbox').removeClass('ez-checked');			
		});	*/	
		/*
		var $checkbox = $parent.find('input.checkbox');
		$checkbox.attr('checked', true).trigger("change");;
		$checkbox.parents('.ez-checkbox').addClass('ez-checked');*/
		var myparent = $(this).parents('.row_searchresult');
		var checkbox = $(myparent).find('input.checkbox');
		var id = $(checkbox).attr('name').replace('id_', '');
		var message = "Подтвердите покупку контакта " + $(myparent).find('a.red14').text();
		$.SaexPopup({
			message: message,
			buttons: [{
			    title: "Да",
			    cssClass: 'buy_popup_ok',
			    handler: function() {		    	
			    	item_that_was_selected = id;			  
			    	return false;				    
			    }
			},
			{
				title: "Нет",				
				handler: function() {						
					return true;
				}
			}]
		});		
		return false;
	});

	$('.buy_popup_ok').live('click', function(){		
		jQuery.ajax({
			url:'/index.php?mod=my_contacts',
			type: 'POST',
			data: {id:item_that_was_selected,mod:'my_contacts',cmd:'save_my_contacts',ajax:1},
			beforeSend:function(){
				$('#xxSaexPopupxx').find('#xxSaexPopupxx-message').text("Пожалуйста, подождите несколько секунд...");
				$('#xxSaexPopupxx').find('input[type=button]').hide();
			},
			success: function(obj){		
				if (obj.status == 'ok') {
					$('#xxSaexPopupxx').find('#xxSaexPopupxx-message').text("Спасибо за покупку!");
					location.href = "/index.php?mod=my_contacts";
				} else {
					$('#xxSaexPopupxx .display_all').hide();
					$('#balance_popup').find('#balance-success').hide();
					$('#balance_popup').find('#txt-error').text('Для завершения операции вам не хватает '+Math.round(obj.d)+declination(Math.round(obj.d), [' балл',' балла',' баллов']));
					$('#balance_popup').find('#txt-error').show();
					$('#balance_popup').fadeIn();
				}
			}
		});
		return false;
	});

	$('#packable-add-btn').click(function(){
		$opaco.fadeIn();
		$("#packable-add").fadeIn();
		return false;
	});

	$("#complain-button").click(function() {
		$("#loadable-content").load($(this).attr("href") + " #complain", function() {
			$('select').sb();
			//$opaco.fadeIn();
			$("#complain").fadeIn();
		});
		return false;
	});
	$("#actualize-button").click(function() {
		$("#loadable-content").load($(this).attr("href") + " #actualize", function() {
			//$opaco.fadeIn();
			$("#actualize").fadeIn();
		});
		return false;
	});
	$("#checkAll").change(function() {
		need_mass_select_confirm_selected = false;
		need_mass_select_confirm_unselected = false;
		var me = $(this);
		/*
		$(".selectAll").attr('checked', $(this).attr('checked')).trigger('change');*/
		var checkboxes = $("input[type=checkbox].selectAll");
		$.each(checkboxes, function(){
			if (me.attr('checked')!=$(this).attr('checked'))
				$(this).attr('checked', me.attr('checked')).trigger('change');
		});
	});	
	$("#button_post_proceed").click(function() {
		jQuery.ajax({
			url:'/admin.php',
			type: 'GET',
			data: {mod:'csv',cmd:'post_proceed'},
			beforeSend: function(){
				$('#post_proceed_count').text("подождите...").hide();
				$('#post_proceed_count').fadeIn();				
			},
			success: function(xml){
				var contacts_imported = $(xml).find('contacts_imported').text();				
				var contacts_failed = $(xml).find('contacts_failed').text();
				var result = 'удачно: '+contacts_imported+' неудачно: '+contacts_failed; 
				$('#post_proceed_count').text(result);				
			}
		});
	});
	$(".ajax_favorites").live("click", function() {
		var self = $(this); 
		if ($(this).hasClass('my_favorites'))
			action='remove';
		else
			action='add';
		query='/index.php?mod=contacts&ajax=1&action='+action+'$id='+$(this).attr("id");
		jQuery.ajax({
			url: '/index.php',
			type: 'GET',
			data: {mod:'contacts',cmd:'ajax_favorites',ajax:1,action:action,id:$(this).attr("id")},
			beforeSend: function(){$("#ico-loading").show();},
			success: function(data) {
				//alert(action);
				if (data.success==1)
					if (action=='add') { 
						self.hide();
						$("#rem_"+data.message).show();
					} else {
						self.hide();
						$("#add_"+data.message).show();
					}
				$("#ico-loading").hide()
			}
			});
		//$("#ico-loading").hide();
	});	
	
	$(".add-to-favorites-button").live("click", function() {
		jQuery.ajax({
			url: '/index.php?mod=contacts',
			type: 'GET',
			data: {mod:'contacts',cmd:'to_favorites',ajax:1},
			beforeSend: function(){$("#ico-loading").show();},
			success: function(data) {			
				$("#ico-loading").hide();
				need_mass_select_confirm_unselected = false;
				$('.contact-item input[type=checkbox]').each(function(index) {
					if ($(this).attr("checked")==true) {
						$(this).attr("checked",false).trigger('change');
						var id = $(this).attr("id");
						if (id.indexOf('cb_id')>-1) {
							id = id.replace("cb_id_","");
							var add_id = 'add_'+id;
							var rem_id = 'rem_'+id;						
							$("#"+add_id).hide();
							$("#"+rem_id).show();
						}
					}						
				});
				$('.notice_green').hide();
				contacts_selected = 0;
				contacts_price = 0;
			}
		});	
	});
	
	$(".remove-from-favorites-button").live("click", function() {
		jQuery.ajax({
			url: '/index.php?mod=contacts',
			type: 'GET',
			data: {mod:'contacts',cmd:'del_favorites',ajax:1},
			beforeSend: function(){$("#ico-loading").show();},
			success: function(data) {
				$("#ico-loading").hide();
				window.location.reload();
			}
		});	
	});
	
	$(".notice-close-button").live("click", function() {
		$(this).parents("div[class*='notice_']").hide();
	});
	
	$(".clear-selected-button").live("click", function() {
		jQuery.ajax({
			url:'/index.php?mod=my_contacts',
			type: 'GET',
			data: {cmd:'selectAllFavorites',action: 0, ajax:1},
			beforeSend:function(){
				need_mass_select_confirm_unselected = false;
				$('.notice_green').find('.notice_text').html("Пожалуйста, подождите...");				
			},
			success: function(data){								
				if (data.success == 1) {					
					need_mass_select_confirm_unselected = false;
					$('.contact-item input.checkbox').each(function() {
						if ($(this).attr("checked")==true) 
							$(this).attr("checked", false).trigger("change");										
					});	
					$('.notice_green').hide();
					contacts_selected = 0;
					contacts_price = 0;					
				} else {
					$('.notice_green').find('.notice_text').html("Ошибка");	
				}
			}	
		});
	});
});

function get_rules(oThis){
	if (!$('#rules').hasClass('prc')) {
		var $popup = $('#packable-add');
		var $container = $('#packable-add').find('#rules');
		jQuery.ajax({
			url: '/index.php',
			type:'GET',			
			data:{mod:"page",cmd:'csv-template-rules'},
			beforeSend:function(){
				$container.append('<span id="i01" style="font-size:14px;margin:0 auto;display:inline-block;color:#C80405;text-align: center">Загрузка...</span> ');
			},
			success: function(html){
				$('#i01').remove();
				$container.append(html);
				$container.addClass('prc');
				$popup.css({position:'absolute'});
				$('.display_all').css({background:'none'});
			}
		});
	} else {
		$('#rules').toggle();

	}
}

function buy_this(oThis, id){
	jQuery.ajax({
		url:'/index.php',
		type: 'GET',
		data: {
			id:id,
			mod:'my_contacts',
			cmd:'save_my_contacts',
			ajax:1
		},
		beforeSend:function(){
			oThis.text("Подождите...");
		},
		success: function(data){
			if (data.status == 'ok') {
				oThis.text("Мои контакты");
				window.location.reload();
			} else {				
				$('#balance_popup').find('#balance-success').hide();
				$('#balance_popup').find('#txt-error').text('Для завершения операции вам не хватает ' + declination(Math.round(data.d), ['балл','балла','баллов']));
				$('#balance_popup').find('#txt-error').show();					
				$('#balance_popup').fadeIn();
			}
		}
	});
	return false;
}

