/*
 * Apologies if the formatting in this is messed up.
 * Tried the best I could but Eclipse kept switching the indent
 * to tabs in certain places and spaces in other bits. Doesn't seem to like
 * .js files for some reason.
 * 
 * Needs work on to make it more watertight, but that's front-end's job
 * not mine ;)
 */

function unbind_func() {
    agree = confirm("Are you sure you want to delete this employer?")
    if (agree) {
        row_id = $(this).parent().find("input.row-id").val()
        
        $(this).parent().parent().fadeOut('slow', function() {
            $(this).remove();
        });
        
        $.post(window.location, {'remove':row_id}, function(data) {})
    }
}

function create_row(table, data) {
    window.rows++;
    row = table.find("tbody").append("<tr></tr>").find("tr:last")
    classes = new Array(
        "employer",
        "jobdesc",
        "fromdate",
        "todate",
        "basicpay",
        "takehome"
    );
    for (i=0; i<7; i++) {
	if (i != 6)
	    row.append("<td class='"+ classes[i] +"'>"+ data[classes[i]] +"</td>")
	else
	    row.append("<td><img class='remove' src='/assets/images/common/close.png' alt='Remove' />" +
	    		"<input type='hidden' class='row-id' value='" + window.rows + "' />" +
	    		"</td>")
    }
    
    data['employer-id'] = window.rows;
    $.post(window.location, data, function(data) {})
    
    $(".remove").unbind('click').click(unbind_func)
    
    return row
}

$(function() {
    
    loc = String(window.location);
    if (loc.search(/view/i) != -1) {
        $("input[type='text']").each(function() {
            var numchars = $(this).val().length;
            var fwidth = $(this).css('width').replace('px', '');
            var newh = Math.ceil(numchars / fwidth) * 16;
            if (newh < 16) newh = 16;
            $(this).css('height', newh + 'px');
        })
    }
    
    
    
    window.rows = $("#employer-history tr").length - 1;
    
    $(".remove").unbind('click').click(unbind_func);
    
    $("#add-job").click(function() {
        data = {
            "employer" : $("#yeh-employer").val(),
            "address"  : $("#yeh-address").val(),
            "jobdesc"  : $("#yeh-jobdesc").val(),
            "fromdate" : $("#yeh-fromdate").val(),
            "todate"   : $("#yeh-todate").val(),
            "basicpay" : $("#yeh-basicpay").val(),
            "takehome" : $("#yeh-takehome").val()
        }
        
        for (key in data) {
            valid = true;
            if (data[key] == "")
        	valid = false;
        }
        if (valid == false) {
            alert("Please enter details into all fields.")
            return false;
        }
        
        create_row(
        	$("#employer-history"),
        	data
        );
        
        $("#employment-history-fields input[type='text']").each(function() {
            $(this).val("")
        }) 
        
        return false;
    })
})
