//
// Add image gallery.
//
function add_gallery()
{
    var f = document.forms['form_add_gallery'];
    var block_title = f.block_title.value;
    var img_file = f.img_file.value;
   
    if (block_title == '' || img_file == '')
    {
        my_alert('all field are must');
        return false;
    }
    
    if ( ! is_image(img_file))
    {
        my_alert('you should select an image');
        return false;
    }

    $('#button_add_gallery').hide();
    $('#saving_add_gallery').show();
    f.submit();
    
    return false;
}

function on_change_add_gallery_form_file_field()
{
    var f = document.forms['form_add_gallery'];
    var block_title = f.block_title.value;
    var img_file = f.img_file.value;
   
    if (block_title != '' && img_file != '')
    {
        add_gallery();
    }
}

//
// Displays the link that adds an image to 
// the gallery.
//
function display_link_add_gallery_img(block_id)
{
    var num_gallery_imgs = $('#mblock_code_'+block_id+' .slideshow').children().size();
    
    if (num_gallery_imgs < MAX_NUM_GALLERY_IMGS)
    {
        $('.qq-upload-button').show();
        $('#button_add_gallery_img_disabled').hide();
    }

    else
    {
        $('.qq-upload-button').hide();
        $('#button_add_gallery_img_disabled').show();
    }

}

//
// Edit gallery.
//
function display_edit_gallery_form(block_id, type)
{
    document.forms['form_gallery'].block_id.value = block_id;
    document.forms['form_gallery'].block_title.value = $('#mblock_title_'+block_id).html();
    $('#gallery_type_'+type).attr('checked', 'checked');
    display_link_add_gallery_img(block_id);
    
    var uploader = new qq.FileUploader({
        element: document.getElementById('file_uploader'),
        action: get_url_action('ajax_add_gallery_img'),
        params: 
        {
            'page_id' : document.forms['form_gallery'].page_id.value,
            'block_id' : document.forms['form_gallery'].block_id.value
        },
        allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
        sizeLimit: 5 * MB, // max size
        minSizeLimit: 0,
        multiple: true,
        maxConnections: 3,
        debug: false,
        messages: {
            typeError: translate('You should select an image'),
            sizeError: translate('File is too large'),//+" {sizeLimit}.",
            minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
            emptyError: "{file} is empty, please select files again without it.",
            onLeave: translate('The files are being uploaded, if you leave now the upload will be cancelled.')            
        },
        showMessage: function(message){
            alert(message);
        },        
        template: '<div class="qq-uploader">' + 
                '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
                '<div class="qq-upload-button">העלאת תמונות</div>' +
                '<ul class="qq-upload-list"></ul>' + 
             '</div>',

        onSubmit: function(id, file_name)
        {
            var ext = parse_file_ext(file_name);
            
            if ( ! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext)))
            { 
                my_alert('you should select an image', '');
                return false;
            }
            
            $('#saving_add_gallery_img').show();
        },
        
        onComplete: function(id, file_name, response)
        {
            if (response === 'null')
            {
                my_alert('NULL response', '');
            }

            else if (response.error)
            {
                my_alert(response.error);
            }
            
            else if (parseInt(uploader._filesInProgress) == 0)
            {
                $('.qq-upload-list').html('');
                $('#saving_add_gallery_img').hide();
                display_gallery(block_id, response.block.code, response.block.lib_name_suffix);
                display_link_add_gallery_img(block_id);
            }
        },
        
        onCancel: function(id, file_name)
        {
            if (parseInt(uploader._filesInProgress) == 0)
            {
                $('#saving_add_gallery_img').hide();
            }
        }
    });    
    
    //
    // Set block ID at multiple file upload.
    // We use 'folder' input. Thus we need not set 'scriptData' parameter, which invokes problems.
    // We use delay, due to uploadify bug. 
    //
    $('#output-message').hide();
    
    //
    // Display gallery thumbnails.
    //
    display_gallery_tns(block_id);
}

//
// Updates image gallery title.
//
function update_gallery_details()
{
    set_form_field('form_gallery', 'action', 'ajax_update_gallery_data');
    var block_id = get_form_field('form_gallery', FLD_BLOCK_ID);
    var data = $("#form_gallery").serialize();  
    var code = "$('#edit_gallery_details').hide(200);";
    code += "update_block_title("+block_id+", %%%.title);";
    code += "display_gallery("+block_id+", %%%.code, %%%.lib_name_suffix);";
    ajax(data, code, "", "button_gallery_details", "saving_gallery_details");
    
    return false;
}

//
// Delete gallery.
//
function del_gallery()
{                  
    var f = document.forms['form_gallery'];
    var block_id = f.block_id.value;
    var block_title = f.block_title.value;
       
    if (confirm(translate('should I delete the gallery')+' '+block_title+'?'))
    {
        var data = 'action=ajax_del_gallery&'+FLD_BLOCK_ID+'='+block_id;
        var code = "close_modals();"; // close modal should come first - otherwise it did not work.
        code += "remove_block("+block_id+");"
        
        ajax(data, code, "", "button_del_gallery", "saving_del_gallery");
    }
    
    return false;
}

//
// Returns display of gallery images.
//
function gen_html_gallery(block_id, code, lib_name_suffix)
{
    var gallery_type, gallery_height, imgs;
    var small_imgs_wlib, big_imgs_wlib;
    var img, img_small_src, img_big_src, img_title, img_height, link_url, margin_top, link_target;
    var html, img_html;
    
    gallery_type = code.type;
    gallery_height = code.height;
    imgs = code.images;
    
    //alert(gallery_height);
    
    var is_slideshow = (gallery_type == GALLERY_TYPE_SLIDESHOW);
    
    //
    // Set gallery web-library.
    //
    small_imgs_wlib = get_block_wlib(block_id, lib_name_suffix) + SMALL_LIB_NAME;
    big_imgs_wlib = get_block_wlib(block_id, lib_name_suffix) + BIG_LIB_NAME;
    
    //
    // Set is-title flag.
    //
    var is_title = false;
    
    for (var ind in imgs)
    {
        if (imgs[ind]['title'] != '')
        {
            is_title = true;
        }
    }
    
    //
    // Generate HTML of gallery images.
    // 
    var html_imgs_pc = '';
    var html_imgs_hh = '';

    for (var ind in imgs)
    {
        img = imgs[ind]
        file_name = img['file_name'];
        img_title = img['title'];
        img_height = img['height'];
        link_url = img['link_url'];
        img_small_src = small_imgs_wlib + file_name;
        img_big_src = big_imgs_wlib + file_name;
        margin_top = Math.max(0, parseInt((gallery_height - img_height) / 2) - (is_title ? 25 : 0));
        
        if (link_url)
        {
            link_target = link_url.indexOf(INDEX_URL) == 0 ? '' : 'target="_blank"'; 
        }
        
        else
        {
            link_target = ''; 
        }
        
        img_title = decode_from_json(img_title);
        img_title = img_title.replace(/\\(['"])/g, "$1");
        
        slashes_title = quotes_to_html(img_title);
        
        if (is_slideshow)
        {
            html_imgs_pc += '<div class="box">';
            
                html_imgs_pc += '<p class="image">';
                
                    img_html = '<img style="margin-top: '+margin_top+'px" src="'+img_small_src+'" title="'+slashes_title+'" alt="'+slashes_title+'" ind="'+ind+'" link_url="'+link_url+'" align="center" valign="middle" />';
                     
                    if (link_url != '' && link_url != undefined)
                    {
                        html_imgs_pc += '<a href="'+link_url+'" '+link_target+'>' + img_html + '</a>';
                    }
                    
                    else
                    {
                        html_imgs_pc += img_html;
                    }
                
                html_imgs_pc += '</p>';
                
                if (is_title)
                {
                    html_imgs_pc += '<p class="image_title">&nbsp;<span id="img_'+ind+'">'+img_title+'</span>&nbsp;</p>';
                }

            html_imgs_pc += '</div>';
        }
        
        else if (gallery_type == GALLERY_TYPE_THUMBNAILS)
        {
            html_imgs_pc += (link_url != '' && link_url != undefined) ?
                '<a href="'+link_url+'" title="'+img_title+'" '+link_target+'>' :
                '<a class="gallery pc_only" rel="gallery_'+block_id+'" href="'+img_big_src+'" title="'+img_title+'">';
                html_imgs_pc += '<img src="'+img_small_src+'" alt="'+img_title+'" title="'+img_title+'" ind="'+ind+'" link_url="'+link_url+'" />';
            html_imgs_pc += '</a>';
        }

        html_imgs_hh += '<p class="small handheld_only">';
            html_imgs_hh += img_title+'<br>';
            html_imgs_hh += '<img src="'+img_big_src+'" ind="'+ind+'" link_url="'+link_url+'" />';
        html_imgs_hh += '</p>';
    }
    
    //
    // Return output.
    //
    if (is_title)
    {
        gallery_height += 25; // the height of image title, as set by CSS file.
    }

    html = is_slideshow ? 
        '<div class="slideshow pc_only" style="height: '+gallery_height+'px">' : 
        "<div class='gallery pc_only'>";
    html += html_imgs_pc;
    html += "</div>";
        
    //html += "<div class='gallery handheld_only'>"+html_imgs_hh+"</div>";
 
    return html;
}
       
//       
// Loads gallery thumbnail data to form.       
//       
function load_gallery_tn_data(id)
{
    document.forms['form_gallery'].img_title.value = $('#'+id).attr('src');    
}
                   
//                   
// Load form of edit gallery image.                   
//                   
function edit_gallery_img(li_obj, block_id, ind)
{
    $('#mblock_code_'+block_id).find('img').each(
        function()
        {   
            if ($(this).attr("ind") == ind)
            {
                var img_title = $(this).attr("title");
                var link_url = $(this).attr("link_url");
                
                if (link_url == 'undefined')
                {
                    link_url = '';
                }
                
                $('#edit_gallery_details').hide();
                $('#edit_img').show(200);

                li_obj.parent().children().removeClass('selected');
                li_obj.addClass('selected');

                document.forms['form_gallery'].img_title.value = img_title;
                document.forms['form_gallery'].img_link_url.value = link_url;
                document.forms['form_gallery'].img_ind.value = ind;
                location.href='#form_gallery';
            }
        });       
} 
                        
//
//  Displays gallery thumbnails.
//
function display_gallery_tns(block_id)
{           
    //
    // Display thumbnails.
    //
    var html = "<ul id='gtns_"+block_id+"' class='thumbnails'>"; // This ID is used to refer to it for sorting.

    $('#mblock_code_'+block_id).find('img').each(
        function()
        {   
            var src = $(this).attr("src");
            var ind = $(this).attr("ind");
            
            html += "<li ondblclick='edit_gallery_img($(this), "+block_id+", \""+ind+"\")'><img class='handle' id='"+ind+"' src='"+src+"' /></li>";
        }       
    );
    
    html += "</ul>";

    $('#gallery_thumbnails').html(html);

    //
    // make thumbnails sortable.
    // See: http://docs.jquery.com/UI/Sortable
    //
    $('#gtns_'+block_id).sortable(
    { 
        items: '.handle',
        opacity: 0.6,
        revert: true,
        containment: $('#form_gallery'), // assi - if I limit it to tn div ('#gtns_'+block_id), I cannot drag tn to the right edge.
        
        update : function () 
        {
            var inds = $('#gtns_'+block_id).sortable('toArray');                                                                   
            var data = 'action=ajax_update_gallery_imgs_order&'+FLD_BLOCK_ID+'='+block_id+'&img_inds='+inds;
            var code = "display_gallery("+block_id+", %%%.code, %%%.lib_name_suffix);";

            ajax(data, code, '');
        } 
    }); 
    
}

//
// Delete gallery image.
//
function del_gallery_img()
{
    var f = document.forms['form_gallery'];
    var block_id = f.block_id.value;
    var ind = f.img_ind.value;

    var data = 'action=ajax_del_gallery_img&'+FLD_BLOCK_ID+'='+block_id+'&img_ind='+ind;
    
    var code = "$('#edit_img').hide(); ";
    code += "if (%%% == 0) {hide_block("+block_id+"); close_modals();}"; 
    code += "else { ";
        code += "display_gallery("+block_id+", %%%.code, %%%.lib_name_suffix);";
        code += "display_link_add_gallery_img("+block_id+");";
        code += "}";

    ajax(data, code, '', 'button_del_gallery_img', 'saving_del_gallery_img');
}

//
// Update gallery image data.
//
function update_gallery_img_data()
{
    var f = document.forms['form_gallery'];
    var block_id = f.block_id.value;
    var ind = f.img_ind.value;
    var title = f.img_title.value;
    var esc_link_url = escape(f.img_link_url.value);
    
    f.img_title.value = title.replace('"', "''");
    
    f.action.value = 'ajax_update_gallery_img_data';
    
    var data = $("#form_gallery").serialize();  

    var code = "$('#edit_img').hide();";
    code += "display_gallery("+block_id+", %%%.code, %%%.lib_name_suffix);";
    
    ajax(data, code, '', 'button_edit_img', 'saving_edit_img');
}

//
// Displays gallery images.
//
function display_gallery(block_id, code_json, lib_name_suffix)
{
    var code = eval_json(code_json);
    var html = gen_html_gallery(block_id, code, lib_name_suffix);
    update_block_code(block_id, html);
    display_gallery_tns(block_id); 
    make_slideshow_and_gallery();
}

