
//function imagewidget(element) {
    // TODO: Animate adding and removal
    // TODO: Disable checking of already associated topics
    // TODO: Disable search when cardinality constraints reached.
    // TODO: Mark as incomplete
    // TODO: Animate waiting for server
    // TODO: Handle error messages from server.

    // The imagewidget is almost identical to the filewidget, so we can just reuse the filewidget function.
    //WIDGETHANDLERS['filewidget'](element)
//}

function imageQueryKeydown(event) {
    if ( event.keyCode == 13 ) {
        imagesearch(event);
        return false;
    } 
}

function imagewidget(element) {
    // TODO: Animate adding and removal
    // TODO: Disable checking of already associated topics
    // TODO: Disable search when cardinality constraints reached.
    // TODO: Mark as incomplete
    // TODO: Animate waiting for server
    // TODO: Handle error messages from server.    
    $('li', element).each(associationline);
    $('input.search', element).click(imagesearch);
    $('input.query').keydown(imageQueryKeydown);               
    $('input.upload', element).click(openUpload);
    $('input.delete', element).hide();
    
    $('.uploadcontrols', element).find('.closer').show().click(closeUpload);
    
    
    $('.uploadcontrols', element).find('.new').change(onBrowseCtrlChanged);
    $('.uploadcontrols', element).find('.submit_new').click(uploadFile);
    
    
    //$('input.search', element).click(imagesearch);
    //$('input.create', element).click(createassociation).disable();
    $('.uploadcontrols', element).hide();
    //$('.associationscontrols',element).hide();
    $('.imgdesc', element).blur(saveDescription);
    $('.imgorder', element).blur(saveOrder);
	$('.imgorder', element).show();
}



function imagesearch(event, page, url) {
    //console.log(this, event, event.target);
    var widget = $(event.target).parents('.widget');
    var inner = $(event.target).parents('.inner');
    var form = $(event.target).parents('form').log();
    var archiveurl = url || $('.imagesearchurl').val();
    var loadingimg = widget.find("#loading");
    loadingimg.show();


    //page = page || 0;
    
    event.stopPropagation();
    event.preventDefault();


    var data = {};
    
    if ( !url || url.match(/pagesize/)===undefined) {
        data.pagesize = 12;
    }
    if (!url || url.match(/query:ustring:utf8/)===undefined) {
        data['query:ustring:utf8'] = widget.find('input.query').attr('value') || ''
    }

    
    imagegetJSON({  url : archiveurl
              , data: data
              , timeout: 10000
              , success: imagesearchSucceded
              , error: function (event)  {
                            humanMsg.displayMsg('Image search failed');
                            var loadingimg = widget.find("#loading");
                            loadingimg.hide();
                       }
              , context: widget.attr('id')      
            });
    return false;
}

function imagesearchSucceded(result, widget_id) {
    //console.log('success');
    var widget = $('#' + widget_id);
    var loadingimg = widget.find("#loading");
    loadingimg.hide();
    
    $('.associationscontrols', widget).hide();
    
    var inner = widget.find('.inner');  
    $('.imagesearch', widget).show();
    $('.closer', widget).click(closeImageSearch);
   
    var wizardserial = $('.topicserial').val();    
    storeWizardInfoInDOM(widget, wizardserial);            
 
    var searchlist = $('#imagelist_'+widget_id),
        images = result['images'],
        length = images.length,
        counter = 0,
        sorters = result['sorters'],
        pages = result['pages'];
        
        searchlist.show();
        searchlist.empty();
   
        searchlist.append('<tbody></tbody>');
    var tablewidth = 4, tablerow = 0;
    
    while (length  > counter) {
        var data = images[counter];
        
        if (tablerow == 0){
            var newrow = '<tr></tr>'
            var row = $(newrow).appendTo(searchlist);
        }
        
        searchimage = '<td class="imagesearch" id="' + data['stringserial'] + '">' +
                  '<a class="imagelink" ztm:serial="' + data['stringserial']  + '" href=""><img src="' + data['thumbnail'] + '" alt=""/><br>' +
                  '<span id="title_' + data['stringserial'] + '">' + data['fullname'] + '</span></a><br>' +                                            
                  '</td>';
        var image = $(searchimage).appendTo(row);
        image.data('imagedata', data);      
        //searchimage searchlist.append();

        counter ++;
        tablerow ++;
        
        if (tablerow == tablewidth){
            tablerow = 0;
        }

    }


    //ie hack - alter the size of the div so that the search will be visible
    $('.imagesearch', widget).attr('style', 'min-height:70em;');
    if ((navigator.appName).indexOf('Explorer') > 0){
        $('#image_search_pagination_bottom_' + widget_id).attr('style', 'margin-top: 46em;');
    }  
            
    //Add number of hits
    $('#image_search_searchinfo_' + widget_id).show();
    $('#image_search_searchinfo_' + widget_id).empty();
    $('#image_search_searchinfo_' + widget_id).append(result['text']);
    
    //display the sorters 
    $('#image_search_sorters_' + widget_id).show(); 
    $('#image_search_sorters_' + widget_id).empty(); 
    $('#image_search_sorters_' + widget_id).append("Sort by: ");
    counter = 0;
    length = sorters.length;
    while (length  > counter) {
        var data = sorters[counter];
        var sortlink = '<a class="clicklink ' + data['class'] + '" href="' + data['url'] + '" >' + data['sortindex'] + '</a>   ';
        $('#image_search_sorters_' + widget_id).append(sortlink);
        counter ++;
    }       
    
    //display the filters
    $('#image_search_filters_' + widget_id).show();        
    
    //Display pagination
    $('#image_search_pagination_' + widget_id).show();  
    $('#image_search_pagination_' + widget_id).empty(); 
    $('#image_search_pagination_bottom_' + widget_id).show();  
    $('#image_search_pagination_bottom_' + widget_id).empty();      
    counter = 0;
    length = pages.length;
    while (length  > counter) {
        var data = pages[counter];
        var pagelink = "";
        if (data['omit'] == false) {
            pagelink = '<a class="clicklink ' + data['class'] + '" href="' + data['url'] + '" title="' + data['title']+ '">' + data['name'] + '</a>   ';
        } else {
            pagelink = '<span class="' + data['class'] + '" title="' + data['title']+ '">' + data['name'] + '</span>   ';
        }
        $('#image_search_pagination_' + widget_id).append(pagelink);
        $('#image_search_pagination_bottom_' + widget_id).append(pagelink);
        counter ++;
    }          
    
    //enable the search again
   $('#image_query_'+widget_id).attr('disabled', false);  
   $('#searchbutton_'+widget_id).attr('disabled', false); 
   
   
   //add click event to the the different links
   $('.clicklink', widget).click(imageSearchAgain);   
   //$('.imagedetailslink', widget).click(showImageDetailsLightbox);   
   $('.imagelink', widget).click(addImage);   
   $('#image_query_' + widget_id).keydown(imageQueryKeydown);               
   $('#searchbutton_' + widget_id).click(imagesearch);               
}

function  imageSearchAgain(event) {
    event.stopPropagation();
    event.preventDefault();

    //console.log('searchAgain');

    var widget = $(event.target).parents('.widget'),
        widget_id = widget.attr('id'),
        url = $(event.target).attr('href');
                
    try {
        imagesearch(event, 0, url);
    }catch(e){
        return false;
    }
    return false;
}

function  closeImageSearch(event) {
    event.stopPropagation();
    event.preventDefault();

    //console.log('searchAgain');

    var widget = $(event.target).parents('.widget');
    
    $('.associationscontrols', widget).show();  
    $('.imagesearch', widget).hide();               

    return false;
}

function  addImage(event) {
    var hit = $(this),
        widget = hit.parents('.widget'),
        form = hit.parents('form'),
        data = {},
        operation = { 'operation' : 'createassociation'
                    , 'players': [hit.attr('ztm:serial')]
                    };
    data[widget.attr('ztm:marker')] = operation
    
    // If this widget is being used by the wizard, we must also make sure that we transfer the wizard-specific
    // context. This is stored in two hidden input-fields: "serial" and "step"    
    //addWizardInfoIfNeeded(data,widget);
    data['serial'] = $('.topicserial').val();   
    var loadingimg = widget.find("#loading");
    loadingimg.show();
    
    jQuery.postJSON({ url : form.attr('action')
                    , data: data
                    , timeout: 50000
                    , success: imageSelectSucceded
                    , error: function(event) { loadingimg.hide();humanMsg.displayMsg('Adding image failed');}
                    });
    event.stopPropagation();
    event.preventDefault();
    return false;
    
}

function imageSelectSucceded(result, status) {
    //$('.imagesearch', widget).hide();
    for (name in result) {
        var data = result[name];
        var widget = $('#' + name);
        //widget.find('.results').slideUp(200);
        widget.find('p.associationscontrols', widget).show();
        var loadingimg = widget.find("#loading");
        loadingimg.hide();
    }
    rebuildList(result);
}

function imagegetJSON(options) {
    
    options = jQuery.extend( { 'type': 'GET'
                             , 'contentType': 'application/x-www-form-urlencoded'
                             , 'processData': true 
                             , 'timeout': 10000
                             , 'dataType': 'json'
                             }
                           , options);

    options._error = options.error
    options.error = function (event) {
        //TODO: Handle other HTTP error codes like redirect.
        //console.log('errorhandler');
        if (event.readyState === 0) {
            // Timeout
            //console.log('Timeout', event);
            if (options.timeoutError)
                options.timeoutError(event, options.context);
            else if (options._error)
                options._error(event, options.context);
        } else if (event.status === 0) {
            //console.log('No answer', event);
            if (options.noreplyError) 
                options.noreplyError(event, options.context);
            else if (options._error)
                options._error(event, options.context);
        } else if (event.status === 404) {
            // Topic has been deleted
            //console.log('404', event);
            humanMsg.displayMsg('Error: The topic has been deleted.');
        } else if (event.status >= 500) {
            //console.log('error', event, options._error);
            if (options._error)
                options._error(event, options.context);
        } else {
            //console.log('errorhandler  got an unknown error!', event, options._error);
            if (options._error)
                options._error(event, options.context);
        }
        delete options.context;
        delete options.error;
        options.error = options._error;         
        return false;
      
    };
    options._success = options.success
    options.success = function (event) {
        options._success(event, options.context);
        delete options.context;
        delete options.success;
        options.success = options._success;
    };
    
    //TODO: Support difference between TIMEOUT, UNREACHABLE and SERVER ERROR
    //TODO: Use object literal as input.
    jQuery.ajax(options);
}

function saveDescription(event) {
    var hit = $(this),
        widget = hit.parents('.widget'),
        form = hit.parents('form'),
        elem = hit.parents('li'),
        data = {},
        operation = { 'operation' : 'adddescription'
                    , 'players': [elem.attr('ztm:serial')]
                    , 'desc': hit.val()
                    };
    data[widget.attr('ztm:marker')] = operation
    // If this widget is being used by the wizard, we must also make sure that we transfer the wizard-specific
    // context. This is stored in two hidden input-fields: "serial" and "step"    
    //addWizardInfoIfNeeded(data,widget);
    data['serial'] = $('.topicserial').val();   
    //var loadingimg = widget.find("#loading");
    //loadingimg.show();
    
    jQuery.postJSON({ url : form.attr('action')
                    , data: data
                    , timeout: 50000
                    , success: saveDescSucceded
                    , error: function(event) { humanMsg.displayMsg('Saving description failed');}
                    });
    event.stopPropagation();
    event.preventDefault();
    return false;
}

function saveDescSucceded(result, status) {
    //$('.imagesearch', widget).hide();
    /*for (name in result) {
        var data = result[name];
        var widget = $('#' + name);
        widget.find('p.associationscontrols', widget).show();
        var loadingimg = widget.find("#loading");
        loadingimg.hide();
    }
    rebuildList(result);*/
}

function saveOrder(event) {
    var hit = $(this),
        widget = hit.parents('.widget'),
        form = hit.parents('form'),
        elem = hit.parents('li'),
        data = {},
        operation = { 'operation' : 'addorder'
                    , 'players': [elem.attr('ztm:serial')]
                    , 'order': hit.val()
                    };
    data[widget.attr('ztm:marker')] = operation
    // If this widget is being used by the wizard, we must also make sure that we transfer the wizard-specific
    // context. This is stored in two hidden input-fields: "serial" and "step"    
    //addWizardInfoIfNeeded(data,widget);
    data['serial'] = $('.topicserial').val();   
    //var loadingimg = widget.find("#loading");
    //loadingimg.show();
    
    jQuery.postJSON({ url : form.attr('action')
                    , data: data
                    , timeout: 50000
                    , success: saveOrderSucceded
                    , error: function(event) { humanMsg.displayMsg('Saving copyright failed');}
                    });
	event.stopPropagation();
    event.preventDefault();
    return false;
}

function saveOrderSucceded(result, status) {
    //$('.imagesearch', widget).hide();
    /*for (name in result) {
        var data = result[name];
        var widget = $('#' + name);
        widget.find('p.associationscontrols', widget).show();
        var loadingimg = widget.find("#loading");
        loadingimg.hide();
    }
    rebuildList(result);*/
}

WIDGETHANDLERS['imagewidget'] = imagewidget

