$(document).ready(function() {
    var tools = $('#tools');
    var counter = tools.find('.basket-item-count');
    
    tools.find('a.print').click(function() {
        window.print();
    });
    
    tools.delegate('a.add-page', 'click', function() {
        var self = $(this);
        
        var data = {
            cm_action: ['add'],
            id: $(this).attr('data-id'),
            url: $(this).attr('data-url'),
            lang: $(this).attr('data-lang'),
            html: $('#content > div:first').html(),
            extracol: $('.subpage #content .right').html()
        };
		
		if($('#exits').length)
			data.html += '<div id="exits">'+$('#exits').html()+'</div>';
		if($('#portfolio').length)
			data.html += '<div id="portfolio">'+$('#portfolio').html()+'</div>';
        
        /* Contacts */
        if(contact = data.url.match(/(?:all-contacts|yhteystiedot|management-group|board-of-directors).*id=(\d+)/)) {
            data.contact_id = contact[1];
            data.html = '';
        }
        
        /* Investments */
        if(estate = data.url.match(/(?:real-estate-portfolio|real-estate-sijoituskohteet).*id=(\d+)/)) {
            data.estate_id = estate[1];
            data.html = '';
        }
        else if(investment = data.url.match(/(?:portfolio|sijoituskohteet).*id=(\d+)/)) {
            data.investment_id = investment[1];
            data.html = '';
        }
        
        $.post('/saved_pages/basket', data, function(json) {
            self.text('Remove page').attr('class', 'remove-page').hide().fadeIn();
        });
        
        counter.text(parseInt(counter.text()) + 1);
    });
    
    tools.delegate('a.remove-page', 'click', function() {
        var self = $(this);
        
        var data = {
            cm_action: ['del'],
            id: $(this).attr('data-id'),
            url: $(this).attr('data-url'),
            lang: $(this).attr('data-lang')
        };
        
        /* Contacts */
        if(contact = data.url.match(/^\/contacts.*id=(\d+)/)) {
            data.contact_id = contact[1];
        }
        
        /* Investments */
        if(estate = data.url.match(/real-estate-portfolio.*id=(\d+)/)) {
            data.estate_id = estate[1];
            data.html = '';
        }
        else if(investment = data.url.match(/portfolio.*id=(\d+)/)) {
            data.investment_id = investment[1];
            data.html = '';
        }
        
        $.post('/saved_pages/basket', data, function(json) {
            self.text('Add page').attr('class', 'add-page').hide().fadeIn();
        });
        
        counter.text(parseInt(counter.text()) - 1);
    });
    
    
    $('#saved-pages li.pages').appendTo($('#saved-pages ul.tabs'));
	
	
    $('#page-sorter').sortable({
        items: '.page',
        axis: 'y',
        handle: '.handle',
        cursor: 'move',
        stop: function() {
            var data = {
                cm_action: ['sort']
            };
            
            $(this).find('.page').each(function(i) {
                data['order['+$(this).attr('data-page')+']'] = i;
            });
            
            $.post('/saved_pages/basket', data);
        }
    });
    
    $('#page-sorter .items').sortable({
        axis: 'y',
        handle: '.handle',
        cursor: 'move',
        stop: function() {
            var ids = [];
            
            var data = {
                cm_action: ['edit'],
                id: $(this).parent().attr('data-page').replace('page:', '')
            }
            
            $(this).children('div').each(function(i) {
                ids.push($(this).attr('data-id'));
            });
            
            var type = $(this).children().eq(0).attr('class');
            
            if(type == 'investment')
                data.investment_ids = ids.join(', ');
            else if(type == 'contact')
                data.contact_ids = ids.join(', ');
            else if(type == 'estate')
                data.estate_ids = ids.join(', ');
            
            $.post('/saved_pages/basket', data);
        }
    });
    
    $('#page-sorter input[type=checkbox]').click(function() {
        var data = {
            cm_action: ['del'],
            id: $(this).parent().attr('data-page').replace('page:', '')
        };
        
        var type = $(this).parent().attr('class');
        
        if(type == 'investment')
            data.investment_id = $(this).parent().attr('data-id');
        else if(type == 'contact')
            data.contact_id = $(this).parent().attr('data-id');
        else if(type == 'estate')
            data.estate_id = $(this).parent().attr('data-id');
        
        $.post('/saved_pages/basket', data);
        
        $(this).parent().fadeOut(function() {
            $(this).remove();
        });
    });
    
    $('#page-sorter a.remove-all').click(function() {
		if(!confirm($(this).attr('data-confirm')))
			return(false);
		
        $('#saved-pages .page').each(function() {
            $.post('/saved_pages/basket', {
                cm_action: ['del'],
                id: $(this).attr('data-page').replace('page:', '')
            });
        }).fadeOut(function() {
            $(this).remove();
            $('#saved-pages a.remove-all').hide().prev().fadeIn();
        });
        
        $(this).fadeOut();
    });
	
	
	
	/* Manage your report */
	
	$('#sitemap li').click(function(e) {
		var input = $(this).find('input');
		
		if(e.target != input.get(0))
			input.attr('checked', !input.attr('checked'));
		
		var data = {
			cm_action: ['add'],
			id: $(this).attr('data-id'),
			url: $(this).attr('data-url'),
			lang: 'en_US'
		};
		
		if(!input.attr('checked'))
			data.cm_action = ['del'];
		
		var type = $(this).attr('data-type');
		
		if(type) {
			data[type] = $(this).attr('data-pid');
			$.post('/saved_pages/basket', data);
		}
		else
			$.get($(this).attr('data-url'), function(html) {
				data.html = $('#content > div:first', html).html();
				data.extracol = $('.subpage #content .right', html).html();
				
				if($('#exits', html).length)
					data.html += '<div id="exits">'+$('#exits', html).html()+'</div>';
				if($('#portfolio', html).length)
					data.html += '<div id="portfolio">'+$('#portfolio', html).html()+'</div>';
				
				$.post('/saved_pages/basket', data);
			});
	});
	
	$('#page-sorter .page').each(function() {
		$('#sitemap li[data-id="'+$(this).attr('data-page').replace('page:', '')+'"]:not(.item) input').attr('checked', true);
	});
	
	$('#page-sorter .items > div').each(function() {
		$('#sitemap li[data-pid="'+$(this).attr('data-id').replace('page:', '')+'"] input').attr('checked', true);
	});
    
    
    
    /* Overlay */
    var dim = $('<div id="dim"></div>').appendTo(document.body);
    var overlay = $('<div id="overlay"><a class="close"></a><div class="inner"></div></div>').appendTo(document.body);
    
    $('a.overlay').click(function() {
        dim.fadeTo(200, 0.5);
        overlay.css({
            'margin-top': -40,
            'opacity': 0
        }).show();
        
        if($(this).attr('href'))
            overlay.find('.inner').load($(this).attr('href'), function() {
                overlay.css({
                    'min-height': overlay.get(0).clientHeight - 80
                }).animate({
                    'margin-top': -overlay.get(0).clientHeight / 2,
                    'opacity': 1
                }, 500);
            });
        
        return(false);
    });
    
    dim.click(function() {
        dim.fadeOut();
        overlay.fadeOut();
    });
    
    overlay.delegate('a.close', 'click', function() {
        dim.click();
    });
    
    
    /* Form helpers */
    $('form').live('submit', function() {
        if(!$(this).checkForm())
            return(false);
    });
    
    
    /* Preload ajax loader animation */
    var ajax_loader = new Image();
    ajax_loader.src = '/files/capman2011/img/ajax-loader.gif';
    
    $('#overlay form').live('submit', function() {
        if(!$(this).checkForm())
            return(false);
        
        $('#overlay').addClass('loading').find('.inner').hide().load($(this).attr('action'), $(this).serializeArray(), function() {
            $(this).fadeIn();
            
            $('#overlay').removeClass('loading').animate({
                'min-height': $(this).height(),
                'margin-top': -($(this).height()+80) / 2
            });
            
            setTimeout(function() {
                $('#dim').click();
            }, 2500);
        });
        
        return(false);
    });
});

 
jQuery.fn.checkForm = function() {
    var errors = [];
    
    this.find('.required').each(function() {
        var value = $(this).find('input, select, textarea').val();
        
        if(value == '') {
            errors.push($(this).addClass('error'));
            $(this).find('> label:first').fadeOut().fadeIn();
        }
    });
    
    if(errors.length)
        return(false);
    else
        return(true);
};
