var font2lineHeight = new Array();
font2lineHeight[8]  = 10;
font2lineHeight[9]  = 11;
font2lineHeight[10] = 12;
font2lineHeight[11] = 14;
font2lineHeight[12] = 15;
font2lineHeight[13] = 16;
font2lineHeight[14] = 17;
font2lineHeight[15] = 18;
font2lineHeight[16] = 20;
font2lineHeight[17] = 21;
font2lineHeight[18] = 22;
font2lineHeight[19] = 23;
font2lineHeight[20] = 24;
font2lineHeight[21] = 26;
font2lineHeight[22] = 27;
font2lineHeight[23] = 28;
font2lineHeight[24] = 29;
font2lineHeight[25] = 30;
font2lineHeight[26] = 32;
font2lineHeight[27] = 33;
font2lineHeight[28] = 34;
font2lineHeight[29] = 35;
font2lineHeight[30] = 36;
font2lineHeight[31] = 38;
font2lineHeight[32] = 39;

var textAlign = false;
var alignChecked = false;

var os2userAgent = new Array();
os2userAgent["Windows 98"] = "Windows 98";
os2userAgent["Windows 98 Second Edition"] = "";
os2userAgent["Windows 2000"] = "Windows NT 5.0";
os2userAgent["Windows XP"] = "Windows NT 5.01";
os2userAgent["Windows XP SP2"] = "Windows NT 5.1";
os2userAgent["Windows Vista"] = "Windows NT 6.0";
os2userAgent["Windows 7"] = "Windows NT 6.1";
os2userAgent["Mac OS X v10.3 Panther"] = "";
os2userAgent["Mac OS X v10.4 Tiger"] = "";
os2userAgent["Mac OS X v10.5 Leopard"] = "";
os2userAgent["Mac OS X v10.6 Snow Leopard"] = "";

var maxId = 2;

var defaultParams = new Array();
var defaultParamsB1 = new Array();

defaultParams['columns'] = 1;
defaultParams['os'] = 'Windows XP';
defaultParams['font-family'] = 'Arial';
defaultParams['font-size'] = 14;
defaultParams['line-height'] = 17;
defaultParams['letter-spacing'] = 'normal';
defaultParams['word-spacing'] = 'normal';
defaultParams['bold'] = 'normal';
defaultParams['italic'] = 'normal';
defaultParams['uppercase'] = 'none';
defaultParams['color'] = '#000000';
defaultParams['bg'] = '#ffffff';
defaultParams['text-align'] = 'left';
defaultParams['columns-padding'] = 5;
defaultParams['field-width'] = 968;

defaultParamsB1['font-size'] = 22;
defaultParamsB1['line-height'] = 27;
defaultParamsB1['text-align'] = 'center';
defaultParamsB1['color'] = '#AD0000';


function getActiveBox()
{
    if(activeBoxId == 'undefined') activeBoxId = 1;
    return activeBoxId;
}


function applyActiveBox(boxId)
{
    activeBoxId = boxId;
    $('.fieldWrap').removeClass('fieldWrapActive');
    $('#fieldWrap_' + boxId).removeClass('fieldWrapOver');
    $('#fieldWrap_' + boxId).addClass('fieldWrapActive');

    $('.hidden').css('display', 'none');
    $('#fieldWrap_' + boxId + ' .hidden').css('display', 'block');

    cancelAnotherEdits();
    applyBoxStyle(false);
}


function cancelAnotherEdits()
{
    $(".boxWrap .writeText").remove();
    $(".boxWrap .contentText").show();
}


function applyBoxStyle(toDefault)
{
    $('#loader').show();

    boxId = getActiveBox();
    style = $('#contentText_' + boxId).attr('style') + ";" + $('#fieldWrap_' + boxId + ' .fieldStyles').val();

    $.post("ajax.php", {request:'prepareBoxStyle', style:style},
        function(data){
            $('#loader').hide();

            params = new Array();
            params['columns'] = false;
            params['columns-padding'] = false;
            params['os'] = false;

            params['font-family'] = false;
            params['font-size'] = false;
            params['line-height'] = false;
            params['letter-spacing'] = false;
            params['word-spacing'] = false;
            params['font-weight'] = false;
            params['font-style'] = false;
            params['text-transform'] = false;
            params['color'] = false;
            params['background-color'] = false;
            params['text-align'] = false;

            if(!toDefault)
            {
                vars = data.split(';');
                for(i=0;i<vars.length;i++)
                {
                    if(vars[i] != '')
                    {
                        singleParam = vars[i];
                        parts = singleParam.split(':');
                        if(typeof(parts[0]) != 'undefined' && typeof(parts[1]) != 'undefined' && typeof(params[parts[0]]) != 'undefined')
                        {
                            params[parts[0]] = parts[1];
                        }
                    }
                }
            } else
            {
                if(boxId == 1) defaultText = $("#defaultText_box1").html();
                else if(boxId == 2) defaultText = $("#defaultText_box2").html();
                else defaultText = $("#defaultText").html();

                $('#contentText_' + boxId).html(defaultText);

                if(boxId == 1) tAlign = defaultParamsB1['text-align'];
                else tAlign = defaultParams['text-align'];
                $('#contentText_' + boxId).css('text-align', tAlign);
                $('#contentText_' + boxId + ' table td').css('text-align', tAlign);

                if(boxId == 1) fSize = defaultParamsB1['font-size'];
                else fSize = defaultParams['font-size'];
                $('#contentText_' + boxId).css('font-size', fSize + 'px');

                if(boxId == 1) lHeight = defaultParamsB1['line-height'];
                else lHeight = defaultParams['line-height'];
                $('#contentText_' + boxId).css('line-height', lHeight + 'px');

                $('#contentText_' + boxId).css('letter-spacing', defaultParams['letter-spacing']);
                $('#contentText_' + boxId).css('word-spacing', defaultParams['word-spacing']);
                $('#contentText_' + boxId).css('font-weight', defaultParams['bold']);
                $('#contentText_' + boxId).css('font-style', defaultParams['italic']);
                $('#contentText_' + boxId).css('text-transform', defaultParams['uppercase']);

                if(boxId == 1) fColor = defaultParamsB1['color'];
                else fColor = defaultParams['color'];
                $('#contentText_' + boxId).css('color', fColor);

                if(boxId == 2) fStyles = 'columns:3;';
                else fStyles = '';

                $('#fieldWrap_' + boxId + ' .fieldStyles').val(fStyles);
            }


            if(params['columns']) val = params['columns'];
            else
            {
                if(boxId == 2) val = 3;
                else val = defaultParams['columns'];

            }
            $("#colNumber option[value='" + val + "']").attr('selected', 'selected');


            if(params['columns-padding']) val = params['columns-padding'];
            else val = defaultParams['columns-padding'];
            $("#columnPaddingVal").html(val + "px");
            $("#columnPadding").slider("option", "value", val);


            if(params['os']) os = params['os'];
            else os = defaultParams['os'];

            if(params['font-family']) font = params['font-family'];
            else font = defaultParams['font-family'];

            $("#os_version option[value='" + os + "']").attr('selected', 'selected');
            changeFont(false, os, false, font);


            if(params['font-size'])
            {
                val = params['font-size'];
                val = val.replace("px", "");
            } else
            {
                if(boxId == 1) val = defaultParamsB1['font-size'];
                else val = defaultParams['font-size'];
            }
            $("#fontSize option[value='" + val + "']").attr('selected', 'selected');


            if(params['line-height'])
            {
                val = params['line-height'];
                val = val.replace("px", "");
            } else
            {
                if(boxId == 1) val = defaultParamsB1['line-height'];
                else val = defaultParams['line-height'];
            }
            $("#lineHeightSelect option[value='" + val + "']").attr('selected', 'selected');


            if(params['letter-spacing'])
            {
                val = params['letter-spacing'];
                val = val.replace("px", "");
            } else val = defaultParams['letter-spacing'];
            $("#letterSpacing option[value='" + val + "']").attr('selected', 'selected');


            if(params['word-spacing'])
            {
                val = params['word-spacing'];
                val = val.replace("px", "");
            } else val = defaultParams['word-spacing'];
            $("#wordSpacing option[value='" + val + "']").attr('selected', 'selected');


            if(params['font-weight'] == 'bold' || params['font-weight'] == 700) $('#style_b').css('background-position', '0 -22px');
            else $('#style_b').css('background-position', '0 0');


            if(params['font-style'] == 'italic') $('#style_i').css('background-position', '0 -22px');
            else $('#style_i').css('background-position', '0 0');


            if(params['text-transform'] == 'uppercase') $('#style_t').css('background-position', '0 -22px');
            else $('#style_t').css('background-position', '0 0');

            if(toDefault)
            {
                if(boxId == 1) val = defaultParamsB1['color'];
                else val = defaultParams['color'];

                $("#fieldWrap_" + boxId + " .fieldColor").ColorPickerSetColor(val);
                $("#fieldWrap_" + boxId + " .fieldColor").css('backgroundColor', val);
            }

            if(params['text-align'])
            {
                $('.align').css('background-position', '0 0');
                $('#align_' + params['text-align']).css('background-position', '0 -22px');
            } else
            {
                $('.align').css('background-position', '0 0');

                if(boxId == 1) tAlign = defaultParamsB1['text-align'];
                else tAlign = defaultParams['text-align'];

                $('#align_' + tAlign).css('background-position', '0 -22px');
            }
    });
}


function addField()
{
    maxId++;
    newId = maxId;

    html  = "";
    html += "<div id='fieldWrap_" + newId + "' class='fieldWrap'>";
    html += "<div class='fieldWrapInner'>";
    html += "<div class='hidden'>";
    html += "<div class='fieldWidth'><span>" + defaultParams['field-width'] + "</span>px</div>";
    html += "<div class='fieldSlider' id='fieldSlider_" + newId + "'></div>";
    html += "<div class='fieldColor'></div>";
    html += "<a href='javascript:void(0)' onclick='resetField(" + newId + ")'>reset</a>";
    html += " <a href='javascript:void(0)' onclick='removeField(" + newId + ")'>delete</a>";
    html += "</div>";
    html += "<input type='hidden' name='#' class='fieldStyles' value='' />";
    html += "<div class='boxWrap' id='boxWrap_" + newId + "'>";
    html += "<div id='contentText_" + newId + "' class='contentText' style='font-size:14px;line-height:17px'>";
    html += $('#defaultText').html();
    html += "</div>";
    html += "</div>";
    html += "</div>";
    html += "</div>";

    $('#fieldsWrapper').append(html);

    applyActiveBox(newId);


    $("#fieldWrap_" + newId).bind("mouseover", function(e){
        fieldMouseover(this);
    });

    $("#fieldWrap_" + newId).bind("mouseout", function(e){
        fieldMouseout(this);
    });

    $("#fieldWrap_" + newId).bind("click", function(e){
        fieldClick(this);
    });


    $("#fieldWrap_" + newId + " .fieldSlider").slider({
			value: defaultParams['field-width'],
			min: 20,
			max: defaultParams['field-width'],
			step: 1,
			slide: function(event, ui) {
                id = $(this).attr('id');
                id = id.replace("fieldSlider_", "");
                applyFieldWidth(id, ui.value);
			},
            change: function(event, ui) {}
	});

    $("#fieldWrap_" + newId + " .fieldColor").ColorPicker({
    	color: '#000000',
    	onShow: function (colpkr) {
    		$(colpkr).fadeIn(500);
            fontPickerId = $(colpkr).attr('id');
    		return false;
    	},
    	onHide: function (colpkr) {
    		$(colpkr).fadeOut(500);
    		return false;
    	},
    	onChange: function (hsb, hex, rgb, parent) {
            $(parent).css('backgroundColor', '#' + hex);
            applyFontColor(hex);
    	},
        onSubmit: function(colpkr) {
		    $('#' + fontPickerId).fadeOut(500);
		}
    });

    $('.fieldWrap, .colorpicker').bind("outerClick", function(){
        removeBorders();
    });
}


function removeBorders()
{
    $('.fieldWrap').removeClass('fieldWrapOver');
    $('.fieldWrap').removeClass('fieldWrapActive');
    $('.fieldWrap .hidden').hide();



/*
    id = $(obj).attr('id');
    id = id.replace("fieldWrap_", "");
    applyActiveBox(id);
*/
}


function applyFieldWidth(boxId, width)
{
    $('#fieldWrap_' + boxId + ' .fieldWidth span').text(width);
    $('#boxWrap_' + boxId).css('width', width - 22);
}


function removeField(boxId)
{
    $('#fieldWrap_' + boxId).remove();
    if(boxId == activeBoxId) applyActiveBox(1);
}


function resetField(boxId)
{
    applyBoxStyle(true);
}


function showEditField()
{
    boxId = getActiveBox();

    $('#loader').show();
    html = $('#contentText_' + boxId).html();

    $.post("ajax.php", {request:'editPrepare', html:html},
        function(data){
            $('#loader').hide();
            $('#editTextDialog textarea').val(data);
            $('#editTextDialog').dialog('open');
    });
}


function writeTextSave(mode)
{
    boxId = getActiveBox();

    $('#loader').show();
    cols = $("#colNumber").val();
    padding = $('#columnPaddingVal').text();

    if(mode == 'save') html = $('#editTextDialog textarea').val();
    else if(mode == 'reset') html = $('#defaultText').html();

    $.post("ajax.php", {request:'savePrepare', html:html, cols:cols, padding:padding},
        function(data){
            $('#loader').hide();
            $('#contentText_' + boxId).html(data);
    });
}


function writeTextCancel()
{
    boxId = getActiveBox();

    $('#boxWrap_' + boxId + ' .writeText').remove();
    $('#boxWrap_' + boxId + ' .contentText').show();
}


function applyFontFamily(obj, v, set)
{
    boxId = getActiveBox();

    val = (obj) ? $(obj).val() : v;
    $('#contentText_' + boxId).css('font-family', val);
    $("#fontFamily option[value='" + val + "']").attr('selected', 'selected');

    setAdditionalStyles('font-family', val);
    defineIsFontInOS(val);
}


function applyFontSize(obj, v, set)
{
    boxId = getActiveBox();

    val = (obj) ? $(obj).val() : v;
    height = font2lineHeight[val];

    $("#lineHeightSelect option[value='" + height + "']").attr('selected', 'selected');
    $('#contentText_' + boxId).css('font-size', val + 'px');

    if(set) applyLineHeight(false, height);
}


function applyLineHeight(obj, v, set)
{
    boxId = getActiveBox();

    val1 = (obj) ? $(obj).val() : v;
    $('#contentText_' + boxId).css('line-height', val1 + 'px');
}


function applyBoldToggle()
{
    boxId = getActiveBox();
    weight = $('#contentText_' + boxId).css('font-weight');

    if(weight == 'bold' || weight == 700)
    {
        val = 'normal';
        $('#style_b').css('background-position', '0 0');
    } else
    {
        val = 'bold';
        $('#style_b').css('background-position', '0 -22px');
    }

    $('#contentText_' + boxId).css('font-weight', val);
}


function applyFontStyleToggle()
{
    boxId = getActiveBox();
    style = $('#contentText_' + boxId).css('font-style');

    if(style == 'normal')
    {
        val = 'italic';
        $('#style_i').css('background-position', '0 -22px');
    } else
    {
        val = 'normal';
        $('#style_i').css('background-position', '0 0');
    }

    $('#contentText_' + boxId).css('font-style', val);
}


function applyTextTransformToggle()
{
    boxId = getActiveBox();
    style = $('#contentText_' + boxId).css('text-transform');

    if(style == 'uppercase')
    {
        val = 'none';
        $('#style_t').css('background-position', '0 0');
    } else
    {
        val = 'uppercase';
        $('#style_t').css('background-position', '0 -22px');
    }

    $('#contentText_' + boxId).css('text-transform', val);
}


function applyFontColor(hex)
{
    boxId = getActiveBox();
    $('#contentText_' + boxId).css('color', '#' + hex);
}


function applyGlobalFontColor(hex)
{
    val = '#' + hex;
    $('.contentText').css('color', val);

    $('.fieldColor').ColorPickerSetColor(val);
    $('.fieldColor').css('backgroundColor', val);
}


function applyFontBG(hex)
{
    $('.contentText').css('background-color', '#' + hex);
    $('body').css('background-color', '#' + hex);
}


function applyColumns(obj, v, set)
{
    boxId = getActiveBox();
    $('#loader').show();

    cols = (obj) ? $(obj).val() : v;
    html = $('#contentText_' + boxId).html();
    padding = $('#columnPaddingVal').text();

    setAdditionalStyles('columns', cols);

    $.post("ajax.php", {request:'applyColumns', html:html, cols:cols, padding:padding},
        function(data){
            $('#loader').hide();
            $('#contentText_' + boxId).html(data);
    });
}


function applyLetterSpacing(obj, v, set)
{
    boxId = getActiveBox();

    val = (obj) ? $(obj).val() : v;
    val = (val == 'normal') ? val : val + 'px';
    $('#contentText_' + boxId).css('letter-spacing', val);
}


function applyWordSpacing(obj, v, set)
{
    boxId = getActiveBox();

    val = (obj) ? $(obj).val() : v;
    val = (val == 'normal') ? val : val + 'px';
    $('#contentText_' + boxId).css('word-spacing', val);
}


/*
function setHash(param, val)
{
    currentHash = window.location.hash;

    output = '';
    if(currentHash.indexOf('#') === 0)
    {
        currentHash = currentHash.substring(1);
        vars = currentHash.split(';');

        for(i=0;i<vars.length;i++)
        {
            if(vars[i] != '')
            {
                singleParam = vars[i];
                parts = singleParam.split('=');

                if(typeof(parts[0]) != 'undefined' && typeof(parts[1]) != 'undefined' && param != parts[0])
                {
                    output += parts[0] + '=' + parts[1] + ';';
                }
            }
        }

        if(typeof(val) != 'undefined')
        {
            output += param + '=' + val + ";";
        }

        if(output != '')
        {
            window.location.hash = output;
        } else window.location.hash = '';
    } else window.location.hash = window.location.hash + param + '=' + val + ";";
}
*/

function changeFont(obj, v, set, font)
{
    boxId = getActiveBox();

    os = (obj) ? $(obj).val() : v;
    $('#loader').show();

    setAdditionalStyles('os', os);

    justLoadStaticState = justLoad;

    $.post("ajax.php", {request:'changeOS', os:os, justLoad:justLoad, font:font},
        function(data){
            $('#fontFamily').html(data);
            if(!font) font = (justLoadStaticState && set) ? 'Arial' : $('#fontFamily option').attr('value');

            if(!justLoadStaticState)
            {
                applyFontFamily(false, font, set);
            } else
            {
                $('#contentText_' + boxId).css('font-family', font);
                $('#contentText_2').css('font-family', font);
            }

            defineIsFontInOS(font);

            setAdditionalStyles('font-family', font);
            $('#loader').hide();
    });
}


function defineIsFontInOS(font)
{
    $('#loader').show();
    $.post("ajax.php", {request:'defineIsFontInOS', font:font},
        function(data){
            $("#statusBar").html(data);
            $('#loader').hide();
    });
}


function applyAlign(align, set)
{
    boxId = getActiveBox();

    $('.align').css('background-position', '0 0');

    if(align != '')
    {
        $('#align_' + align).css('background-position', '0 -22px');

        alignChecked = !alignChecked;
        $('#contentText_' + boxId).css('text-align', align);
        $('#contentText_' + boxId + ' table td').css('text-align', align);
        textAlign = align;
    } else
    {
        $('#contentText_' + boxId).css('text-align', 'left');
    }
}


function resetToDefault()
{
    activeBoxId = 1;
    boxId = activeBoxId;

    box_2 = $("#defaultFieldWrap").html();
    box_2 = box_2.replace(/\[x\]/g, "2");
    box_2 = box_2.replace(/2text/g, $("#defaultText_box2").html());

    $(".fieldWrap").not('#fieldWrap_' + boxId).not('#defaultFieldWrap .fieldWrap').remove();

    $('.fieldWrap').removeClass('fieldWrapActive');
    $('.fieldWrap .hidden').hide();
    $('#fieldWrap_' + boxId).removeClass('fieldWrapOver');

    $('#fieldWrap_' + boxId + ' .fieldStyles').val('');
    $('#contentText_' + boxId).attr('style', '');
    $('#contentText_' + boxId).css('font-size', defaultParamsB1['font-size'] + 'px');
    $('#contentText_' + boxId).css('line-height', defaultParamsB1['line-height'] + 'px');
    $('#contentText_' + boxId).css('font-family', defaultParams['font-family']);
    $('#contentText_' + boxId).css('color', defaultParamsB1['color']);
    $('#contentText_' + boxId).css('text-align', defaultParamsB1['text-align']);

    $('.align').css('background-position', '0 0');
    $('#align_' + defaultParamsB1['text-align']).css('background-position', '0 -22px');


    $("#fieldWrap_" + boxId + " .fieldSlider").slider("option", "value", defaultParams['field-width']);
    $("#fieldWrap_" + boxId + " .fieldWidth span").text(defaultParams['field-width']);
    $('#boxWrap_' + boxId).css('width', defaultParams['field-width'] - 22);

    // Content text
    // box1
    html = $('#defaultText_box1').html();
    $('#fieldWrap_' + boxId + ' .writeText').remove();
    $('#contentText_' + boxId).show().html(html);


    // box2
    $('#fieldWrap_1').after(box_2);

    $('#fieldWrap_2 .fieldStyles').val('columns:3;');
    $('#contentText_2').attr('style', '');
    $('#contentText_2').css('font-size', defaultParams['font-size'] + 'px');
    $('#contentText_2').css('line-height', defaultParams['line-height'] + 'px');
    $('#contentText_2').css('font-family', defaultParams['font-family']);

    $("#fieldWrap_2").bind("mouseover", function(e){
        fieldMouseover(this);
    });

    $("#fieldWrap_2").bind("mouseout", function(e){
        fieldMouseout(this);
    });

    $("#fieldWrap_2").bind("click", function(e){
        fieldClick(this);
    });

    $(".fieldSlider").slider({
        value:946,
        min:20,
        max:968,
        step:1,
        slide: function(event, ui) {
                    id = $(this).attr('id');
                    id = id.replace("fieldSlider_", "");
                    applyFieldWidth(id, ui.value);
        },
        change: function(event, ui) {}
	});

    $('#fieldWrap_2 .fieldColor').ColorPicker({
    	color: '#000000',
    	onShow: function (colpkr) {
    		$(colpkr).fadeIn(500);
            fontPickerId = $(colpkr).attr('id');
    		return false;
    	},
    	onHide: function (colpkr) {
    		$(colpkr).fadeOut(500);
    		return false;
    	},
    	onChange: function (hsb, hex, rgb, parent) {
            $(parent).css('backgroundColor', '#' + hex);
            applyFontColor(hex);
    	},
        onSubmit: function(colpkr) {
		    $('#' + fontPickerId).fadeOut(500);
		}
    });

    $('.fieldWrap, .colorpicker').bind("outerClick", function(){
        removeBorders();
    });


    // Columns
    $("#colNumber option[value='" + defaultParams['columns'] + "']").attr('selected', 'selected');

    // OS version
    justLoad = true;
    $("#os_version option[value='" + defaultParams['os'] + "']").attr('selected', 'selected');
    changeFont(false, defaultParams['os'], true, false);
    justLoad = false;

    // Font size
    applyFontSize(false, defaultParamsB1['font-size'], true);
    $("#fontSize option[value='" + defaultParamsB1['font-size'] + "']").attr('selected', 'selected');

    // Letter spacing
    applyLetterSpacing(false, defaultParams['letter-spacing'], true);
    $("#letterSpacing option[value='" + defaultParams['letter-spacing'] + "']").attr('selected', 'selected');

    // Word spacing
    applyWordSpacing(false, defaultParams['word-spacing'], true);
    $("#wordSpacing option[value='" + defaultParams['word-spacing'] + "']").attr('selected', 'selected');

    // Bold
    $('#style_b').css('background-position', '0 0');
    $('#contentText_' + boxId).css('font-weight', defaultParams['bold']);

    // Italic
    $('#style_i').css('background-position', '0 0');
    $('#contentText_' + boxId).css('font-style', defaultParams['italic']);

    // Transform
    $('#style_t').css('background-position', '0 0');
    $('#contentText_' + boxId).css('text-transform', defaultParams['uppercase']);

    // Font color
    color = defaultParams['color'];
    color = color.replace("#", "")
    $('#fontColorSelector').ColorPickerSetColor('#' + color);
    $('#fontColorSelector').css('backgroundColor', '#' + color);
    $('#fontColorHex').text(color);
    $("#fieldWrap_2 .fieldColor").css('backgroundColor', '#' + color);

    color = defaultParamsB1['color'];
    color = color.replace("#", "")
    $("#fieldWrap_" + boxId + " .fieldColor").ColorPickerSetColor('#' + color);
    $("#fieldWrap_" + boxId + " .fieldColor").css('backgroundColor', '#' + color);


    // BG color
    bg = defaultParams['bg'];
    bg = bg.replace("#", "")
    $('#bgColorSelector').ColorPickerSetColor('#' + bg);
    $('#bgColorSelector').css('backgroundColor', '#' + bg);
    $('#bgColorHex').text(bg);
    applyFontBG(bg);

    // TD padding
    $("#columnPaddingVal").text(defaultParams['columns-padding'] + "px");
    $("#columnPadding").slider("option", "value", defaultParams['columns-padding']);
}


function apply_saved_params()
{
    params = new Array();
    params['columns'] = false;
    params['os'] = false;
    params['family'] = false;
    params['size'] = false;
    params['height'] = false;
    params['letter-spacing'] = false;
    params['word-spacing'] = false;
    params['bold'] = false;
    params['italic'] = false;
    params['uppercase'] = false;
    params['color'] = false;
    params['bg'] = false;
    params['text-align'] = false;

/*
    hash = window.location.hash;
    hash = hash.substring(1);
    hash = hash.replace(/%20/gi, " ");
    vars = hash.split(';');


    for(i=0;i<vars.length;i++)
    {
        if(vars[i] != '')
        {
            singleParam = vars[i];
            parts = singleParam.split('=');

            if(typeof(parts[0]) != 'undefined' && typeof(parts[1]) != 'undefined' && typeof(params[parts[0]]) != 'undefined')
            {
                params[parts[0]] = parts[1];
            }
        }
    }
*/
    if(params['columns'])
    {
        $("#colNumber option[value='" + params['columns'] + "']").attr('selected', 'selected');
        applyColumns(false,params['columns'], false);
    }

    if(params['os'] && params['family'])
    {
        $("#os_version option[value='" + params['os'] + "']").attr('selected', 'selected');
        changeFont(false, params['os'], false, params['family']);
    } else changeFont(false, "Windows XP", true, false);

    if(params['size'])
    {
        $("#fontSize option[value='" + params['size'] + "']").attr('selected', 'selected');
        applyFontSize(false, params['size'], false);
    }

    if(params['height'])
    {
        $("#lineHeightSelect option[value='" + params['height'] + "']").attr('selected', 'selected');
        applyLineHeight(false, params['height'], false);
    }

    if(params['letter-spacing'])
    {
        val = params['letter-spacing'];
        val = val.replace("px", "");
        $("#letterSpacing option[value='" + val + "']").attr('selected', 'selected');
        applyLetterSpacing(false, val, false);
    }

    if(params['word-spacing'])
    {
        val = params['word-spacing'];
        val = val.replace("px", "");
        $("#wordSpacing option[value='" + val + "']").attr('selected', 'selected');
        applyWordSpacing(false, val, false);
    }

    if(params['bold'] && params['bold'] == 1)
    {
        $('#style_b').css('background-position', '0 -22px');
        $('#contentText').css('font-weight', 'bold');
    }

    if(params['italic'] && params['italic'] == 1)
    {
        $('#style_i').css('background-position', '0 -22px');
        $('#contentText').css('font-style', 'italic');
    }

    if(params['uppercase'] && params['uppercase'] == 1)
    {
        $('#style_t').css('background-position', '0 -22px');
        $('#contentText').css('text-transform', 'uppercase');
    }

    if(params['color'])
    {
        $('#fontColorSelector').ColorPickerSetColor('#' + params['color']);
        $('#fontColorSelector').css('backgroundColor', '#' + params['color']);
        $('#fontColorHex').text(params['color']);
        applyFontColor(params['color']);
    }

    if(params['bg'])
    {
        $('#bgColorSelector').ColorPickerSetColor('#' + params['bg']);
        $('#bgColorSelector').css('backgroundColor', '#' + params['bg']);
        $('#bgColorHex').text(params['bg']);
        applyFontBG(params['bg']);
    }

    if(params['text-align'])
    {
        applyAlign(params['text-align'], false);
    }
}


function applyColumnsPadding(val)
{
    boxId = getActiveBox();
    $('#contentText_' + boxId + ' .contTable td').css("padding", "0 " + val + "px");
}


function setAdditionalStyles(par, val)
{
    boxId = getActiveBox();
    styles = $('#fieldWrap_' + boxId + " .fieldStyles").val();
    $('#fieldWrap_' + boxId + " .fieldStyles").val(styles + par + ":" + val + ";");
}


function saveCSS()
{
    $('#loader').show();

    allStyle = "";
    allTableStyle = "";

    $(".contentText").each(function(){
        id = "#" + $(this).attr('id');

        allStyle += $(id).attr('style') + "~~";

        tableStyle = $(id + " table td").attr('style');
        if(tableStyle) allTableStyle += tableStyle + "~~";
        else allTableStyle += "~~";
    });

    bodyBG = '#' + $('#bgColorHex').text();

    $.post("ajax.php", {request:'saveCSS', style:allStyle, tableStyle:allTableStyle, bodyBG:bodyBG},
        function(data){
        $('#loader').hide();
        $('#cssDialog textarea').val(data);
        $('#cssDialog').dialog('open');
        $('#loader').hide();
    });
}


function saveHTML()
{
    $('#loader').show();

    data = prepareHTMLData();
    bodyBG = '#' + $('#bgColorHex').text();

    $.post("ajax.php", {request:'saveHTML', style:data['allStyle'], tableStyle:data['allTableStyle'], html:data['allHTML'], bodyBG:bodyBG},
        function(data){
        $('#htmlDialog textarea').val(data);
        $('#htmlDialog').dialog('open');
        $('#loader').hide();
    });
}


function preview()
{
    $('#loader').show();

    data = prepareHTMLData();
    bodyBG = '#' + $('#bgColorHex').text();

    $.post("ajax.php", {request:'saveHTML', style:data['allStyle'], tableStyle:data['allTableStyle'], html:data['allHTML'], bodyBG:bodyBG},
        function(data){
        var win = window.open("Preview", "Preview", 'width=1000,height=400,toolbar=1,top=0,left=0,toolbar=no,location=yes,directories=no,menubar=no,scrollbars=yes,resizable=yes');
        with (win.document) {
            open("text/html", "replace");
            write(data);
            close();
        }
        $('#loader').hide();
    });
}


function prepareHTMLData()
{
    data = new Array();

    data['allStyle'] = "";
    data['allTableStyle'] = "";
    data['allHTML'] = "";

    $("#fieldsWrapper .contentText").each(function(){
        id = "#" + $(this).attr('id');
        boxId = id.replace("#contentText_", "");

        data['allStyle'] += $(id).attr('style');

        tmp = data['allStyle'];
        len = tmp.length;
        last = tmp.substring(len - 1, len);
        if(last != ';') data['allStyle'] += ';';

        width = $("#boxWrap_" + boxId).css('width');
        width = width.replace("px", "");
        width = width*1 + 22;

        data['allStyle'] += "width:" + width + "px;";
        data['allStyle'] += "~~";

        tableStyle = $(id + " table td").attr('style');
        if(tableStyle) data['allTableStyle'] += tableStyle + "~~";
        else data['allTableStyle'] += "~~";

        data['allHTML'] += $(id).html() + "[~~html~~]";
    });

    return data;
}


function fieldMouseover(obj)
{
    if(!$(obj).hasClass("fieldWrapActive"))
    {
        $(obj).addClass('fieldWrapOver');
    }
}


function fieldMouseout(obj)
{
    if(!$(obj).hasClass("fieldWrapActive"))
    {
        $(obj).removeClass('fieldWrapOver');
    }
}


function fieldClick(obj)
{
    if(!$(obj).hasClass("fieldWrapActive"))
    {
        $(obj).removeClass('fieldWrapOver');
        $('.fieldWrap').removeClass('fieldWrapActive');
        $(obj).addClass('fieldWrapActive');

        id = $(obj).attr('id');
        id = id.replace("fieldWrap_", "");
        applyActiveBox(id);
    }
}




