// Base URL of the application, will be retreived right after the DOM is ready
var APP_BASE_URL      = '';
var MEDIA_BASE_URL    = '';
var COLUMN_CREATE_MIN = -1;

// Called after DOM ready event
$(document).bind('ready', function (e) {
    // IE 7 version detection fix
    if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && window.XMLHttpRequest) {
        jQuery.browser.version = '7.0';
    }
    
    // Check if we are in production or not
    var isProduction = window.location.href.match(/sparia\.de/gi);
    if (isProduction) {
        APP_BASE_URL   = false;
        MEDIA_BASE_URL = 'http://media.sparia.de/';
    } else {
        APP_BASE_URL   = $('script[@src$="media/js/sparia.js"]').attr('src').replace(/media\/js\/sparia\.js/, '');
        MEDIA_BASE_URL = APP_BASE_URL + 'media/';
    }

    // MarkItUp
    if (typeof($.markItUp) != 'undefined') {
        if (APP_BASE_URL == false) {
            var prefix = 'http://admin.sparia.de/'; 
        } else {
            var prefix = APP_BASE_URL + 'admin/';
        }
        
        $('textarea.bb-code').markItUp({
            previewParserPath: prefix + 'bbcode-parser',
            markupSet: [
                {name:'H1', className: 'bbcode-h1', openWith:'[h1]', closeWith:'[/h1]'},
                {name:'H2', className: 'bbcode-h2', openWith:'[h2]', closeWith:'[/h2]'},
                {name:'Fett', className: 'bbcode-bold', key:'B', openWith:'[b]', closeWith:'[/b]'},
                {name:'Kursiv', className: 'bbcode-italic', key:'I', openWith:'[i]', closeWith:'[/i]'},
                {name:'Durchgestrichen', className: 'bbcode-stroke', key:'S', openWith:'[s]', closeWith:'[/s]'},
                {name:'Farbe', className: 'bbcode-color', openWith:'[color=[![Farbe]!]]', closeWith:'[/color]', dropMenu: [
                    {name:'Red', openWith:'[color=red]', closeWith:'[/color]', className:"bbcode-color-red" },
                    {name:'Yellow', openWith:'[color=yellow]', closeWith:'[/color]', className:"bbcode-color-yellow" },
                    {name:'Blue', openWith:'[color=blue]', closeWith:'[/color]', className:"bbcode-color-blue" },
                    {name:'Green', openWith:'[color=green]', closeWith:'[/color]', className:"bbcode-color-green" },
                    {name:'Gray', openWith:'[color=gray]', closeWith:'[/color]', className:"bbcode-color-gray" },
                    {name:'Maroon', openWith:'[color=maroon]', closeWith:'[/color]', className:"bbcode-color-maroon" },
                    {name:'Fuchsia', openWith:'[color=fuchsia]', closeWith:'[/color]', className:"bbcode-color-fuchsia" },
                    {name:'Lime', openWith:'[color=lime]', closeWith:'[/color]', className:"bbcode-color-lime" },
                    {name:'Black', openWith:'[color=black]', closeWith:'[/color]', className:"bbcode-color-black" }
                ]},
                {separator:'---------------' },
                {name:'Bulleted list', className: 'bbcode-bulleted-list', openWith:'[list]\n', closeWith:'\n[/list]'}, 
                {name:'Numeric list', className: 'bbcode-numeric-list', openWith:'[list=[![Starting number]!]]\n', closeWith:'\n[/list]'}, 
                {name:'List item', className: 'bbcode-list-item', openWith:'[*] '}, 
                {separator:'---------------' },
                {name:'Quotes', className: 'bbcode-quotes', openWith:'[quote]', closeWith:'[/quote]'}, 
                {name:'HTML', className: 'bbcode-html', openWith:'[html]', closeWith:'[/html]'}, 
                {separator:'---------------' },
                {name:'Link', className: 'bbcode-link', key:'L', openWith:'[url=[![Url]!]]', closeWith:'[/url]', placeHolder:'Ziel-URL'},
                {name:'Säubern', className:"bbcode-clean", replaceWith:function(h) { return h.selection.replace(/\[(.*?)\]/g, "") } },
                {name:'Preview', className:"bbcode-preview", call:'preview' }
            ]
        });
    }
    
    // Bind uploader functionallity   
    $('#uploader_file').bind('change', function(e) {
        this.form.submit();
        
        window.parent.beginUpload(document.getElementById('upload_url').value);
    });
      
    var uploadDone = $('#upload_done');
    if (uploadDone.length > 0) {
        var name     = uploadDone.attr('rel');
        var filename = uploadDone.text();
        
        window.parent.resetUploadForm();
        window.parent.parent.finishUpload(name, filename);
    }
    
    var uploadFailed = $('#upload_failed');
    if (uploadFailed.length > 0) {
        var message = uploadFailed.text();
        
        alert(message);
        
        window.parent.resetUploadForm();
        window.parent.parent.exitUpload();
    }
    
    // NiceJForms
    if (typeof($.ProForms) != 'undefined') {
        $.ProForms.replace(MEDIA_BASE_URL + "images/niceforms/");
    }
    
    // Datepicker
    if (typeof($.datepicker) != 'undefined') {
        $('input.datepicker').datepicker();
    }

    // Lightbox
    if (typeof($.fn.lightBox) != 'undefined') {
        $(function() {
        	$('a.product-image').lightBox({fixedNavigation:true});
        	$('a.lightbox').lightBox({fixedNavigation:true});
        });
    }
    
    // Tooltips       
    $('.tooltip').bind('mouseenter', function(e) {                                             
        this.t     = this.title;
        this.title = '';
        
        $('body').append('<p id="tooltip">' + this.t + '</p>');
        $('#tooltip').css('top',  (e.pageY - 10) + 'px')
                     .css('left', (e.pageX + 24) + 'px')
                     .fadeIn('fast');
    }).bind('mouseleave', function() {
        this.title = this.t;        
        $('#tooltip').remove();
    }).bind('mousemove', function(e) {
        $('#tooltip').css('top',  (e.pageY - 10) + 'px')
                     .css('left', (e.pageX + 24) + 'px');
    });
    
    // Sortable tables
    if (typeof($.fn.tablesorter) != 'undefined') {
        $.tablesorter.addParser({ 
            id: 'vendor', 
            is: function(s) {
                if (s.match(/<a.*?>(?:\s|\n)*([^<>]*?)(?:\s|\n)*<\/a>/m)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                var result = s.match(/<a.*?>(?:\s|\n)*([^<>]*?)(?:\s|\n)*<\/a>/m);

                if (result) {
                    return result[1].toLowerCase();
                }
                return 0;
            },
            type: 'text' 
        });
               
        $.tablesorter.addParser({ 
            id: 'euro', 
            is: function(s) {
                if (s.match(/^\d+(?:,\d+) €$/)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                return s.replace(/€/,'').replace(/,/,'.'); 
            },
            type: 'numeric' 
        });
        
        $.tablesorter.addParser({ 
            id: 'cent',
            is: function(s) {
                if (s.match(/^\d+(?:,\d+)? ¢$/)) {
                    return true;
                }
                return false; 
            }, 
            format: function(s) { 
                return s.replace(/¢/,'').replace(/,/,'.'); 
            },
            type: 'numeric' 
        });
        
        $.tablesorter.addWidget({ 
            id: "repeatHeaders", 
            format: function(table) { 
                if (!this.headers) { 
                    var h = this.headers = [];  
                    $("thead th",table).each(function() { 
                        h.push( 
                            '' + $(this).text() + '' 
                        ); 
                    }); 
                } 
                  
                $("tr.repated-header",table).remove(); 
                    
                for (var i=0; i < table.tBodies[0].rows.length; i++) { 
                    if ((i%5) == 4) { 
                        $("tbody tr:eq(" + i + ")",table).before( 
                            $("").html(this.headers.join("")) 
                        );     
                    } 
                } 
            } 
        });
        
        $.tablesorter.defaults.widgetZebra.css = ['tableRow0', 'tableRow1'];
        
        $('table.sortable').tablesorter({widgets: ['zebra']});
    }
    
    // Floating table headers
    if (!jQuery.browser.msie || parseInt(jQuery.browser.version, 10) >= 7) {
        var tableHeaderDoScroll = function() {
            if (typeof(tableHeaderOnScroll) == 'function') {
                tableHeaderOnScroll();
            }
        };

        // Track positioning and visibility.
        function tracker(e) {
            // Save positioning data.
            var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            
            if (e.viewHeight != viewHeight) {
                e.viewHeight = viewHeight;
                e.vPosition = $(e.table).offset().top + 1;
                e.hPosition = $(e.table).offset().left;
                e.vLength = e.table.clientHeight - 100;
                
                // Resize header and its cell widths.
                var parentCell = $('th', e.table);
                $('th', e).each(function(index) {
                    var cellWidth = parentCell.eq(index).css('width');

                    // Exception for IE7.
                    if (cellWidth == 'auto') {
                        cellWidth = (parentCell.get(index).clientWidth - 22) +'px';
                    }
                
                    $(this).css('width', cellWidth);
                });
                
                if (jQuery.browser.msie) {
                    $(e).css('width', (parseInt($(e.table).css('width')) - 50) + 'px');
                    $(e).css('table-layout', 'fixed');
                } else {
                    $(e).css('width', $(e.table).css('width'));
                }
            }

            // Track horizontal positioning relative to the viewport and set visibility.
            var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft;
            var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - e.vPosition;
            var visState = (vOffset > 0 && vOffset < e.vLength) ? 'visible' : 'hidden';
            $(e).css({left: -hScroll + e.hPosition +'px', visibility: visState});
        }
        
        // Keep track of all cloned table headers.
        var headers = [];

        $('table.sticky-enabled thead:not(.tableHeader-processed)').each(function () {
            var $table  = $(this).parent('table');
            var table   = $table[0];
            var classes = $table.attr('class');
            
            // Clone thead so it inherits original jQuery properties.
            var headerClone = $(this).clone(true).insertBefore(this.parentNode).wrap('<table class="' + classes + ' sticky-header"></table>').parent().css({
                position: 'fixed',
                top: '-2px'
            });

            // Local fix
            $('th', headerClone).each(function(index) {
                $(this).unbind('click');
                $(this).attr('title', '');
            });
            
            headerClone = $(headerClone)[0];
            headers.push(headerClone);

            // Store parent table.
            headerClone.table = table;
            
            // Finish initialzing header positioning.
            tracker(headerClone);

            $(table).addClass('sticky-table');
            $(this).addClass('tableHeader-processed');
        });

        // Only attach to scrollbars once, even if Drupal.attachBehaviors is called
        // mulud le times.
        if (!$('body').hasClass('tableHeader-processed')) {
            $('body').addClass('tableHeader-processed');
            $(window).scroll(tableHeaderDoScroll);
            $(document.documentElement).scroll(tableHeaderDoScroll);
        }

        // Track scrolling.
        var tableHeaderOnScroll = function() {
            $(headers).each(function () {
                tracker(this);
            });
        };

        // Track resizing.
        var time = null;
        var resize = function () {
            // Ensure minimum time between adjustments.
            if (time) {
                return;
            }
            
            time = setTimeout(function () {
                $('table.sticky-header').each(function () {
                    // Force cell width calculation.
                    this.viewHeight = 0;
                    tracker(this);
                });
                
                // Reset timer
                time = null;
            }, 250);
        };
        
        $(window).resize(resize);
    }
    
    // Search
    $('form#quick-search').find('input[@type=text]').bind('focus', function (e) {
        if (this.value == this.title) {
            this.value = '';
        }
    }).bind('blur', function (e) {
        if (this.value.trim() == '') {
            this.value = this.title;
        }
    });

    // Word counter
    var wordCounter = function (e) {
        var minLength = 20;
        var words     = this.value.split(' ');

        var length = 0;
        for (var i = 0; i < words.length; i++) {
            if (words[i].length > 1) {
                length++;
            }
        }

        if (length < minLength) {
            var lengthLeft = minLength - length;
        } else {
            var lengthLeft = 0;
        }

        var span = $('#comment-length-info');
        span.text(lengthLeft);
    }

    $('#df_comment').bind('keyup',   wordCounter);
    $('#df_comment').bind('focus',   wordCounter);
    $('#df_comment').bind('blur',    wordCounter);
    $('#df_comment').bind('mouseup', wordCounter);

    $('#df_comment').blur();

    // Table click
    $('table.rate-overview tbody tr').bind('click', function() {
        var url = $(this).find('a').attr('href');
        window.location.href = url;
    });
    
    // Show URL binding
    $('input.showUrl').bind('focus', function (e) {
        $(this).select();

        if (jQuery.browser.msie) {
            if (window.clipboardData && clipboardData.setData) {
                clipboardData.setData("Text", this.value);
            }
        }
    }).bind('click', function (e) {
        $(this).select();

        if (jQuery.browser.msie) {
            if (window.clipboardData && clipboardData.setData) {
                clipboardData.setData("Text", this.value);
            }
        }
    });

    // Bind change of sort selection
    $('select.sortSelect').bind('change', function (e) {
        window.location.href = $(this).val();
    });

    // Bind product more details
    $('a.showAdditionalDetails').bind('click', function (e) {
        if ($('#productAdditionalDetails').css('display') != 'block') {
            $(this).text('Details verbergen');
            $('#productAdditionalDetails').show('slow');
        } else {
            $(this).text('Weitere Details');
            $('#productAdditionalDetails').hide('slow');
        }

        return false;
    });
    
    // Coupons char list
    $('a.coupon-char-select').bind('click', function (e) {
        $(this).parent().find('.char-result').hide('slow');
        
        $.getJSON($(this).attr('href'),
            function (data) {
                var oldResult = $('.char-result'); 
            
                if (data.length == 0) {
                    var result = $('<p class="char-result">Unter diesem Buchstaben gibt es keine Shops.</p>');
                } else {
                    var result = $('<ul class="char-result"></ul>');
                    
                    for (var i = 0; i < data.length; i++) {
                        var date = data[i];
                        
                        var li     = $('<li></li>');
                        var anchor = $('<a></a>');
                        
                        li.append(anchor);
                        
                        if (date.logo_url == null) {
                            anchor.text(date.shop_name);
                        } else {
                            var img = $('<img width="88" height="31" />');
                            img.attr('alt', date.shop_name);
                            img.attr('src', date.logo_url);
                            anchor.append(img);
                            anchor.attr('title', date.shop_name);
                        }

                        anchor.attr('href', date.target_url);
                        
                        result.append(li);
                    }
                }
                
                result.hide();
                
                oldResult.before(result);
                oldResult.remove();
                
                result.show('slow');
            }
        );

        return false;
    });

    // Active switch
    $('input.switch-active').bind('click', function (e) {
        window.location.href = $(this).attr('value');
    });
    
    // Ask for delete
    $('a.delete').bind('click', function (e) {
       if (this.title) {
           return window.confirm('Soll der Eintrag "' + this.title + '" wirklich gelöscht werden?');
       } else {
           return window.confirm('Soll der Eintrag wirklich gelöscht werden?');
       }
    });

    // Open links with blank class in new windows   
    $('a.blank').bind('click', function (e) {
        if (!jQuery.browser.msie || !$(this).hasClass('rev-popup')) {
            window.open(this.href);
        }

        if ($(this).hasClass('rev-popup')) {
            window.open(this.rev, 'coupon', 'left=50,top=50,width=560,height=120,location=0,toolbar=0,resizable=0,statusbar=0,menubar=0');
        }
        
        if (!jQuery.browser.msie || !$(this).hasClass('rev-popup')) {
            return false;
        }
    });
    
    $('a.link-top').bind('click', function (e) {
        top.location.href = this.href;
        return false;
    });
       
    // HTML editor popup
    $('a.html').bind('click', function (e) {
        var htmlEditor = window.open(this.href, 'HTML-Editor', 'width=1024,height=500,scrollbars=yes');
        htmlEditor.focus();
        return false;
    });

    // Execute check event on amazon icons
    $('a.icon.amazon').bind('click', function (e) {
        var content = this.href.split('#');
        var data = content[1].split('-');

        var searchIndex  = data[0];
        var browsenodeId = data[1];

        if (APP_BASE_URL == false) {
            var prefix = 'http://admin.sparia.de/'; 
        } else {
            var prefix = APP_BASE_URL + 'admin/';
        }

        $.getJSON(prefix + 'testreports/categories/check/' + browsenodeId + '/' + searchIndex,
            function (data) {
                if (data.result == 'ok') {
                    window.alert('Kategorie in Ordnung, es wurden Produkte gefunden.');
                } else {
                    window.alert("Kategorie fehlerhaft, es wurden keine Produkte gefunden!\n\nMeldung:\n" + data.message);
                }
            }
        );

        return false;
    });

    // Amazon review truncate
    $('a.amazon-review').bind('click', function (e) {
        var content  = this.href.split('#');
        var data     = content[1].split('-');
        var reviewId = data[1];

        if (APP_BASE_URL == false) {
            var prefix = 'http://testberichte.sparia.de/'; 
        } else {
            var prefix = APP_BASE_URL + 'testberichte/';
        }
        $.getJSON(prefix + 'review/get/' + reviewId,
            function (data) {
                var parent = $('a.amazon-review[@href$="#review-' + data.id + '"]').parent();
                parent.html(data.content);
            }
        )

        return false;
    });

    // Replace rating dropdowns with rating element
    $('select.rating').each(function() {
        var $this = $(this);

        var id = $this.attr('id');

        var $input = $(document.createElement('input'));
        $input.attr('id',    id);
        $input.attr('name',  id);
        $input.attr('type',  'hidden');
        $input.attr('value', $this.val());

        var $ratingBox = $(document.createElement('span'));
        $ratingBox.addClass('rating-box');

        for (var i = 1; i <= 5; i++) {
            var $rating = $(document.createElement('span'));
            $rating.attr('id', id + '_' + i);

            $rating.addClass('rating');
            if (i <= $this.val()) {
                $rating.addClass('rating-hover');
            }

            $ratingBox.append($rating);
        }

        $ratingBox.insertAfter($this);
        $input.insertAfter($this);

        $this.remove();
    });

    // Bind the rating element actions
    $('span.rating').bind('mouseenter', function (e) {
        var data   = splitIntoIdAndRating(this.id);
        var id     = data.id;
        var rating = data.rating;

        for (var i = 1; i <= 5; i++) {
            if (i <= rating) {
                $('#' + id + '_' + i).addClass('rating-hover');
            } else {
                $('#' + id + '_' + i).removeClass('rating-hover');
            }
        }
    });

    $('span.rating').bind('mouseleave', function (e) {
        var data       = splitIntoIdAndRating(this.id);
        var id         = data.id;
        var rating     = data.rating;
        var currentVal = parseInt($('#' + id).val());

        for (var i = 1; i <= 5; i++) {
            if (i <= currentVal) {
                $('#' + id + '_' + i).addClass('rating-hover');
            } else {
                $('#' + id + '_' + i).removeClass('rating-hover');
            }
        }
    });

    $('span.rating').bind('click', function (e) {
        var data = splitIntoIdAndRating(this.id);
        var id     = data.id;
        var rating = data.rating;

        if (rating == $('#' + id).val()) {
            $('#' + id).val(0);
        } else {
            $('#' + id).val(rating);
        }
    });

    // Column create
    if ($.browser.mozilla) {
        var bindEvent = 'keypress';
    } else {
        var bindEvent = 'keydown';
    }
    
    $('input.columnCreateName').bind(bindEvent, function(e) {
        if (e.keyCode == 13) {
            columnCreate($(this));
            e.preventDefault();
            return false;
        }
        
        return true;
    });
    
    $('input.columnCreateAdd').bind('click', function () { columnCreate($(this)); });
       
    if (typeof($.ui) != 'undefined') {
        $('ul.columnCreateList').sortable({'update': function() { columnCreateUpdate($(this)); }});
    }
    
    $('ul.columnCreateList a.icon.delete').unbind('click').bind('click', columnDelete);
    $('ul.columnCreateList a.icon.edit').unbind('click').bind('click', columnEdit);
    $('ul.columnCreateList a.icon.info').unbind('click').bind('click', columnInfo);
    
    $("ul.columnCreateList input[@type='checkbox']").bind('click', function() {
        columnCreateUpdate($(this).parent().parent());
    });

    // Google Analytics
    if (typeof(_gat) != 'undefined') {
        var pageTracker = _gat._getTracker("UA-301363-6");
        pageTracker._initData();
        pageTracker._trackPageview();
    }
});

/**
 * Edit info column
 */
function columnInfo() {
    var info = window.prompt('Neuer Info:', $(this).parent().find('span').attr('title'));
    
    if (info == null) {
        return false;
    }
    
    info = info.trim();
    
    $(this).parent().find('span').attr('title', info);
    columnCreateUpdate($(this).parent().parent());
    
    return false;
}

/**
 * Edit acolumn
 */
function columnEdit() {
    var name = window.prompt('Neuer Name:', $(this).parent().find('span').text());
    
    if (name == null) {
        return false;
    }
    
    name = name.trim();
    
    if (name == '') {
        alert('Bitte gib einen Namen an.');
        return false;
    }
    
    $(this).parent().find('span').text(name);
    columnCreateUpdate($(this).parent().parent());
    
    return false;
}

/**
 * Delete a column
 */
function columnDelete() {
    var confirm = window.confirm('Soll die Spalte wirklich gelöscht werden?');
    
    if (confirm == true) {
        var ul = $(this).parent().parent();
    
        $(this).parent().css('display', 'none');
        $(this).parent().addClass('column-deleted');
        
        ul.sortable('refresh');
        columnCreateUpdate(ul);
    }

    return false;
}

/**
 * Create a new column
 */
function columnCreate(element) {
    var thisId        = element.attr('id');
    var lastUnderline = thisId.lastIndexOf('_');
    var id            = thisId.substr(0, lastUnderline);
    
    var name = $('#' + id + '_name').attr('value');
    var type = $('#' + id + '_type').attr('value');
    
    if (typeof(name) == 'undefined') {
        name = '';
    } else {
        name = name.trim();
    }
    
    if (name == '') {
        alert('Bitte gib einen Namen an.');
        return;
    }
       
    var li = $(document.createElement('li'));
    li.attr('id', id + '_column_' + COLUMN_CREATE_MIN--);
    li.addClass('columnCreate-' + type);
    
    var anchor = $(document.createElement('a'));
    anchor.addClass('icon');
    anchor.addClass('delete');        
    anchor.bind('click', columnDelete);       
    li.append(anchor);
    
    var anchor = $(document.createElement('a'));
    anchor.addClass('icon');
    anchor.addClass('edit');        
    anchor.bind('click', columnEdit);       
    li.append(anchor);
    
    var anchor = $(document.createElement('a'));
    anchor.addClass('icon');
    anchor.addClass('info');        
    anchor.bind('click', columnInfo);       
    li.append(anchor);

    var checkbox = $(document.createElement('input'));
    checkbox.attr('type',  'checkbox');
    checkbox.attr('value', 'overview');
    checkbox.attr('title', 'Nur in Detailansicht anzeigen');
    checkbox.addClass('checkbox-overview');
    checkbox.bind('click', function() {
        columnCreateUpdate($(this).parent().parent());
    });
    li.append(checkbox);

    var checkbox = $(document.createElement('input'));
    checkbox.attr('type',  'checkbox');
    checkbox.attr('value', 'highlight');
    checkbox.attr('title', 'Spalte hervorgeben');
    checkbox.addClass('checkbox-highlight');
    checkbox.bind('click', function() {
        columnCreateUpdate($(this).parent().parent());
    });
    li.append(checkbox);
    
    var span = $(document.createElement('span'));
    span.text(name);
    li.append(span);
    
    $('#' + id + '_list').append(li);
    $('#' + id + '_name').attr('value', '');
    
    $('#' + id + '_list').sortable('refresh');
    
    columnCreateUpdate($('#' + id + '_list'));
};

/**
 * A column in a columnCreate has changes
 */
function columnCreateUpdate(ul) {
    var thisId        = ul.attr('id');
    var lastUnderline = thisId.lastIndexOf('_');
    var id            = thisId.substr(0, lastUnderline);
    
    var lis  = ul.find('li');
    var data = new Array();
    var ids  = ul.sortable('toArray');
    
    for (var i = 0; i < ids.length; i++) {
        $this = $('#' + ids[i]);
               
        if ($this.hasClass('columnCreate-text')) {
            var type = 'text';
        } else if ($this.hasClass('columnCreate-number')) {
            var type = 'number';
        } else if ($this.hasClass('columnCreate-euro')) {
            var type = 'euro';
        } else if ($this.hasClass('columnCreate-cent')) {
            var type = 'cent';
        } else if ($this.hasClass('columnCreate-boolean')) {
            var type = 'boolean';
        }
       
        if ($this.find('input.checkbox-overview').attr('checked')) {
            var overview = 'y';
        } else {
            var overview = 'n';
        }
        
        if ($this.find('input.checkbox-highlight').attr('checked')) {
            var highlight = 'y';
        } else {
            var highlight = 'n';
        }

        var thisId        = $this.attr('id');
        var lastUnderline = thisId.lastIndexOf('_');
        var colId         = thisId.substr(lastUnderline + 1);
        var name          = $this.find('span').text();
        var info          = $this.find('span').attr('title');
        
        if ($this.hasClass('column-deleted')) {
            var deleted = 'y';
        } else {
            var deleted = 'n';
        }
        
        data[data.length] = '"' + colId +  '","' + type + '","' + overview + '","' + highlight + '","' + deleted + '","' + addslashes(name) + '","' + addslashes(info) + '"';
    }
    
    var value = data.join("\n");
    $('#' + id).attr('value', value);
}

function beginUpload(url)
{
    var overlay       = $(document.createElement('div'));
    var progressOuter = $(document.createElement('div'));
    var progressText  = $(document.createElement('div'));
    var progressBar   = $(document.createElement('span'));
        
    overlay.attr('id',       'progress-overlay');
    progressOuter.attr('id', 'progress-outer');
    progressBar.attr('id',   'progress-bar');

    progressText.text('Lade hoch ...');

    progressOuter.append(progressText);
    progressOuter.append(progressBar);    
    overlay.append(progressOuter);
    $('body').append(overlay);    

    $("#progress-bar").progressBar(0, {showText: false,
                                       boxImage: APP_BASE_URL + 'media/images/progressbar/progressbar.gif',
                                       barImage: APP_BASE_URL + 'media/images/progressbar/progressbg_red.gif'} );

    setTimeout("showUpload('" + url + "')", 1500);
}

function finishUpload(name, filename)
{
    var preview = $('#' + name + '_preview');
    
    preview.text('[img]' + MEDIA_BASE_URL + 'images/uploads/' + filename + '[/img]');
    $('#' + name).attr('value', filename);
    
    $('#progress-overlay').remove();
}

function exitUpload()
{
    $('#progress-overlay').remove();
}

function resetUploadForm()
{
    document.getElementById('uploadForm').reset();
}
 
function showUpload(url)
{
    $.get(url, function(data) {
        if (!data) {
            var percentage = 100;
        } else {
            var response;
            eval("response = " + data);
     
            if (!response) {
                percentage = 100;
            } else {
                var percentage = Math.floor(100 * parseInt(response['bytes_uploaded']) / parseInt(response['bytes_total']));
            }
        }
 
        $("#progress-bar").progressBar(percentage);
        
        if (percentage < 100) {
            setTimeout("showUpload('" + url + "')", 750);
        }
    });
}

/**
 * add slashes to a string
 */
function addslashes(str)
{
    str = str.replace(/\\/g,'\\\\');
    str = str.replace(/\'/g,'\\\'');
    str = str.replace(/\"/g,'\\"');
    str = str.replace(/\0/g,'\\0');
    
    return str;
}

/**
 * Split a rating id into it's common rating and id
 */
function splitIntoIdAndRating(id)
{
    var data = id.split('_');

    var extract    = new Object();
    extract.id     = data.slice(0, data.length -1).join('_');
    extract.rating = parseInt(data[data.length - 1]);

    return extract;
}

/**
 * Strip leading and trailing whitespaces and return everything in between
 */
String.prototype.trim = function()
{
    var x = this;
    x = x.replace(/^\s*(.*)/, "$1");
    x = x.replace(/(.*?)\s*$/, "$1");
    return x;
}
