var suche_aktiv = false;	// fuer das suchformular
var interval_aktiv = false;

$(document).ready(function()
{
    init();
});

function init()
{
    try {
        document.execCommand("BackgroundImageCache", false, true);
    } catch(e) {};

    // set default js
    //	try { setActive(); } catch(e) {};
    //	try { setSelectable(); } catch(e) {};
    //	try { setDraggable(); } catch(e) {};
    try {
        setPositions();
    }	catch(e) {};

    try {
        toggleTitel();
    }	catch(e) {};
    try {
        setInfoButtons();
    }	catch(e) {};
    try {
        setGesamtdownloadButtons();
    } catch(e) {};

    try {
        setFormSearch();
    }	catch(e) {};

    try {
        showFormExport();
    }	catch(e) {};
    try {
        getAjaxLoader();
    }	catch(e) {};

    $('table.tablesorter').tablesorter();
}

function debug()
{
    if (window && window.console && window.console.log)
        for(var i=0, len = arguments.length; i < len; i++)
            console.log(arguments[i]);
}


var log = function(elem){
    if (window.console) {
        console.debug(elem);
    }
} //Ende debug

function str_replace (search, replace, subject)
{
    var result = "";
    var  oldi = 0;
    for (i = subject.indexOf (search)
        ; i > -1
        ; i = subject.indexOf (search, i))
        {
        result += subject.substring (oldi, i);
        result += replace;
        i += search.length;
        oldi = i;
    }
    return result + subject.substring (oldi, subject.length);
}

function trim (zeichenkette)
{
    // Erst f�hrende, dann Abschlie�ende Whitespaces entfernen
    // und das Ergebnis dieser Operationen zur�ckliefern
    return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
}

function strip_tags(html)
{
    //PROCESS STRING
    if(arguments.length < 3) {
        html=html.replace(/<\/?(?!\!)[^>]*>/gi, '');
    } else {
        var allowed = arguments[1];
        var specified = eval("["+arguments[2]+"]");
        if(allowed){
            var regex='</?(?!(' + specified.join('|') + '))\b[^>]*>';
            html=html.replace(new RegExp(regex, 'gi'), '');
        } else{
            var regex='</?(' + specified.join('|') + ')\b[^>]*>';
            html=html.replace(new RegExp(regex, 'gi'), '');
        }
    }

    //CHANGE NAME TO CLEAN JUST BECAUSE
    var clean_string = html;

    //RETURN THE CLEAN STRING
    return clean_string;
}

function strip_tags_with_content(html)
{
    return html.replace(/<\/?(?!\!)[^>]*>([\w\s������()-]*)/gi, '');
}

/**
 *      knauf_24_37_98_0_0_0_7165_0_0
 *            |  |  |  | | |   |  | |
 * 	  gewerk_id  |  |  | | |   |  | |
 * 	      titel_id  |  | | |   |  | |
 *      untertitel_id  | | |   |  | |
 *        symbolgruppeId | |   |  | |
 *         eigenschaft_id  |   |  | |
 *               attribut_id   |  | |
 *                     system_id  | |
 *                   gruppierung_id |
 *                        baustein_id
 */
function IdStringToJson(id_string)
{
    var html_id_array_new = new Array();
    html_id_array_new[0] = new Object();
    var html_id_array = id_string.split("_");

    var json = {
        "typ": 						html_id_array[0],
        "gewerk_id": 			html_id_array[1],
        "titel_id": 			html_id_array[2],
        "untertitel_id":	html_id_array[3],
        "symbolgruppe_id":html_id_array[4],
        "eigenschaft_id":	html_id_array[5],
        "attribut_id":		html_id_array[6],
        "system_id": 			html_id_array[7],
        "gruppierung_id": html_id_array[8],
        "baustein_id": 		html_id_array[9]
    };

    return json;
}

/**
 *      knauf_24_37_98_0_0_0_7165_0_0
 *            |  |  |  | | |   |  | |
 * 	  gewerk_id  |  |  | | |   |  | |
 * 	      titel_id  |  | | |   |  | |
 *      untertitel_id  | | |   |  | |
 *        symbolgruppeId | |   |  | |
 *         eigenschaft_id  |   |  | |
 *               attribut_id   |  | |
 *                     system_id  | |
 *                   gruppierung_id |
 *                        baustein_id
 */
function putHtmlIdInArray(id_string)
{
    var html_id_array_new = new Array();
    html_id_array_new[0] = new Object();
    var html_id_array = id_string.split("_");

    html_id_array_new[0]['typ'] = 						html_id_array[0];
    html_id_array_new[0]['gewerk_id'] = 			html_id_array[1];
    html_id_array_new[0]['titel_id'] = 				html_id_array[2];
    html_id_array_new[0]['untertitel_id'] = 	html_id_array[3];
    html_id_array_new[0]['symbolgruppe_id'] = html_id_array[4];
    html_id_array_new[0]['eigenschaft_id'] = 	html_id_array[5];
    html_id_array_new[0]['attribut_id'] = 		html_id_array[6];
    html_id_array_new[0]['system_id'] = 			html_id_array[7];
    html_id_array_new[0]['gruppierung_id'] = 	html_id_array[8];
    html_id_array_new[0]['baustein_id'] = 		html_id_array[9];

    return html_id_array_new;
}

function getAjaxLoader(){
    $('#loading_gif').ajaxStart(function(){
        $(this).show();
    });
    $('#loading_gif').ajaxStop(function(){
        $(this).hide();
    });
}

function validateEmail(div, div_error, email)
{
    var filter = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (filter.test(email) != false)
    {
        return true;
    }
    else
    {
        $(div).css('border', '1px solid red');
        //string = unescape("Bitte geben Sie eine g%FCltige Email-Adresse ein!");
        $(div_error).fadeIn('slow').fadeOut(3000);
        //alert(string);
        return false;
    }
}

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function print_r(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;

    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";

    if(typeof(arr) == 'object') { //Array/Hashes/Objects
        for(var item in arr) {
            var value = arr[item];

            if(typeof(value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}

/**
 *	liefert ein ajax ergebnis.
 */
function getAjax(action, type, param)
{
//    var action = action;
//    var type = type;
//    var param = param;
    var str = '';
    $.ajax(
    {
        type: "POST",
        url: getAjaxUrl(action),
        data: param,
        async: false, // !! erforderlich
        dataType: type,
        timeout: 5000,
        success: function(data)
        {
            str = data;
        },
        error: function(request, errorType, errorThrown)
        {
            debug(errorType);
        }
    });
    return str;
}

function getDeleteImg()
{
    return '<img class="delete_position" src="assets/common/icon_delete.gif" />';
}

function getPositionsButtons()
{

    var id = randomString();
    var id2 = randomString();
    var html = '';

    html += '<div class="buttons">';
    html += '<input type="checkbox" id="'+ id +'" class="eventualposition" %s />';
    html += '<label for="'+ id +'">EP</label>';
    html += '<input type="checkbox" id="'+ id2 +'" class="alternativposition" %s />';
    html += '<label for="'+ id2 +'">AP</label>';
    html += '</div>';
    return html;
}

function randomString(length)
{
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
    var numbers = '0123456789';

    if (! length)
    {
        length = Math.floor(Math.random() * chars.length);
    }

    var str = '';
    for (var i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }

    for (var i = 0; i < length; i++) {
        str += numbers[Math.floor(Math.random() * numbers.length)];
    }

    return str;
}

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
