/**** 
   Kick off the main handler
*/
(function($){
  run_builder = function() {
    /*set defaults*/
    set_sign_size();
    set_sign_pictograms();
    set_text_color();
    set_text();

    /*draw sign*/
    draw_sign();

    /*add watchers*/
    watch_style();
    watch_cat();
    watch_size();
    watch_text();
    watch_text_color();
    watch_header();
    watch_position();
    $('#upload_file').fancybox();
    $('#json_errors').hide();

    $('#upload_form').bind('submit', function(e) {
        e.preventDefault();
        $(this).ajaxSubmit({
            'dataType':'html',
            'success': function(data) {
                obj = $.parseJSON(data);
                if(obj.errors)
                {
                    $('#json_errors').show().text(obj.errors.image);
                }
                else
                {
                    $.fancybox.close();
                    $('input[name="sign_pictogram"]').val(obj.file);
                    draw_sign();
                }
                    
            }
        });
    });

  };
})(jQuery);

/**** 
  When they change the style set the relevant size options 
*/
(function($){
  watch_style = function() {

    $('select[name=sign_style]').change( function() {
        set_sign_size();
        set_header();
        set_text_color();
        if($(this).val() == 'custom')
        {
            $('input[name="sign_pictogram"]').val('');
            $('#sign_pictograms ul li img').unbind('click');
            $('#sign_pictograms ul li img').css({'cursor':'default'});
            $($('select[name=sign_size] option').get().reverse()).each(function(idx) {
                if($(this).val() == '200mm x 300mm' || $(this).val() == '300mm x 400mm' || $(this).val() == '450mm x 600mm')
                {
                    $(this).attr('selected','selected');
                }
            });
            $('#custom_pictograms').show();
            $('#custom_pictogram_position').show();
            $('#sign_pictogram').hide();
        }
        else
        {
            $('#custom_pictograms').hide();
            $('#custom_pictogram_position').hide();
            $('#sign_pictogram').show();
            $('input[name="sign_pictogram"]').val($('.pic_selected').attr('title'));
            if($(this).val() == 'portrait')
            {
                $($('select[name=sign_size] option').get().reverse()).each(function(idx) {
                    if($(this).val() == '200mm x 200mm' || $(this).val() == '200mm x 250mm' || $(this).val() == '200mm x 300mm' || $(this).val() == '300mm x 400mm' || $(this).val() == '400mm x 400mm' || $(this).val() == '450mm x 600mm')
                    {
                        $(this).attr('selected','selected');
                    }
                });
            }
            else
            {
                $($('select[name=sign_size] option').get().reverse()).each(function(idx) {
                    if($(this).val() == '300mm x 150mm' || $(this).val() == '400mm x 150mm' || $(this).val() == '600mm x 200mm')
                    {
                        $(this).attr('selected','selected');
                    }
                });
            }
        }
        draw_sign();
    });


  };
})(jQuery);

/**** 
  set sign size according to style
*/
(function($){
  set_sign_size = function() {

    $('select[name=sign_size] option').hide();

    style = $('select[name=sign_style]').val();

    if (style == "")
        return;

    if (style == "custom")
    {
        $($('select[name=sign_size] option').get().reverse()).each(function(idx) {
            if($(this).val() == '200mm x 300mm' || $(this).val() == '300mm x 400mm' || $(this).val() == '450mm x 600mm')
            {
                $(this).show();
            }
        });
    }
    else if (style == "portrait") 
    {
        $($('select[name=sign_size] option').get().reverse()).each(function(idx) {
            sizes = $(this).val().split(' x ');
            width = parseInt(sizes[0].substring(0,sizes[0].length-2));
            height = parseInt(sizes[1].substring(0,sizes[1].length-2));
            if(width <= height)
            {
                $(this).show();
            }
        });
    }
    else if (style == "landscape")
    {
        $($('select[name=sign_size] option').get().reverse()).each(function(idx) {
            sizes = $(this).val().split(' x ');
            width = parseInt(sizes[0].substring(0,sizes[0].length-2));
            height = parseInt(sizes[1].substring(0,sizes[1].length-2));
            if(width > height)
            {
                $(this).show();
            }
        });
    }
  };
})(jQuery);

/**** 
  watch size and redraw sign if necessary
*/
(function($){
  watch_size = function() {

    $('select[name="sign_size"]').change(function() {
        draw_sign();
    });

  };
})(jQuery);

/* watch header redraw if changed */
(function($){
  watch_header = function() {

    $('select[name="sign_header"]').change(function() {
        draw_sign();
    });

  };
})(jQuery);

/* watch position redraw if changed */
(function($){
  watch_position = function() {

    $('select[name="custom_pictogram_position"]').change(function() {
        draw_sign();
    });

  };
})(jQuery);

/**** 
  set header and pictograms, only certain styles get a header
*/
(function($){
  set_header = function() {

    style = $('select[name=sign_style]').val();

    if (style == "")
        return;

    $('select[name=sign_header]').attr("disabled", false);
    $('select[name=sign_category]').attr("disabled", false);
    $('select[name=sign_pictogram]').attr("disabled", false);

    if (style != "custom")
    {
        $('select[name=sign_header]').attr("disabled", true);
        set_sign_pictograms();
    }
    else
    {
        $('select[name=sign_category]').attr("disabled", true);
    }
  };
})(jQuery);

/**** 
  When they change the pictogram category set the relevant cat options 
*/
(function($){
  watch_cat = function() {

    $('select[name=sign_category]').change( function() {
        set_sign_pictograms();
    });

  };
})(jQuery);

/****
  Watch text
*/
(function($){
  watch_text = function() {
    $('input[name^="sign_text_"]').keyup( function() {
        i = parseInt($(this).attr('name').substr(10));
        if($(this).val() == '')
        {
            $('input[name^="sign_text_"]').each(function(idx) {
                if(i <= (idx + 1))
                {
                    $(this).val($('input[name^="sign_text_' + (idx + 2) + '"]').val())
                    if($('input[name^="sign_text_' + (idx + 2) + '"]').val() == '')
                    {
                        $('input[name^="sign_text_' + (idx + 2) + '"]').prop('disabled','true');
                    }
                }
            });
        }
        else
        {
            $('input[name^="sign_text_' + (i + 1) + '"]').removeProp('disabled');
        }
        draw_sign();
    });

  };
})(jQuery);

(function($) {
  set_text = function() {
     $('input[name^="sign_text_"]').each(function(idx) {
        if(idx != 0 && $(this).val() == '' && $('input[name^="sign_text_' + idx + '"]').val() == '')
        {
            $(this).prop('disabled','true');
        }
     });
  };
})(jQuery);

/**** 
  When they change the pictogram category set the relevant cat options and attach event to select pic 
*/
(function($){
  set_sign_pictograms = function() {

    cat = $('select[name=sign_category]').val();

    if (cat == "")
        return;

    $('#sign_pictograms ul').empty();
    $('#sign_pictograms ul li img').unbind('click');
    $('#sign_pictograms ul li img').css({'cursor':'default'});
    
    if($('select[name="sign_style"]').val() != 'custom')
    {
        $('#sign_pictograms').show();
        $('#custom_pictograms').hide();
        $('#custom_pictogram_position').hide();
        $.getJSON('/signimages/' + cat, function(data) {
            width = parseInt(data.json_count) * 58;
            $('#sign_pictograms ul').css( { 'width': width + 'px' } );
            $.each(data.json_files,function(key,val) {
                selected = '';
                title = val.split('/').pop().split('.').shift().replace(/_/, ' ');
                if(key == 0)
                {
                    selected = 'pic_selected';
                }
                $('#sign_pictograms ul').append(
                    $("<li></li>").append(
                        $('<img />').attr('src',val)
                                    .attr('title',title)
                                    .addClass(selected)
                                    .click(function() {
                                        img_src = val;
                                        $(this).parent().siblings('li').children('img').removeClass('pic_selected');
                                        $(this).addClass('pic_selected');
                                        $('input[name="sign_pictogram"]').val($('.pic_selected').attr('title'));
                                        draw_sign();
                                    })
                    )
                );
            });
            if($('select[name="sign_style"]').val() != 'custom')
            {
                $('input[name="sign_pictogram"]').val($('.pic_selected').attr('title'));
            }
            if($('select[name=sign_style]').val() == 'custom')
            {
                $('#sign_pictograms ul li img').unbind('click');
                $('#sign_pictograms ul li img').css({'cursor':'default'});
            }
            draw_sign();
        });
    }
    else
    {
        $('#sign_pictograms').hide();
        $('#custom_pictograms').show();
        $('#custom_pictogram_position').show();

    }

  };
})(jQuery);

/****
  Watch color
*/
(function($){
  watch_text_color = function() {

    $('select[name^="sign_text_color"]').change( function() {
        draw_sign();
    });

  };
})(jQuery);

(function($){
  set_text_color = function() {

    style = $('select[name=sign_style]').val();

    if (style == "")
        return;

    $('select[name=sign_header]').attr("disabled", false);
    $('select[name=sign_category]').attr("disabled", false);
    $('select[name=sign_text_color]').attr("disabled", false);

    if (style != "custom")
    {
        $('select[name=sign_header]').attr("disabled", true);
        $('select[name=sign_text_color]').attr("disabled", true);
    }
    else
    {
        $('select[name=sign_category]').attr("disabled", true);
    }
  };
})(jQuery);


/**** 
  Draw sign from current settings
*/
(function($){
  draw_sign = function() {

    //reset contents
    $('#notice_pic').empty().attr('style','');
    $('#notice_text').empty().attr('style','');

    style = $('select[name="sign_style"]').val();

    size = $('select[name="sign_size"]').val();

    if(size == '100mm x 100mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(10.40);
        }
        else
        {
            $('input[name="price"]').val(13.65);
        }
    }
    else if(size == '150mm x 200mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(12.70);
        }
        else
        {
            $('input[name="price"]').val(16.20);
        }
    }
    else if(size == '150mm x 300mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(18.80);
        }
        else
        {
            $('input[name="price"]').val(22.00);
        }
    }
    else if(size == '300mm x 150mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(18.80);
        }
        else
        {
            $('input[name="price"]').val(22.00);
        }
    }
    else if(size == '150mm x 400mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(23.20);
        }
        else
        {
            $('input[name="price"]').val(25.60);
        }
    }
    else if(size == '400mm x 150mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(23.20);
        }
        else
        {
            $('input[name="price"]').val(25.60);
        }
    }
    else if(size == '150mm x 450mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(24.60);
        }
        else
        {
            $('input[name="price"]').val(26.40);
        }
    }
    else if(size == '200mm x 200mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(15.60);
        }
        else
        {
            $('input[name="price"]').val(18.10);
        }
    }
    else if(size == '200mm x 250mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(18.20);
        }
        else
        {
            $('input[name="price"]').val(21.40);
        }
    }
    else if(size == '200mm x 300mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(19.00);
        }
        else
        {
            $('input[name="price"]').val(23.20);
        }
    }
    else if(size == '200mm x 600mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(31.80);
        }
        else
        {
            $('input[name="price"]').val(42.30);
        }
    }
    else if(size == '600mm x 200mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(31.80);
        }
        else
        {
            $('input[name="price"]').val(42.30);
        }
    }
    else if(size == '250mm x 850mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(52.00);
        }
        else
        {
            $('input[name="price"]').val(70.50);
        }
    }
    else if(size == '300mm x 400mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(25.30);
        }
        else
        {
            $('input[name="price"]').val(33.80);
        }
    }
    else if(size == '300mm x 600mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(33.70);
        }
        else
        {
            $('input[name="price"]').val(45.60);
        }
    }
    else if(size == '400mm x 400mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(89.60);
        }
        else
        {
            $('input[name="price"]').val(36.20);
        }
    }
    else if(size == '450mm x 600mm')
    {
        if($('select[name="sign_mounting_type"]').val() == 'Wall Mounting')
        {
            $('input[name="price"]').val(49.10);
        }
        else
        {
            $('input[name="price"]').val(68.90);
        }
    }

    sizes = size.split(' x ');

    width = parseInt(sizes[0].substring(0,sizes[0].length-2));
    height = parseInt(sizes[1].substring(0,sizes[1].length-2));

    ratio = height/width;

    sign_height = Math.ceil($('#sign').width() * ratio);

    $('#sign').css( { 'height': sign_height + 'px' } );
    $('#notice_content').css( { 'height': sign_height + 'px' } );

    /*set text and background color */
    backgrd_color = '';
    text_color = '';
    if(style != 'custom')
    {
        if($('select[name="sign_category"]').val() == 'Order')
        {
            backgrd_color = '#D90033';
            text_color = '#FFFFFF';
        }
        else if($('select[name="sign_category"]').val() == 'Warning')
        {
            backgrd_color = '#FFFF00';
            text_color = '#000000';
        }
        else if($('select[name="sign_category"]').val() == 'Info')
        {
            backgrd_color = '#0033E3';
            text_color = '#FFFFFF';
        }
        else if($('select[name="sign_category"]').val() == 'Safety')
        {
            backgrd_color = '#02C400';
            text_color = '#FFFFFF';
        }
        else
        {
            backgrd_color = '#FFFFFF';
            text_color = '#000000';
        }
    }
    else
    {
        text_color = $('select[name="sign_text_color"]').val();
        backgrd_color = '#FFFFFF';
    }
    $('#notice_text').css({'background-color':backgrd_color,'height':height,'margin':'0px 20px 20px 20px'});

    if(style == 'custom')
    {
        custom(text_color);
    }
    else if(style == 'portrait')
    {
        portrait(text_color);
    }
    else
    {
        landscape(text_color);
    }

  };
})(jQuery);

/**** 
  Draw custom
*/
(function($){
  custom = function(text_color) {
    img_height = '';
    height = $('#notice_content').height();

    //append image if available
    if($('input[name="sign_pictogram"]').val())
    {
        img_height = Math.ceil(height/3);
        $('#notice_pic').css({'height':img_height + 'px'}).append($('<img>').attr({'src':$('input[name="sign_pictogram"]').val()}));
        if($('select[name="custom_pictogram_position"]').val() == 'centre')
        {
            $('#notice_pic img').css({'margin':'auto','display':'block'});
        }
        else
        {
            $('#notice_pic img').css({'float':$('select[name="custom_pictogram_position"]').val()});
        }
        $('#notice_pic').append($('<div>/div>').addClass('clear'));
    }
    
    if($('select[name="sign_header"]').val() != 'No Header')
    {
            $('#notice_pic').append($('<h1></h1>').html($('select[name="sign_header"]').val()).css({'text-align':'center','font-size':'30px'}));
            $('#notice_pic img').css({'height':(img_height - $('#notice_pic h1').height()) + 'px'});
    }

    if(!$('input[name="sign_pictogram"]').val())
    {
        img_height = $('#notice_pic').height();
    }
    
    text_height = (Math.ceil(height - img_height) - 20) + 'px';

    $('#notice_text').css({'height':text_height,'margin':'0px 20px 20px 20px'});
    count = 0;
    $('input[name^="sign_text_"]').each(function(i) {
        if($(this).val())
        {
            count += 1;
            $('#notice_text').append($('<p></p>').html($(this).val()));
        }
    });
    $('#notice_text p').css({
        'height': Math.ceil($('#notice_text').height() / count) + 'px',
        'text-align':'center',
        'padding':'0px',
        'line-height': Math.ceil($('#notice_text').height() / count) + 'px',
        'color':text_color,
        'width':'100%',
        'font-size':'20px'
    });
  };
})(jQuery);

/**** 
  Draw portrait
*/
(function($){
  portrait = function(text_color) {
    dims = Math.ceil($('#sign').height() / 3);
    left = Math.ceil( ($('#sign').width() - dims) / 2 ) + 'px';
    height = (Math.ceil($('#sign').height() - dims - 20)) + 'px';
    dims = dims + 'px';
    $('#notice_pic').append($('<img>')).css({'height':dims,'width':dims,'position':'relative','left':left});
    $('#notice_pic img').css({'height':dims,'width':dims}).attr({'src':$('.pic_selected').attr('src'),'title':$('.pic_selected').attr('title')});
    $('#notice_text').css({'height':height,'margin':'0px 20px 20px 20px'});
    count = 0;
    $('input[name^="sign_text_"]').each(function(i) {
        if($(this).val())
        {
            count += 1;
            $('#notice_text').append($('<p></p>').html($(this).val()));
        }
    });
    $('#notice_text p').css({
        'height': Math.ceil($('#notice_text').height() / count) + 'px',
        'text-align':'center',
        'padding':'0px',
        'line-height': Math.ceil($('#notice_text').height() / count) + 'px',
        'color':text_color,
        'width':'100%',
        'font-size':'20px',
        'overflow':'hidden'
    });
  };
})(jQuery);

/**** 
  Draw landscape
*/
(function($){
  landscape = function(text_color) {
    dims = Math.ceil($('#sign').height());
    width = (Math.ceil($('#sign').width() - dims - 10)) + 'px';
    height = ($('#sign').height() - 10 )+ 'px';
    dims = dims + 'px';
    $('#notice_pic').append($('<img>').attr('src',$('.pic_selected').attr('src'))).css({'height':dims,'width':dims,'position':'relative','float':'left'});
    $('#notice_pic img').css({'height':dims,'width':dims});
    $('#notice_text').css({'width':width,'height':height,'margin':'5px 5px 5px 5px','position':'relative', 'float':'left'});
    count = 0;
    $('input[name^="sign_text_"]').each(function(i) {
        if($(this).val())
        {
            count += 1;
            $('#notice_text').append($('<p></p>').html($(this).val()));
        }
    });
    $('#notice_text p').css({
        'height': Math.ceil($('#notice_text').height() / count) + 'px',
        'text-align':'center',
        'padding':'0px',
        'line-height': Math.ceil($('#notice_text').height() / count) + 'px',
        'color':text_color,
        'width':'100%',
        'font-size':'10px',
        'overflow':'hidden'
    });
  };
})(jQuery);

