/**
 * Осуществляет поиск по указанному ключевому слову, страница перенаправляется на результаты поиска.
 * Если ссылка нажата в диалоговом окне (например, в окне просмотра материала), то окно закрывается.
 * @param keyword слово, по которому осуществляется поиск
 */
function searchByKeyword(keyword) {
    var query = keyword;

    var w = window;
    if (window.opener) {
        w = window.opener;
        window.close();
    }


    if (query.length>0) {
        w.location.href = context+"/search.html?query="+query;
    }
}

function searchByKeywords() {
    var query = '';
    $("input[name='imagekeyword']:checked:enabled").each(
        function(index) {
            query+=this.value+' ';
        }
    );

    var w = window;
    if (window.opener) {
        w = window.opener;
        window.close();
    }


    if (query.length>0) {
        w.location.href = context+"/search.html?query="+query;
    }
}



/**
 * callback функция для листания по страницам результатов поиска
 * @param hash
 */
function searchPageLoad(hash) {
    // alert("pageload: " + hash);
    // hash doesn't contain the first # character.
    if(hash) {
        // restore ajax loaded state
        if($.browser.msie) {
            // jquery's $.load() function does't work when hash include special characters like aao.
            hash = encodeURIComponent(hash);
        }
        var pattern = /^[0-9]+$/gi;
        if (hash.match(pattern)) {
            searchFragment(currentSearchPageUrl+'&page='+hash);
        }
    } else {
        currentSearchPageUrl = hash;
    }
}
function searchFragment(query) {
    $("body").scrollTop(0);
    $('.content .detail-pane').html("").html("<img src='/img/ajax-loader.gif' width='32' height='32' alt='Loading'>");
    $(".content .detail-pane").load(context+"/searchfragment.html?"+query, {}, function() {
        //$("body").scrollTop(0);
        lightboxWindow.updateImageOperations();
        countAjaxPageHit(context+"/search.html?"+query);
    });
}

function search() {
    var query = encodeURIComponent($('#search-query').attr('value'));

    if (query=='') {
        $('#search-query').focus();
        return;
    }

    var useEditorial = $('#editorial-search-rubric').attr('checked');
    var useCreative = $('#creative-search-rubric').attr('checked');
    var useFootage = $('#footage-search-rubric').attr('checked');
    var useSearchFilters = $('#use-filters-switch').attr('checked');

    if (!$('#rm-search-license').attr('checked') && !$('#rf-search-license').attr('checked')) {
        useCreative = false;
    }
    else if ($('#rm-search-license').attr('checked') || $('#rf-search-license').attr('checked')) {
        useCreative = true;
    }
    var useRMLicense = $('#rm-search-license').attr('checked') && useCreative;
    var useRFLicense = $('#rf-search-license').attr('checked') && useCreative;
    var useRRFootageLicense = $('#rr-footage-search-license').attr('checked') && useFootage;
    var useRFFootageLicense = $('#rf-footage-search-license').attr('checked') && useFootage;
    var useTVDataFootageLicense = $('#tvdata-footage-search-license').attr('checked') && useFootage;

    if (useFootage) {
        useEditorial = false;
        useCreative = false;
        useRMLicense = false;
        useRFLicense = false;
    }

    var searchUrl = context+"/search.html?query="+query;
    if (!(useCreative && useEditorial)) {
        if (useCreative) {
            searchUrl+='&f=creative';
        }
        else if (useEditorial) {
            searchUrl+='&f=editorial';
        }
        else if (useFootage) {
            searchUrl+='&f=footage';
        }
        else {
            return;//todo сделать выбор рубрики
        }
    }

    if (useCreative) {

        if (!(useRMLicense && useRFLicense)) {
            if (useRMLicense) {
                searchUrl+='&l=rm';
            }
            else if (useRFLicense) {
                searchUrl+='&l=rf';
            }
        }
    }

    if (useEditorial) {
        if ($('#editorial-search-date').val()!='any') {
            searchUrl+='&eda='+$('#editorial-search-date').val();
        }
    }

    if (useFootage) {
        if (useRRFootageLicense) {
            searchUrl+='&l=rrf';
        }
        if (useRFFootageLicense) {
            searchUrl+='&l=rff';
        }
        if (useTVDataFootageLicense) {
            searchUrl+='&l=tvdata';
        }
    }

    if (useSearchFilters) {
        var selectedEoTopics = $('[id^="eo-filter-topic"]:checked').size();
        var selectedRfTopics = $('[id^="rf-filter-topic"]:checked').size();
        var selectedRmTopics = $('[id^="rm-filter-topic"]:checked').size();
        var selectedRRFootageTopics = $('[id^="rr-footage-filter-topic"]:checked').size();
        var selectedRFFootageTopics = $('[id^="rf-footage-filter-topic"]:checked').size();
        var selectedTVDataFootageTopics = $('[id^="tvdata-footage-filter-topic"]:checked').size();
        var eoTopics = $('[id^="eo-filter-topic"]').size();
        var rmTopics = $('[id^="rm-filter-topic"]').size();
        var rfTopics = $('[id^="rf-filter-topic"]').size();
        var rrFootageTopics = $('[id^="rr-footage-filter-topic"]').size();
        var rfFootageTopics = $('[id^="rf-footage-filter-topic"]').size();
        var tvdataFootageTopics = $('[id^="tvdata-footage-filter-topic"]').size();

        if (useRMLicense && (selectedRmTopics < rmTopics)) {
            $('[id^="rm-filter-topic"]:checked').each(function() {
               searchUrl+='&c='+this.value;
            });
        }
        if (useRFLicense && (selectedRfTopics < rfTopics)) {
            $('[id^="rf-filter-topic"]:checked').each(function() {
               searchUrl+='&c='+this.value;
            });
        }
        if (useEditorial && (selectedEoTopics < eoTopics)) {
            $('[id^="eo-filter-topic"]:checked').each(function() {
               searchUrl+='&c='+this.value;
            });
        }
        if (useRRFootageLicense && (selectedRRFootageTopics < rrFootageTopics)) {
            $('[id^="rr-footage-filter-topic"]:checked').each(function() {
               searchUrl+='&c='+this.value;
            });
        }
        if (useRFFootageLicense && (selectedRFFootageTopics < rfFootageTopics)) {
            $('[id^="rf-footage-filter-topic"]:checked').each(function() {
               searchUrl+='&c='+this.value;
            });
        }
        if (useTVDataFootageLicense && (selectedTVDataFootageTopics < tvdataFootageTopics)) {
            $('[id^="tvdata-footage-filter-topic"]:checked').each(function() {
               searchUrl+='&c='+this.value;
            });
        }
    }

    //orientation: collect all checkboxes with name='o'
    $('input[name="o"]:checked').each(function() {
       searchUrl+='&o='+this.value;
    });



    window.location.href = searchUrl;

}

function onCreativeChange() {
    var checked = $('#creative-search-rubric').attr('checked');
    updateCreative(checked);
    onRMChange($('#rm-search-license').get(0));
    onRFChange($('#rf-search-license').get(0));
    updateFootage(false);
}

function updateCreative(flag) {
    $('#creative-search-rubric').attr({checked : flag});
    $('#rm-search-license').attr({checked : flag});
    $('#rf-search-license').attr({checked : flag});
    onRMChange($('#rm-search-license').get(0));
    onRFChange($('#rf-search-license').get(0));
}

function onEditorialChange(input) {
    updateEditorial(input.checked);
    updateFootage(false);
}
function updateEditorial(flag) {
    $('#editorial-search-rubric').attr('checked', flag);
    $('#editorial-search-rubric2').attr('checked', flag);
    $('[id^="eo-filter-topic"]').attr({disabled : !$('#editorial-search-rubric').attr('checked')});
}

function onRMChange(input) {
    $('#rm-search-license').attr('checked', input.checked);
    $('#rm-search-license2').attr('checked', input.checked);
    $('[id^="rm-filter-topic"]').attr({disabled : !$('#rm-search-license').attr('checked')});
}

function onRFChange(input) {
    $('#rf-search-license').attr('checked', input.checked);
    $('#rf-search-license2').attr('checked', input.checked);
    $('[id^="rf-filter-topic"]').attr({disabled : !$('#rf-search-license').attr('checked')});
}

function onFootageChange(input) {
    updateFootage(input.checked);
    updateEditorial(false);
    updateCreative(false);
}

function updateFootage(flag) {
    $('#footage-search-rubric').attr('checked', flag);
    $('#footage-search-rubric2').attr('checked', flag);
    //обновляем галочки у лицензий (rr, rf, tvdata)
    $('#rr-footage-search-license').attr({checked : flag});
    $('#rf-footage-search-license').attr({checked : flag});
    $('#tvdata-footage-search-license').attr({checked : flag});
    onRRFootageChange($('#rr-footage-search-license').get(0));
    onRFFootageChange($('#rf-footage-search-license').get(0));
    onTVDataFootageChange($('#tvdata-footage-search-license').get(0));

    $('[id^="footage-filter-topic"]').attr({disabled : !$('#footage-search-rubric').attr('checked')});
}


function onRRFootageChange(input) {
    $('#rr-footage-search-license').attr('checked', input.checked);
    $('#rr-footage-search-license2').attr('checked', input.checked);
    $('[id^="rr-footage-filter-topic"]').attr({disabled : !$('#rr-footage-search-license').attr('checked')});
}

function onRFFootageChange(input) {
    $('#rf-footage-search-license').attr('checked', input.checked);
    $('#rf-footage-search-license2').attr('checked', input.checked);
    $('[id^="rf-footage-filter-topic"]').attr({disabled : !$('#rf-footage-search-license').attr('checked')});
}

function onTVDataFootageChange(input) {
    $('#tvdata-footage-search-license').attr('checked', input.checked);
    $('#tvdata-footage-search-license2').attr('checked', input.checked);
    $('[id^="tvdata-footage-filter-topic"]').attr({disabled : !$('#tvdata-footage-search-license').attr('checked')});
}


function onRMFilterChange() {
    $('[id^="rm-filter-topic"]').attr("checked", $('#rm-filter-common').attr('checked'));
}

function selectAllRM() {
    if (!$('#rm-search-license').attr('checked')) {
        return;
    }
    $('[id^="rm-filter-topic"]').attr("checked", true);
}

function deselectAllRM() {
    if (!$('#rm-search-license').attr('checked')) {
        return;
    }
    $('[id^="rm-filter-topic"]').attr("checked", false);
}

function onRMFilterItemsChange() {
    var selectedAll = $('#rm-filter-collections>option[selected!=false]').size() == $('#rm-filter-collections>option').size();
    $('#rm-filter-common').attr({checked: selectedAll});
}

function onRFFilterChange() {
    $('[id^="rf-filter-topic"]').attr("checked", $('#rf-filter-common').attr('checked'));
}

function selectAllRF() {
    if (!$('#rf-search-license').attr('checked')) {
        return;
    }
    $('[id^="rf-filter-topic"]').attr("checked", true);
}

function deselectAllRF() {
    if (!$('#rf-search-license').attr('checked')) {
        return;
    }
    $('[id^="rf-filter-topic"]').attr("checked", false);
}

function onRFFilterItemsChange() {
    var selectedAll = $('#rf-filter-collections>option[selected!=false]').size() == $('#rf-filter-collections>option').size();
    $('#rf-filter-common').attr("checked", selectedAll);
}

function toggleAllEO() {
    $('[id^="eo-filter-topic"]').attr("checked", $('#eo-filter-common').attr('checked'));
}

function selectAllEO() {
    if (!$('#editorial-search-rubric').attr('checked')) {
        return;
    }
    $('[id^="eo-filter-topic"]').attr("checked", true);
}

function deselectAllEO() {
    if (!$('#editorial-search-rubric').attr('checked')) {
        return;
    }
    $('[id^="eo-filter-topic"]').attr("checked", false);
}

function selectAllRRFootage() {
    if (!$('#rr-footage-search-license').attr('checked')) {
        return;
    }
    $('[id^="rr-footage-filter-topic"]').attr("checked", true);
}

function deselectAllRRFootage() {
    if (!$('#rr-footage-search-license').attr('checked')) {
        return;
    }
    $('[id^="rr-footage-filter-topic"]').attr("checked", false);
}

function selectAllRFFootage() {
    if (!$('#rf-footage-search-license').attr('checked')) {
        return;
    }
    $('[id^="rf-footage-filter-topic"]').attr("checked", true);
}

function deselectAllRFFootage() {
    if (!$('#rf-footage-search-license').attr('checked')) {
        return;
    }
    $('[id^="rf-footage-filter-topic"]').attr("checked", false);
}

function selectAllTVDataFootage() {
    if (!$('#tvdata-footage-search-license').attr('checked')) {
        return;
    }
    $('[id^="tvdata-footage-filter-topic"]').attr("checked", true);
}

function deselectAllTVDataFootage() {
    if (!$('#tvdata-footage-search-license').attr('checked')) {
        return;
    }
    $('[id^="tvdata-footage-filter-topic"]').attr("checked", false);
}

function onEOFilterItemsChange() {
    var selectedAll = $('#eo-filter-collections>option[selected!=false]').size() == $('#eo-filter-collections>option').size();
    $('#eo-filter-common').attr("checked", selectedAll);
}


