﻿var current;

$('#preview-template').ready(function() {
    var view = $('#preview-template').contents();

    $("#tabs-mail").tabs();

    //Dialog for edit
    $("#dialog").dialog({
        bgiframe: true,
        autoOpen: false,
        height: 500,
        width: 650,
        modal: true,
        buttons: {
            'Spara': function() {
                var content = $('#dialog #txtcontent').val();
                view.find(current).html(content);
                $(this).dialog('close');
            }
        }
    });

    //Load properties
    view.find('#properties input').each(function(i) {
        var id = $(this).attr('id').split('_');
        var selector = id[0];
        var style = id[1];
        var value = $(this).attr('value');

        styleupdate(view.find(selector), style, value);

        //Load value into textbox
        var textboxid = $(this).attr('title');
        var marked = $(this).attr('class');
        var extra = $(this).attr('name');
        var valuebox = $(textboxid);

        valuebox.val(value);
        valuebox.focus(function() { view.find(marked).addClass('selected'); });
        valuebox.blur(function() { view.find(marked).removeClass('selected'); });
        valuebox.change(function() { styleupdate(view.find(selector), style, $(this).val()); });
        if (extra == 'colorpicker') valuebox.attachColorPicker();
    });
    view.find('#properties').remove();

    //Prevent link-clicks
    view.find('a').click(function() { return false; });

    //Clickable fields
    view.find('.content').click(function() {
        current = '#' + $(this).attr('id');
        showdialog($(this).html());
    });
});

function styleupdate(obj, style, value) {
    if (style == 'href' || style == 'src' || style == 'width' || style == 'height')
        obj.attr(style, value);
    else
        obj.css(style, value);
}

function showdialog(content) {
    $('#dialog #txtcontent').val(content);
    $('#dialog').dialog('open');
}

function preCommit() {
    var holder = $('#preview-template').contents();
    var html = holder.find('body').html();

    var css_background = holder.find('body').css('background-color');
    var css_color = holder.find('body').css('color');
    var css_fontfamily = holder.find('body').css('font-family');
    var css_fontsize = holder.find('body').css('font-size');

    html = '<html><head></head><body style="background-color:' + css_background + '; color:' + css_color + '; font-family:' + css_fontfamily + '; font-size:' + css_fontsize + ';">' + html + '</body></html>';
    
    $('#hfmail').attr('value', html);
}
