﻿

$(function() {
    $('.searchbox').attr('autocomplete', 'off');
});

window.SearchAPI = {
    // ******** properties *********
    CurrentPageNo: null,
    LastPageNo: 0,
    NoImages: 0,
    ArchiveID: 0,
    ArchiveChanged: false,
    ItemsPerRow: 4,
    ItemsPerCol: 4,
    SearchQuery: '',
    LicenseType: 3,
    Token: 0,
    CheckArchiveList: false,
    PreviewWindow: null,
    AssetIDs: [],
    Enabled: false,
    // ********** methods **********
    __checkQuery: function (q) {
        q = $.trim(q);
        while (q.indexOf('  ') >= 0) q = q.replace('  ', ' ');
        while (q.indexOf(' ') >= 0) q = q.replace(' ', '+');
        return q;
    },
    Init: function () {
        if ($('#CurrentPageNo').length == 0) { SearchAPI.Enabled = false; return; }

        SearchAPI.Enabled = true;

        $(['CurrentPageNo', 'LastPageNo', 'NoImages', 'Token', 'ItemsPerRow', 'ItemsPerCol', 'LicenseType']).each(function () { SearchAPI[this] = parseInt($('#' + this).val()) });
        $(['SearchQuery', 'ArchiveID']).each(function () { SearchAPI[this] = $('#' + this).val() });

        if (SearchAPI.CurrentPageNo > 1) $('.serNav .prev').addClass('navAct').bind('click', SearchAPI.PrevPage);                    // prev button state
        if (SearchAPI.CurrentPageNo < SearchAPI.LastPageNo) $('.serNav .next').addClass('navAct').bind('click', SearchAPI.NextPage);    // next button state
        if (SearchAPI.LastPageNo > 1) $('.specific').addClass('navAct').each(function () { var el = $(this); el.bind('click', function () { SearchAPI.GoSpecific(el); return false; }) });

        if (SearchAPI.CurrentPageNo > 1) $('.damNavPrev').addClass('damNavAct').bind('click', SearchAPI.PrevPage);                    // prev button state
        if (SearchAPI.CurrentPageNo < SearchAPI.LastPageNo) $('.damNavNext').addClass('damNavAct').bind('click', SearchAPI.NextPage);    // next button state
        if (SearchAPI.LastPageNo > 1) $('.damSpecific').addClass('damNavNext').each(function () { var el = $(this); el.bind('click', function () { SearchAPI.GoSpecific(el); return false; }) });

    },
    ArchiveList: function () {
        var a = '', sep = '';
        var arch = $('#ArchiveList input:checked');
        for (var i = 0; i < arch.length; i++) { a += sep + $(arch[i]).val(); sep = ','; }
        return a;
    },
    LeftSearch: function (opts) {
        var q = $('#q').val();
        var a = '', sep = '';
        var arch = $('#ArchiveList input:checked');
        if (SearchAPI.CheckArchiveList) {
            if (arch.length == 0) { notify(R.str.PLEASE_SELECT_ARCHIVE); return }
        }
        var query = SearchAPI.__checkQuery(q);
        query = '?q=' + escape(query) + '&a=' + SearchAPI.ArchiveList();
        if (typeof (opts) == 'object') { for (var k in opts) { query += '&' + k + '=' + opts[k]; } }
        if ($('#aCreative:checked').length > 0) { query += "&l=" + $('#creativeExtras :checked').val(); }
        query += "&st=" + $('#searchType :checked').val();
        if ($('#aSport:checked').length > 0) { query += "&dr=" + $('#sportExtras :checked').val(); }
        window.location = getUrl('Search') + query;
    },
    Search: function (q, opts, ad) {
        var query = SearchAPI.__checkQuery(q);
        query = '?q=' + escape(query);
        if (query == '?q=') query = '?';
        if (typeof (opts) == 'object') { for (var k in opts) { query += '&' + k + '=' + opts[k]; } }
        else if (opts != '0') { query += '&a=' + opts; }

        window.location = getUrl('Search') + query;
        return false;
    },
    NewUISearch: function (arc) {
        var data = $('#form_arc' + arc).serialize();
        notify($.query.get('filetype'));
    },
    Refine: function (q) {
        if ($.trim(q) == '') { notify(R.str.REFINE_TO_SEARCH_FURTHER); return; }
        if (SearchAPI.SearchQuery != '') q = SearchAPI.SearchQuery + " " + q;
        SearchAPI.Search(q, SearchAPI.ArchiveID);
    },
    Preview: function (id, extra, hideOther) {
        var url = getUrl('Asset', 'Details', id, extra);
        SearchAPI.PreviewWindow = window.open(url, "prev_" + id, 'scrollbars=yes,resizable=yes,width=1020,height=720', true);
        window.showOther = hideOther ? 0 : 1;
        SearchAPI.PreviewWindow.opener = self;
    },
    Comp: function (id) {
        var url = getUrl('Asset', 'Comping', id);
        SearchAPI.PreviewWindow = window.open(url, 'gallo_comp', 'scrollbars=yes,resizable=yes,width=1020,height=720', true);
        SearchAPI.PreviewWindow.opener = self;
    },
    __navigate: function (dir) {
        var opts = { is: (SearchAPI.CurrentPageNo - 1 + dir) * SearchAPI.ItemsPerCol * SearchAPI.ItemsPerRow + 1 };

        if (SearchAPI.ArchiveID.length > 20) { opts['a'] = ''; }
        else { opts['a'] = SearchAPI.ArchiveID; }

        if ($('#q').val() == '') $('#q').val(SearchAPI.SearchQuery);
        var lic = $('input[name="l"]:checked');
        if (lic.length > 0)
            opts['l'] = lic.val();
        SearchAPI.Search(SearchAPI.SearchQuery, opts);
        return false;
    },
    NextPage: function () {
        SearchAPI.__navigate(1);
        return false;
    },
    PrevPage: function () {
        SearchAPI.__navigate(-1);
        return false;
    },
    GoSpecific: function (el) {
        var page = parseInt(el.prev().val());
        if (isNaN(page) || page < 1 || page > SearchAPI.LastPageNo) { notify(R.str.NOT_VALID_PAGE_NO); return; }

        var opts = { is: (page - 1) * SearchAPI.ItemsPerCol * SearchAPI.ItemsPerRow + 1 };

        if (SearchAPI.ArchiveID.length > 20) { opts['a'] = ''; }
        else { opts['a'] = SearchAPI.ArchiveID; }

        SearchAPI.Search(SearchAPI.SearchQuery, opts);
        return false;
    },
    AddToQuote: function (id) {
        QuoteAPI.AddToQuote(id);
    },
    SetCurrentAsset: function (wnd, id) {
        wnd.location = getUrl('Asset', 'Details', id);
    },
    SearchKeywords: function (wnd, q) {
        while (q.indexOf('[') > -1) q = q.replace('[', '"');
        while (q.indexOf(']') > -1) q = q.replace(']', '"');
        wnd.notify(R.str.SEE_ORIG_WINDOW, function () {
            wnd.close();
            SearchAPI.Search(q, SearchAPI.ArchiveID);
        });
    },
    SetRowCount: function (cnt) {
        window.location = setURLParam('' + window.location, 'rc', '' + cnt);
    }
};

window.QuoteAPI = {
    AddToQuote : function(id) { // assetID
        $.get(getUrl('Quote','AddToQuote',id), function(res) {
            if (res!='1') notify(res);
            else notify('Added to the current quote');
        });
    },
    RemoveFromQuote : function(id, url) {
        confirmModal('Remove quote item', R.str.CONF_DEL_QUOTE_ITEM, function() {
            $('#quoteItems').load(getUrl('Quote','RemoveFromQuote',id));
        });
    }
};

window.LightboxAPI = {
    AddByChoosing: function(id) {
        $.get(getUrl('Lightbox', 'QuickAdd', id), function(html) {
            showPopup("Add to a Lightbox", html, {
                Cancel: function() {
                    $(this).dialog('close');
                },
                Add: function() {
                    var dlg = this;
                    $.post(getUrl('Lightbox', 'QuickAddToLightbox', id), { groupID: $('#lb_groupID').val(), name: $('#lb_name').val() }, function() {
                        $(dlg).dialog('close');
                    });
                }
            });
        });
    },
    AddItem: function(id) {
        $.get(getUrl('Lightbox', 'AddItem'), { assetID: id, lightboxID: $('#Lightbox').val() }, function(res) {
            if (res != '1') notify(res);
            else notify('Added the item to the lightbox');
        });
    },
    DeleteItem: function(id) {
        confirmModal('Remove lightbox item', R.str.CONF_DEL_LB_ITEM, function() {
            $.get(getUrl('Lightbox', 'DeleteItem'), { assetID: id, lightboxID: $('#Lightbox').val() }, function(res) {
                if (res != '1') notify(res);
                else window.location.href = window.location.href;
            });
        });
    },
    DeleteLightbox: function(id) {
        confirmModal('Delete lightbox', R.str.CONF_DEL_LB, function() {
            $.get(getUrl('Lightbox', 'Delete', id), function(resStr) {
                var res;
                eval('res=' + resStr)
                if (res.status == '-1') notify(res.msg);
                else window.location.href = res.url;
            });
        });
    }
};

window.ShoppingCartAPI = {
    AddByChoosing: function(id) {
        $.get(getUrl('ShoppingCart', 'QuickAddDlg', id), function(html) {
            showPopup("Add to a shopping cart", html, {
                Cancel: function() {
                    $(this).dialog('close');
                },
                Add: function() {
                    var dlg = this;
                    $.post(getUrl('ShoppingCart', 'QuickAddToShoppingCart', id), { shoppingCartID: $('#sc_shoppingCartID').val(), name: $('#sc_shoppingCartName').val() }, function(res) {
                        if (res != '1') notify(res);
                        else $(dlg).dialog('close');
                    });
                }
            });
        });
    },
    DeleteItem: function(id) {
        confirmModal('Remove shopping cart item', R.str.CONF_DEL_SC_ITEM, function() {
            $.get(getUrl('ShoppingCart', 'DeleteItem'), { assetID: id, shoppingCartID: $('#ShoppingCartID').val() }, function(res) {
                if (res != '1') notify(res);
                else window.location.href = window.location.href;
            });
        });
    }
};