//
// 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;
    }

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

//
// 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)
    {
        $('#button_add_gallery_img').show();
        $('#button_add_gallery_img_disabled').hide();
    }

    else
    {
        $('#button_add_gallery_img').hide();
        $('#button_add_gallery_img_disabled').show();
    }

}

//
// Edit gallery.
//
function display_edit_gallery_form(block_id, type)
{
    var f = document.forms['form_gallery'];
    f.block_id.value = block_id;
    f.block_title.value = $('#mblock_title_'+block_id).html();
    $('#gallery_type_'+type).attr('checked', 'checked');
    display_link_add_gallery_img(block_id);
    
    //
    // Set image upload through ajax.
    //
    // See http://valums.com/ajax-upload/
    //
    var upload_obj = new AjaxUpload($('#button_add_gallery_img'), 
    {
        action: get_url_action('ajax_add_gallery_img'),
        
        name: 'img_file',
        
        data: 
        {
            'page_id' : f.page_id.value,
            'block_id' : f.block_id.value
        },
    
        onSubmit: function(file, ext)
        {
            if ( ! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext)))
            { 
                my_alert('Only JPG, PNG or GIF files are allowed', '');
                return false;
            }
            
            $('#button_add_gallery_img').hide();
            $('#saving_add_gallery_img').show();
        },
        
        onComplete: function(file_name, response)
        {
            $('#button_add_gallery_img').show();
            $('#saving_add_gallery_img').hide();
            
            if (response === 'null')
            {
                my_alert('NULL response', '');
            }

            else
            {                    
                display_gallery(block_id, eval_json(response).code); // response is block data (json format).
                display_link_add_gallery_img(block_id);
            }
        }
    });
    
    //
    // 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);";
    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 = "hide_block("+block_id+");";
        code += "close_modals();"
        
        ajax(data, code, "", "button_del_gallery", "saving_del_gallery");
    }
    
    return false;
}

//
// Returns display of gallery images.
//
function gen_html_gallery(block_id, code)
{
    var gallery_type, gallery_height, imgs;
    var gallery_wlib, small_imgs_wlib, big_imgs_wlib;
    var img, img_small_src, img_big_src, img_title, img_height, link_url, margin_top;
    var html, img_html;
    
    gallery_type = code.type;
    gallery_height = code.height;
    imgs = code.images;
    
    //
    // Set gallery web-library.
    //
    if (IS_CLIENT && IS_SW_MODE)
    {
        gallery_wlib = document.forms['form_gallery'].gallery_wlib.value;
    }
    
    else
    {
        var is_home_page = (PAGE_LIB_NAME == 'home/');
        //gallery_wlib = is_home_page ? PAGE_LIB_NAME + GALLERY_LIB_NAME : GALLERY_LIB_NAME;
        gallery_wlib = SITE_URL + '/' + PAGE_LIB_NAME + GALLERY_LIB_NAME;
    }
    
    small_imgs_wlib = gallery_wlib + SMALL_LIB_NAME;
    big_imgs_wlib = gallery_wlib + BIG_LIB_NAME;    
    //
    // Set is-title flag.
    //
    var is_title = false;
    
    for (var ind in imgs)
    {
        if (imgs[ind]['title'] != '')
        {
            is_title = true;
        }
    }
    
    //
    // Update gallery height, based on 
    // existence of image title. 
    //
    if (is_title)
    {
        gallery_height += 25; // the height of image title, as set by CSS file.
    }
        
    //
    // Generate HTML of gallery div start.
    //
    if (gallery_type == GALLERY_TYPE_SLIDESHOW)
    { 
        html = '<div class="slideshow" style="height: '+gallery_height+'px">';
    }
    
    else if (gallery_type == GALLERY_TYPE_THUMBNAILS)
    {
        html = '<div class="gallery">';
    }
    
    //
    // Generate HTML of gallery images.
    // 
    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));
        
        img_title = utf8_decode(base64_decode(img_title));
        img_title = img_title.replace(/\\(['"])/g, "$1");
        
        slashes_title = quotes_to_html(img_title);
        
        if (gallery_type == GALLERY_TYPE_SLIDESHOW)
        {
            html += '<div class="box">';
            
                if (is_title)
                {
                    html += '<p class="image_title">&nbsp;<span id="img_'+ind+'">'+img_title+'</span>&nbsp;</p>';
                }
                
                                
                html += '<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 += '<a href="'+link_url+'">' + img_html + '</a>';
                    }
                    
                    else
                    {
                        html += img_html;
                    }
                
                html += '</p>';
                
            html += '</div>';
        }
        
        else if (gallery_type == GALLERY_TYPE_THUMBNAILS)
        {
            if (link_url != '' && link_url != undefined)
            {
                html += '<a href="'+link_url+'" title="'+img_title+'" target="_blank">';
                    html += '<img src="'+img_small_src+'" alt="'+img_title+'" title="'+img_title+'" ind="'+ind+'" link_url="'+link_url+'" />';
                html += '</a>';
            }
            
            else
            {
                html += '<a class="gallery" rel="gallery_'+block_id+'" href="'+img_big_src+'" title="'+img_title+'">';
                    html += '<img src="'+img_small_src+'" alt="'+img_title+'" title="'+img_title+'" ind="'+ind+'" link_url="'+link_url+'" />';
                html += '</a>';
            }
        }
    }
    
    //
    // Generate HTML of gallery div end.
    //
    html += '</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);";

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

//
// Delete gallery image.
//
function del_gallery_img()
{
    if (confirm(translate('should I delete the image')))
    {
        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);";
            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);";
    
    ajax(data, code, '', 'button_edit_img', 'saving_edit_img');
}

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