var maxTags = 12;
var maxTagsTop = 6;
var tagMinLength = 2;
var tagMaxLength = 48;
var tagList = new Array();

var sendPhotoList = new Array();

/**
 * Reset all tags arrays
 */
var resetTags = function(eID) {
    var A = new Array();
    eval('var A' + eID + ' = new Array();');
    var E = new Array();
    eval('var E' + eID + ' = new Array();');
    var K = new Array();
    eval('var K' + eID + ' = new Array();');
    var N = new Array();
    eval('var N' + eID + ' = new Array();');
    var R = new Array();
    eval('var R' + eID + ' = new Array();');
    var U = new Array();
    eval('var U' + eID + ' = new Array();');
    $('#' + eID).find('.autoels').html('');
    $('#' + eID).find('.autolist').removeClass('filled');
}

/**
 * Save tags to DB
 */
var saveTags = function(eID) {
    if(eID===undefined) {
        return null;
    }
    eval('var CurrA = $.merge([], A' + eID + ');');
    eval('var CurrN = $.merge([], N' + eID + ');');
    eval('h = H' + eID + ';');
    $.ajax({
        type: 'POST',
        url: '/h/ajax/save_tag',
        data: 'a='+CurrA.join(',')+'&n='+CurrN.join(',')+'&o='+eID+'&h='+h,
        success: function(data){
            //resetTags(eID);
            getTags(eID, $('#' + eID).find('input').val());
        },
        dataType: 'json'
    });
}

/**
 * Remove tags from DB
 */
var removeTags = function(eID) {
    if(eID===undefined) {
        return null;
    }
    eval('var CurrR = $.merge([], R' + eID + ');');
    eval('h = H' + eID + ';');
    $.ajax({
        type: 'POST',
        url: '/h/ajax/remove_tags',
        data: 'r='+CurrR.join(',')+'&o='+eID+'&h='+h,
        success: function(data){
            //resetTags(eID);
            eval('R' + eID + ' = new Array();');
            getTags(eID, $('#' + eID).find('input').val());
        },
        dataType: 'json'
    });
}

var xhrGetTagsSuggest = null;
var xhrGetTagsUsed = null;
var tagInMemory = false;
var listForRefill = new Array();
// This function get list of eg.1000 tags. Should be use just one time!
var getAllTags = function() {
    tagList = new Array();
    tagInMemory = false;
    listForRefill = new Array();
    //*************** NEW ***********************************
    xhrGetTagsSuggest = $.ajax({
        type: 'POST',
        url: '/h/area_tag/get_tags',
        data: '',
        success: function(data){
            var HTMLChange = '';
            break_callback = callback_json_parse(data);
            if(break_callback==null)
                return;
            $.each(data, function(i, item){
                tagList.push(item.label.toLowerCase());
            });
            tagInMemory = true;
            if(listForRefill.length>0) {
                $.each(listForRefill, function(i,item){
                    fillFirstHtml(item);
                });
            }
        },
        dataType: 'json'
    });
}
//**************************************************************************

var fillFirstHtml = function(eID) {
    var eName = eID ? '#' + eID + ' ' : '';
    var eID = eID ? eID : '';
    var HTMLChange = '';
    eval('var CurrN = $.merge([], N' + eID + ');');
    if(tagInMemory) {
        shortTagList = tagList.slice(0,maxTagsTop);
        $.each(shortTagList, function(i, item){
            if(jQuery.inArray(item.toLowerCase(), CurrN) == -1) {
                itemId = item.toLowerCase().replace(/(\')+/gi, '\\\'');
                HTMLChange = HTMLChange + '<div class="el" id_area="' + itemId + '"><div class="icon"></div>' + item + '</div>';
                eval('E' + eID + '.push(\'' + itemId  + '\');');
            }

        });
        $(eName + '.els').html(HTMLChange);
    } else {
        listForRefill.push(eID);
    }
}

var fillHtml = function(eID,shortTagList) {
    var eName = eID ? '#' + eID + ' ' : '';
    var eID = eID ? eID : '';
    var HTMLChange = '';
    eval('var CurrN = $.merge([], N' + eID + ');');
    eval('E' + eID + ' = new Array();');


    $.each(shortTagList, function(i, item){
        if(jQuery.inArray(item.toLowerCase(), CurrN) == -1) {
            itemId = item.toLowerCase().replace(/(\')+/gi, '\\\'');
            HTMLChange = HTMLChange + '<div class="el" id_area="' + itemId + '"><div class="icon"></div>' + item + '</div>';
            eval('E' + eID + '.push(\'' + itemId  + '\');');
        }

    });
    $(eName + '.els').html(HTMLChange);
    if(shortTagList.length<maxTags) {

}
}
/**
 * Get json with available tag list
 */
var getTags = function(eID, input) {

    if($("#cat"+eID).hasClass("grayInput")) {
        input = '';
    }

    var eName = eID ? '#' + eID + ' ' : '';
    var eID = eID ? eID : '';
    var selected_areas = '';
    if(eID != '') {

        eval('if(A' + eID + '.length > 0) { var go = true; } else { var go = false; }');

        if(go) {

            eval('var CurrID = $.merge([], A' + eID + ');');

            var n = 0;
            $.each(CurrID, function(i, v) {
                if(n == 0) {
                    selected_areas = selected_areas + v;
                } else {
                    selected_areas = selected_areas + ',' + v;
                }
                n = n + 1;
            });

        }

    }

    xhrGetTagsSuggest = $.ajax({
        type: 'POST',
        url: '/h/area_tag/get_suggests',
        data: 'query='+selected_areas+'&letters='+input+'&o='+eID,
        success: function(data){
            var HTMLChange = '';
            break_callback = callback_json_parse(data);
            if(break_callback==null)
                return;
            $.each(data, function(i, item){

                eval('var CurrA = $.merge([], A' + eID + ');');
                eval('var CurrE = $.merge([], E' + eID + ');');
                eval('var CurrK = $.merge([], K' + eID + ');');
                eval('var CurrN = $.merge([], N' + eID + ');');

                if(jQuery.inArray(item.value, CurrA) == -1 && jQuery.inArray(item.label.toLowerCase(), CurrN) == -1) {
                    HTMLChange = HTMLChange + '<div class="el" id_area="' + item.value + '"><div class="icon"></div>' + item.label + '</div>';

                    eval('E' + eID + '.push(\'' + item.label.toLowerCase().replace(/(\')+/gi, '\\\'') + '\');');
                    eval('K' + eID + '.push(\'' + item.value + '\');');
                }

            });

            $(eName + '.els').html(HTMLChange);
        },
        dataType: 'json'
    });

    xhrGetTagsUsed = $.ajax({
        type: 'POST',
        url: '/h/area_tag/get_used',
        data: 'query='+selected_areas+'&letters='+input+'&o='+eID,
        success: function(data){
            eval(' U' + eID + ' = new Array()');
            var HTMLChange = '';
            break_callback = callback_json_parse(data);
            if(break_callback==null)
                return;
            $.each(data, function(i, item){
                eval('U' + eID + '.push(\'' + item.label.toLowerCase().replace(/(\')+/gi, '\\\'') + '\');');
            });
        },
        dataType: 'json'
    });
}

/**
 * Function remove white spaces from given text
 */
var removeWhiteSpaces = function(input) {
    m = /\s+/g;
    return input.replace(m," ");
}

var searchNextTags = function(input,eID) {
    if($("#cat"+eID).hasClass("grayInput")) {
        input = '';
    }
    if(input=='') {
        shortTagList = tagList.slice(0,maxTags*2);
        shortTagListReturn = new Array();
        j = 0;
        eval('var CurrN = $.merge([], N' + eID + ');');

        $.each(shortTagList, function(i, item){
            if(j<maxTagsTop) {
                itemId = item.toLowerCase();//.replace(/(\')+/gi, '\\\'');
                if (jQuery.inArray(itemId, CurrN) == -1) {
                    shortTagListReturn.push(itemId);
                    //alert('If ' + itemId);
                    j++;
                } else {
            //alert('Else ' + itemId);
            }
            } else {
                return shortTagListReturn;
            }
        });
        return shortTagListReturn;
    } else {
        shortTagListReturn = new Array();
        eval('var CurrN = $.merge([], N' + eID + ');');
        j = 0;
        $.each(tagList, function (i,item) {
            if(j<maxTagsTop) {
                itemId = item.toLowerCase();
                input = input.toLowerCase();
                if((itemId.indexOf(input)!=-1) && (jQuery.inArray(itemId, CurrN) == -1)) {
                    shortTagListReturn.push(itemId);
                    j++;
                }
            }
            else {
                return shortTagListReturn;
            }
        });
        return shortTagListReturn;
    }
}

$('#fill_elem').click(function() {
    getTags(false, '');
});

var tagInterval = 700;

/**
 * Click on tag element - in list both list : used and not used now.
 * Change position this element and start timer.
 */
$('.el').live('click', function() {

    $(this).closest('.input').find('input').focus();

    //cat<?= $f_id ?>
    //eval('var inputVal = N' + getEID(this) + '.length;');
    var n = $('#' + getEID(this)).find('.autoels').find('.el').length;

    eval('var elCount = N' + getEID(this) + '.length;');
    //    eval('if(elCount > 0) { var CurrB = $.merge([], A' + getEID(this) + '); } else { var CurrB = new Array(); }');
    eval('var CurrN = $.merge([], N' + getEID(this) + ');');

    if( $(this).parent().hasClass('els') ) {
        if(n < maxTags && jQuery.inArray($(this).attr('id_area'), CurrN) == -1) {

            $('#' + getEID(this)).find('.autoels').append( $(this) );

            eval('N' + getEID(this) + '.push(\'' + $(this).attr('id_area') + '\');');

            var removeItem = $(this).attr('id_area').replace(/(\\\')+/gi, '\'');

            eval('E' + getEID(this) + ' = jQuery.grep(E' + getEID(this) + ', function(value) { return value != removeItem; });');

            //            $("#cat"+getEID(this)).val('');


            //if(inputVal != '' && !$("#cat"+getEID(this)).hasClass("grayInput")) {
            $("#cat"+getEID(this)).val('');
            var inputVal = $("#cat"+getEID(this)).val();
            //                $("#cat"+getEID(this)).val($("#cat"+getEID(this)).attr('defaulttext'));
            //                $("#cat"+getEID(this)).toggleClass('grayInput');
            //                alert('test');
            //}

            fillHtml(getEID(this),searchNextTags(inputVal,getEID(this)));

            $("#cat"+getEID(this)).focus();

            $("#cat"+getEID(this)).removeClass('grayInput');
        }

        if(elCount == 0) $('#' + getEID(this)).find('.autolist').addClass('filled');



    } else if( $(this).parent().hasClass('autoels') ) {

        var removeItem = $(this).attr('id_area').replace(/(\\\')+/gi, '\'');

        //alert($(this).attr('id_area'));

        eval('N' + getEID(this) + ' = jQuery.grep(N' + getEID(this) + ', function(value) { return value != removeItem; });');

        $("#cat"+getEID(this)).val('');

        var inputVal = $("#cat"+getEID(this)).val();

        fillHtml(getEID(this),searchNextTags(inputVal,getEID(this)));

        $("#cat"+getEID(this)).focus();

        $("#cat"+getEID(this)).removeClass('grayInput');

        $(this).remove();


    }

});

$('.els').live('click', function() {
    $(this).closest('.input').find('input').focus();
});

/**
 * Get photo id
 */
var getEID = function(e) {
    return $(e).closest('.photo_box').attr('id');
}

var cleanTagInput = function(e) {
    var pattern = /[^\s0-9a-ząćęłńóśżźäöü\'\-]+/gi;
    if (pattern.test($(e).val())) {
        showPopup(i18n.error_title,i18n.wrong_character);
        $(e).val($(e).val().replace(/[^\s0-9a-ząćęłńóśżźäöü\'\-]+/gi, ''));
    }
    pattern = /[\s]{2,}/gi;
    if (pattern.test($(e).val())) {
//        showPopup(i18n.error_title,i18n.wrong_character);
        $(e).val($(e).val().replace(/[\s]{2,}/gi, ' '));
    }
}

var addToForm = function(eID, v) {
    var current_v = $('#' + eID + ' .t').val();
    if(current_v != '') {
        v = current_v + ',' + v;
    }
    $('#' + eID + ' .t').val(v);
}

var removeFromForm = function(eID, v) {
    var current_v = $('#' + eID + ' .t').val();
    v = current_v.replace(v, '');
    $('#' + eID + ' .t').val(v);
}

var mouse_is_inside = false;

$('.el').live('hover', function() {
    mouse_is_inside = true;
}, function() {
    mouse_is_inside = false;
});

var typeTimer;
var intervalType = 300;

/**
 * Insert tags into box after type in input and confirm enter.
 */
$('.tag_box input').live('keydown', function(e) {
    cleanTagInput(this);

    var code = e.keyCode ? e.keyCode : e.which;

    if(code == 13) { // 13 = enter

        var tag = removeWhiteSpaces($(this).val().substring(0, tagMaxLength));
        tag = tag.trim();
        tag = tag.replace(/(\')+/gi, '\\\'');
        //var tag = $(this).val().substring(0, tagMaxLength);
        var n = $('#' + getEID(this)).find('.autoels').find('.el').length;
        eval('var CurrE = $.merge([], E' + getEID(this) + ');');
        eval('var CurrN = $.merge([], N' + getEID(this) + ');');
        if(tag != '' && tag.toLowerCase()!='tatuaże' && tag.length > (tagMinLength - 1) && n < maxTags && jQuery.inArray(tag.toLowerCase().replace(/(\\\')+/gi, '\''), CurrN) == -1) {
            if(jQuery.inArray(tag.toLowerCase(), CurrE)!=-1) {
                tagText = tag.toLowerCase().replace(/(\\\')+/gi, '\'');
                var appendHTML = '<div class="el user" id_area="' + tag + '"><div class="icon"></div>' + tagText + '</div>';
                $('#' + getEID(this)).find('.autoels').append(appendHTML);
                eval('N' + getEID(this) + '.push(\'' + tag.toLowerCase() + '\');');
                if(jQuery.inArray(tag.toLowerCase(),tagList)!=-1) {
                } else {
                    tagList.push(tagText.toLowerCase());
                }
                if(n == 0) $('#' + getEID(this)).find('.autolist').addClass('filled');
                var obj = $(this);

                $(this).val('');
            } else {
                tagText = tag.toLowerCase().replace(/(\\\')+/gi, '\'');
                var appendHTML = '<div class="el user" id_area="' + tag + '"><div class="icon"></div>' + tagText + '</div>';
                eval('N' + getEID(this) + '.push(\'' + tag.toLowerCase() + '\');');
                $('#' + getEID(this)).find('.autoels').append(appendHTML);
                if(jQuery.inArray(tag.toLowerCase().replace(/(\\\')+/gi, '\''),tagList)!=-1) {
                } else {
                    tagList.push(tagText.toLowerCase());
                }
                if(n == 0) $('#' + getEID(this)).find('.autolist').addClass('filled');
                $(this).val('');
            }
        }

    //event.preventDefault();
    }
});

/**
 * Start timer for search tags in DB
 */
$('.tag_box input').live('keyup', function() {
    cleanTagInput(this);
    obj = this;
    fillHtml(getEID(this),searchNextTags($(obj).val(),getEID(this)));
//getTags(getEID(this), $(this).val())}
});


$('.tag_object').live('click', function(ev) {
    ev.preventDefault();
    eval('var CurrA = $.merge([], A' + getEID(this) + ');');
    eval('var CurrN = $.merge([], N' + getEID(this) + ');');

    var $link = $(this),
    h = $link.attr( 'href' );

    $.ajax({
        type: 'POST',
        url: '/h/ajax/save_tag',
        data: 'a='+CurrA.join(',')+'&n='+CurrN.join(',')+'&o='+getEID(this)+'&h='+h,
        beforeSend: function(){
            $link.closest('.form').addClass('saving');
        },
        success: function(data){
            resetTags(getEID($link));
            getTags(getEID($link), $('#' + getEID($link)).find('input').val());
            $.each(data, function(i, item){

                });
            $link.closest('.form').removeClass('saving');
        },
        error: function(){
            $link.closest('.form').removeClass('saving');
        },
        dataType: 'json'
    });
});

$('.cat,.fp_description').live("focus", function(ev){
    if($(this).val()==$(this).attr('defaulttext')) {
        $(this).val('');
        $(this).removeClass('grayInput');
    }
});

$('.cat,.fp_description').live("blur", function(ev){
    if($.trim($(this).val())=='') {
        $(this).val($(this).attr('defaulttext'));
        $(this).addClass('grayInput');
    }
});

