/*
 * Fuer die Benutzer bewertung benoetigt
 *
 * @author kscheffelmeier
 */
var given          = new Array();
var account_dd     = false;
var on_prev_player = false;
var show_video     = true;
var attributes     = {
                        '1':{
                                'type':'radiobox',
                                'values':null
                            },
                        '2':{
                                'type':'radiobox',
                                'values':null
                            },
                        '3':{
                                'type':'radiobox',
                                'values':null
                            },
                        '4':{
                                'type':'select',
                                'title':'mood',
                                'values':{
                                    11:null,
                                    12:null,
                                    13:null,
                                    14:null,
                                    15:null,
                                    16:null,
                                    17:null,
                                    18:null
                                }
                            },
                        '5':{
                                'type':'checkbox',
                                'values':new Array()
                            },
                        '6':{
                                'type':'checkbox',
                                'values':new Array()
                            },
                        '7':{
                                'type':'select',
                                'title':'genre',
                                'values':{
                                    64:null,
                                    65:null
                                }
                            },
                        '8':{
                                'type':'select',
                                'title':'music_for',
                                'values':{
                                    67:null,
                                    68:null,
                                    69:null,
                                    70:null,
                                    71:null
                                }
                            },
                        '9':{
                                'type':'select',
                                'title':'cd_category',
                                'values':{
                                    72:null,
                                    73:null,
                                    74:null
                                }
                            }
                        };

/**
 * Suchformular validieren
 *
 * @author kscheffelmeier
 */
$(document).ready(function() {

    jQuery.validator.messages.required = '';
// change by sw, to suit requirements from 09.11.2011
//    $("#search_form").validate({
//        errorPlacement: function(error, element) {}
//    });
//
//    $("#search_form").validate({
//        rules: {
//            "sb-searchtext": {
//                required: true
//            }
//        }
//    });

    /*
     * AJAX-Caching ausschalten
     */
    $.ajaxSetup({ cache: false });
});

/**
 * Init Navi
 *
 * @modified kscheffelmeier
 */
active_page_btn = false;

function clearHideMenuTimeout() {

  if (hidemenu_timer) {

    window.clearTimeout(hidemenu_timer);
    hidemenu_timer = false;
  }
}

function toggleVideo() {

  if (show_video)  {

    $('#mypholder').css('display', 'block');
    show_video = false;
  } else {

    $('#mypholder').css('display', 'none');
  }
}

hidemenu_timer = false;
open_menu_a    = false;

/**
 * Menus
 *
 * @modified kscheffelmeier
 */
function showMenu(e) {
  if (e.currentTarget.id != 'btn-auctions' && e.currentTarget.id != 'btn-upload') {

    show_video = false;
    toggleVideo();
    var preview = $('#previewplayer').is(':visible');
    if(preview) {

      endPreview();
    }
  }

  clearHideMenuTimeout();

 if (active_page_btn) {

   removeClass($(active_page_btn), 'active');
 }

 if (open_menu_a) {

   removeClass(open_menu_a, 'active');
 }

 if (!e) {

   e = window.event;
 }

 var target = e.target || e.srcElement;

 if (target.nodeName.toLowerCase() != 'a') {

   target = target.parentNode;
 }

 open_menu_a = target;
 addClass(open_menu_a, 'active');

 if(open_menu_a.id == 'btn-upload' || open_menu_a.id == 'btn-auctions') {

   navi_menu.css('display', 'none');
   return;
 }

 navi_menu.html('<div class="navi-menu-p"></div><div id="navi-menu-in">'+target.nextSibling.innerHTML+'</div>');

 var target_pos = getPos(target);
 var navi_l_pos = (target_pos.x - 22);

 navi_menu.css('left',    navi_l_pos+'px');
 navi_menu.css('display', 'block');

 /*
  * bei Mac Firefoxes blenden wir das Video aus, wenn vorhanden

 if (window.navigator.userAgent.indexOf('Macintosh') != -1 &&
     window.navigator.userAgent.indexOf('Mac') != -1) {

     $('#embedprevi').attr('autoplay', false);
     $('#mypholder').css('display', 'none');
 }

 if (window.navigator.userAgent.indexOf('Mozilla') != -1) {

     $('#embedprevi').attr('autoplay', false);
     $('#mypholder').css('display', 'none');
 }*/
}

/**
 * detect internetexplore and if it is one
 * then detect its version
 *
 * @author nschulze
 */
function getInternetExplorerVersion() {

  var rv = -1;

  if (navigator.appName == 'Microsoft Internet Explorer') {

    var ua = navigator.userAgent;
    var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");

    if (re.exec(ua) != null) {

      rv = parseFloat(RegExp.$1);
    }
  }
  return rv;
}

/**
 * Hide Menu
 *
 * @modified kscheffelmeier
 */
function hideMenu(e) {

  hidemenu_timer = window.setTimeout(function() {

    navi_menu.css('display', 'none');
    if (open_menu_a) {

      removeClass(open_menu_a, 'active');
    }

    if (active_page_btn) {

      addClass($(active_page_btn), 'active');
    }

    open_menu_a = false;

    if (e.currentTarget.id != 'btn-auctions' && e.currentTarget.id != 'btn-btn-upload') {
      show_video  = true;
      toggleVideo();
    }

 }, 700);

  /*
   * bei Mac Firefoxes blenden wir das Video aus, wenn vorhanden

  if (window.navigator.userAgent.indexOf('Macintosh') != -1 &&
      window.navigator.userAgent.indexOf('Mac') != -1) {

      $('#mypholder').css('display', 'block');
  }

  if (window.navigator.userAgent.indexOf('Mozilla') != -1) {

      $('#mypholder').css('display', 'block');
  }*/
}

/**
 * Feedback-Overlay anzeigen
 *
 * @author kscheffelmeier
 */
function showFeedbackOverlay() {

  if ($('#feedbackoverlay').css('display') == 'none') {

    $('#mypholder').css('display', 'none');
    $.get('/system/ajaxShowFeedbackOverlay', {}, function (data) {

                                                $('#feedbackoverlay').html(data);
                                                $('#feedbackoverlay').css('display', 'block');
                                                $('#feedbackoverlay').css('width',   '400px');
                                                $('#feedbackoverlay').css('top',     '50px');
                                                $('#feedbackoverlay').css('padding', '10px');
                                                $('#feedbackoverlay').css('height',  'auto');
                                                $('#feedbackoverlay').css('left',    ($(document).width() / 2 - 200)+'px');
                                                $('#overlay').css('display', 'block');
                                              });
  } else {

    $('#feedbackoverlay').css('display', 'none');
    $('#mypholder').css(      'display', 'block');
  }
}

var animate_feedback = false;
function initNavi() {

  // Navi Menu
  navi_menu = $('#navi-menu');

  navi_menu.bind('mouseover', function(e) { clearHideMenuTimeout(e); hideAC(); });
  navi_menu.bind('mouseout',  function(e) { hideMenu(e); });

  $('#btn-audio').bind(   'mouseover', function(e) { showMenu(e); hideAC(); });
  $('#btn-video').bind(   'mouseover', function(e) { showMenu(e); hideAC(); });
  $('#btn-auctions').bind('mouseover', function(e) { showMenu(e); hideAC(); });
  $('#btn-upload').bind(  'mouseover', function(e) { showMenu(e); hideAC(); });

  $('#btn-audio').bind(   'mouseout',  function(e) { hideMenu(e); });
  $('#btn-video').bind(   'mouseout',  function(e) { hideMenu(e); });
  $('#btn-auctions').bind('mouseout',  function(e) { hideMenu(e); });
  $('#btn-upload').bind(  'mouseout',  function(e) { hideMenu(e); });

  if ($('#btn-audio').attr('className') == 'active') {

    active_page_btn = 'btn-audio';
  }

  if ($('#btn-video').attr('className') == 'active') {

    active_page_btn = 'btn-video';
  }

  if ($('#btn-auctions').attr('className') == 'active') {

    active_page_btn = 'btn-auctions';
  }

  if ($('#btn-upload').attr('className') == 'active') {

    active_page_btn = 'btn-upload';
  }

  $('#feedback_btn').click(
    function() {
      showFeedbackOverlay();
    }
  );

  $('#feedback_btn').hover(
    function() {

      if (animate_feedback == true) {

        return;
      } else {

        animate_feedback = true;
      }

      $('#feedback_btn').animate(
        {left: "-1px"},
        200,
        'linear',
        function() {

        }
      );
    },
    function() {
      animate_feedback = true;

      $('#feedback_btn').animate(
        {left: "-13px"},
        200,
        'linear',
        function() {

          animate_feedback = false;
        }
      );
    }
  );

}

// Items
function itemOver(item) {

 item.style.backgroundColor = '#e2e2e2';
}

function itemOut(item) {

 item.style.backgroundColor = 'transparent';
}

function itemClick(item) {

 top.location.href = item.getElementsByTagName('a')[0].href;
}

/**
 * Autocomplete
 *
 * @modified kscheffelmeier
 */
function showAC(input) {

 var input_pos = getPos(input);

 $('#autocomplete-menu').css('left',     input_pos.x -10 + 'px');
 $('#autocomplete-menu').css('top',      input_pos.y +26 + 'px');
 $('#autocomplete-menu').css('minWidth', input.offsetWidth+10 + 'px');

 $('#autocomplete-menu').html('<strong>Test Title</strong><a href="#">Test Asdf</a><a href="#">Test Asd asdfsf</a><strong>Test Title</strong><a href="#">Test Adssf</a><a href="#">Test Asdf</a><a href="#">Test Asd asdfsf</a>');

 $('#autocomplete-menu').css('display', 'block');
}


/**
 * Info Layer
 *
 * @modified kscheffelmeier
 */
function showInfo(obj) {

  var obj_pos = getPos(obj);

  if (obj.title) {

    obj.info_text = obj.title;
    obj.title     = '';
  }

  if ((obj_pos.x - 150) < 0) {

    $('#info-layer').attr('className', 'info-layer-right');
    obj_pos.x += 174;
  } else {

    $('#info-layer').attr('className', '');
  }

  $('#info-layer').html('<div class="info-layer-p"></div><div id="info-layer-in">'+obj.info_text+'</div>');
  $('#info-layer').css('left',     (obj_pos.x - 150) + 'px');
  $('#info-layer').css('top',      (obj_pos.y - 11)  + 'px');
  $('#info-layer').css('display', 'block');
}

function showInfoOverlay(obj) {

 var obj_offset = $(obj).offset();
 var obj_pos    = {x:(obj_offset.left-20), y:obj_offset.top};

 if (obj.title) {

  obj.info_text = obj.title;
  obj.title = '';
 }

 if (obj_pos.x - 150 < 0) {
  $('#info-layer').attr('className', 'info-layer-right');
  obj_pos.x += 174;
 } else {
  $('#info-layer').attr('className', '');
 }

 $('#info-layer').html('<div class="info-layer-p"></div><div id="info-layer-in">'+obj.info_text+'</div>');
 $('#info-layer').css('left',     obj_pos.x - 150 + 'px');
 $('#info-layer').css('top',      obj_pos.y - 11 + 'px');
 $('#info-layer').css('display', 'block');
}

/**
 * Hide Menu
 *
 * @modified kscheffelmeier
 */
function hideInfo() {

  $('#info-layer').css('display', 'none');
}

// Toggle Box
function toggleBox(link) {
 var box = link.parentNode;
 if (box.className.indexOf('box-open') == -1) {
  addClass(box, 'box-open');
 } else {
  removeClass(box, 'box-open');
 }
 return false;
}

/**
 * Get element pos
 *
 * modified kscheffelmeier
 */
function getPos(obj, stopclass, is_home, show_player) {

 if (!stopclass) {

   stopclass = '#';
 }

 if (is_home == true) {

   var obj_offset = $(obj).offset();
   var coord      = {x:(obj_offset.left + 25), y:obj_offset.top};

   if (show_player) {

     if ($(window).width() < (coord.x + $('#previewplayer').width())) {

       var coord = {x:(obj_offset.left - 470), y:obj_offset.top};
     }
   }
 } else {

   var coord = {x:obj.offsetLeft, y:obj.offsetTop};

   while (obj = obj.offsetParent) {

     if (obj.className == stopclass || obj.id == stopclass) {

       return coord;
     }

     coord.x += obj.offsetLeft;
     coord.y += obj.offsetTop;
   }
 }

 return coord;
}

function getAbsolutePos(el) {

  var SL = 0, ST = 0;
  var is_div = /^div$/i.test(el.tagName);
  if (is_div && el.scrollLeft) {

    SL = el.scrollLeft;
  }
  if (is_div && el.scrollTop) {

    ST = el.scrollTop;
  }
  var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST }

  if (el.offsetParent) {
    var tmp = this.getAbsolutePos(el.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
}


function addClass(obj, cn) {
 if (String(' '+obj.className+' ').indexOf(' '+cn+' ')!=-1) return;
 if (obj.className=='') {
  obj.className=cn;
 } else {
  obj.className+=' '+cn;
 }
}

function removeClass(obj, cn) {

 obj.className = trim(String(' '+obj.className+' ').split(' '+cn+' ').join(' '));
}

function trim($s) {

 return String($s).replace(/^\s+/,'').replace(/\s+$/,'');
}

function getByClass(obj, className) {

 var i=0, subobj;

 while (subobj = obj.getElementsByTagName('*')[i++]) {

  if (subobj.className.indexOf(className) != -1) {

    return subobj;
  }
 }

 return false;
}

function stopEvent(e) {

 if (! e) {

   e = window.event;
 }

 e.cancelBubble=true;
 if (e.stopPropagation) {

   e.stopPropagation();
 }
}

var W3CDOM = (document.createElement && document.getElementsByTagName);

function initFileUploads(lang) {

  if (!W3CDOM) {

    return;
  }

  var fakeFileUpload       = document.createElement('div');
  fakeFileUpload.className = 'fakefile';

  var image       = document.createElement('img');
  image.src       = '/images/v2/choose_file_'+lang+'.png';
  image.className = 'pointer';

  fakeFileUpload.appendChild(image);

  var x = document.getElementsByTagName('input');

  for (var i=0;i<x.length;i++) {

    if (x[i].type != 'file') { continue; }
    if (x[i].parentNode.className != 'fileinputs') { continue; }

    x[i].className = 'file hiddeni';
    var clone      = fakeFileUpload.cloneNode(true);

    x[i].parentNode.appendChild(clone);
    x[i].relatedElement = clone.getElementsByTagName('input')[0];
    x[i].onchange       = x[i].onmouseout = function () { this.relatedElement.value = this.value; }
  }
}

preview_open = null;

/**
 * Zeigt ein Videopreview
 *
 * @author sweber
 * @author kscheffelmeier
 */
function showPreview(element, id, is_home) {

  if (preview_open != id) {

    show_video = false;
    toggleVideo();
    var obj_pos = getPos(element, null, is_home, true);

    $.get('/media/preview/'+id,
              {},
               function(data) {

                  $('#previewplayer').html(data);
                  $('#previewplayer').css('left',    (obj_pos.x + 100) + 'px');
                  $('#previewplayer').css('top',     (obj_pos.y - 150) + 'px');
                  $('#previewplayer').css('zIndex',  999);
                  $('#previewplayer').css('display', 'block');
                }
              );

    preview_open = id;
  }
}

/**
 * beendet ein Videopreview
 *
 * @author sweber
 */
function endPreview(mouseout) {

  if (mouseout == true) {

    preview_open = null;
    $('#previewplayer').load('/media/previewClose', function() { $('#previewplayer').css('display', 'none'); });
    show_video = true;
    toggleVideo();
  } else {

    if (!on_prev_player) {

      preview_open = null;
      $('#previewplayer').load('/media/previewClose', function() { $('#previewplayer').css('display', 'none'); });
      show_video = true;
      toggleVideo();
    } else {

      return;
    }
  }

//
//  if ($('#previewplayer').css('display') == 'block' && mouseout !== true) {
//
//    return;
//  } else if (mouseout == true) {
//
//    on_prev_player = true;
//    preview_open   = null;
//    $('#previewplayer').load('/media/previewClose', function() { $('#previewplayer').css('display', 'none'); });
//  } else {
//
//    on_prev_player = false;
//    preview_open   = null;
//    $('#previewplayer').load('/media/previewClose', function() { $('#previewplayer').css('display', 'none'); });
//  }
}

/**
 * aktualisiert die Sidebar auf der Uploadseite und Mediaedit
 *
 * @author sweber
 * @author kscheffelmeier
 */
function changeUploadSidebar(mode, page, mediafile_id) {

  if (mediafile_id) {

    $('#sidebar_list_holder').load('/upload/ajaxShowSidebar/'+mode+'/'+page+'/'+mediafile_id);
  } else {

    $('#sidebar_list_holder').load('/upload/ajaxShowSidebar/'+mode+'/'+page);
  }
}

/**
 * aktualisiert die Sidebar auf der Uploadseite und Mediaedit
 *
 * @author sweber
 */
function changeOtherFromSameSidebar(user_id, actual_id, page) {

  $('#sidebar_list_holder').load('/media/ajaxShowRelatedSidebar/'+user_id+'/'+actual_id+'/'+page);
}

/**
 * aktualisiert die verfügbaren Attribute anhand der Kategorie
 *
 * @author sweber
 */
function updateAttributes(select, id, mode) {

  $('#cat_spinner_'+id).css('display', 'block');
  category_id = select.options[select.options.selectedIndex].value;

//  $.jsonp({"url":     '/media/ajaxUpdateAttributeEditList/'+id+'/'+mode+'/'+category_id+'?jsoncallback=?',
//           "success": function(object) {
//                          $('#attribute_holder_'+id).html(object.data);
//                          $('#cat_spinner_'+id).css('display', 'none');
//                        }
//                     });

  $.get('/media/ajaxUpdateAttributeEditList/'+id+'/'+mode+'/'+category_id,
        {},
        function(data){ $('#attribute_holder_'+id).html(data);
                        $('#cat_spinner_'+id).css('display', 'none');
                       } );

//  $.jsonp({"url":     '/media/ajaxUpdateAttributeEditList/'+id+'/'+mode+'/'+category_id+'?jsoncallback=?',
//           "success": function(object) {
//                          $('#attribute_holder_'+id).html(object.data);
//                          $('#cat_spinner_'+id).css('display', 'none');
//                        }
//                     });
}

/**
 * fügt eine Lizenzgruppe an ein Mediafile hinzu
 *
 * @author sweber
 */
function addLicenseGroup(id) {

  $('#license_group_spinner').css('display', 'block');

  $.post(
    '/media/ajaxAddLicenseGroup/'+id,
    $('#edit_step_three_'+id).serialize(),
    function(data){

      $('#stepthree_'+id).html(data);
      $('#license_group_spinner').css('display', 'none');
    }
  );
}


/**
 * löscht eine Lizenzgruppe eines Mediafiles
 *
 * @author sweber
 */
function deleteLicenseGroup(id, group_id, mode) {

  $('#license_group_spinner').css('display', 'block');

  $.post(

    '/media/ajaxDeleteLicenseGroup/'+id+'/'+group_id,
    $('#edit_step_three_'+id).serialize(),
    function(data){

      $('#data_' + id).load('/media/ajaxReloadLicenseGroups/' + id + '/' + mode + '/3');
      $('#license_group_spinner').css('display', 'none');
    }
  );
}


/**
 * Checkt oder uncheckt alle Mediarechte einer Rechtegruppe
 *
 * @author sweber
 */
function checkAllMediarightsByLicenseGroup(type, group_id) {

  var state     = $('#'+type+'_'+group_id+'_state').val();
  var checked   = (state == 0) ? 'checked' : '';
  var new_state = (state == 0) ? '1' : '0';
  var alt_text  = $('#'+type+'_'+group_id+'_hidden').val();
  var inputs    = $('.'+type+'_input_'+group_id).attr('checked', checked);

  $('#'+type+'_'+group_id+'_hidden').val($('#'+type+'_'+group_id+'_switch').html());
  $('#'+type+'_'+group_id+'_switch').html(alt_text);
  $('#'+type+'_'+group_id+'_state').val(new_state);
}


/**
 * Zeigt oder versteckt die Länderexcludes im Mediafile edit Step 3
 *
 * @author sweber
 */
function handleCountryExcludes(value) {

  if (value == 0) {

    $('#exclude_country').css('display',    'none');
    $('#excluded_countries').css('display', 'none');
  } else {

    $('#exclude_country').css('display',    'block');
    $('#excluded_countries').css('display', 'block');
  }
}

/**
 * Zeigt oder versteckt die Sofortkaufoptionen im Mediafile edit Step 3
 *
 * @author sweber
 */
function updateInstantBuyEditValues(input_field) {

  if (input_field.checked) {

    $('#instantbuy_settings_price').css('display', 'block');
  } else {

    $('#instantbuy_settings_price').css('display', 'none');
  }
}

/**
 * Blendet ein "warten"-Overlay beim Upload ein
 *
 * @author sweber
 */
function waitForUploadOverlay() {

  $('#overlay').fadeIn('fast',function(){ $('#upload_infobox').animate({'top':'160px'},500);});
}

/**
 * Blendet ein "warten"-Overlay beim Upload aus
 *
 * @author sweber
 */
function endUploadOverlay() {

  $('#overlay').fadeOut('fast',function(){ $('#upload_infobox').fadeOut('fast', function () {});});
}

/**
 * Form-Submit ohne Submit-Button. Als workaround für den netten Safari, der hidden Submits dezent ignoriert. Danke!
 */
function initFormSubmit() {
  $('form').each(function() {
    $('input').keypress(function(e) {

      // nicht für die Editmaske im Mediafile.
      if(this.form.id.indexOf('it_step_t') == 2) {

        return;
      }

      // Enter pressed?
      if(e.which == 10 || e.which == 13) {
          this.form.submit();
      }
    });

    $('input[type=submit]').hide();
  });
}

/**
 * Nimmt einen Like oder Dislike entgegen
 *
 * @author sweber
 */
function handleLDClick(image, id, mode) {

  $('#mediafileInteractions').load('/media/ajaxLike/'+id+'/'+mode, function() { return false; });

  if (mode == 'like') {

    var image_left = '-90px';
    $('#media_likes').attr('onclick', 'return false;');
    $('#mini-overlay').css('display', 'none');
  } else {

    var image_left = '-120px';
    $('#media_dislikes').attr('onclick', 'return false;');
    $('#mini-overlay').css('display', 'none');
  }

  image.style.backgroundPosition = ''+image_left+' -30px';
}

/**
 * Steuert den Hover-effekt bei den Like und Dislikebuttons im Mediashow
 *
 * @author sweber
 */
function handleLDButton(image, mode, state, content) {

  image.src = '/images/v2/media_'+mode+'_'+state+'.gif';

  if (state == 'a') {

    var image_pos = getAbsolutePos(image);
    $('#minioverlay_content').html(content);
    $('#mini-overlay').css('display', 'block');

    var width = $('#mini-overlay').css('width');
    $('#mini-overlay').css('top',  (image_pos.y + 25)  + 'px');
    $('#mini-overlay').css('left', (image_pos.x - parseInt($('#mini-overlay').css('width'), 10) / 2 + 10) + 'px');
    var image_top = '-30px';
  } else {

    jQuery('#mini-overlay').css('display', 'none');
    var image_top = '0px';
  }

  var image_left = (mode == 'like') ? '-90px' : '-120px';

  image.style.backgroundPosition = ''+image_left+' '+image_top+'';
}

dialog_open = null;

/**
 * Öffnet den Add-To Dialog
 *
 * @author sweber
 */
function openAddToDialog(caller_obj, id) {

  if (dialog_open == 'addto') {

    caller_obj.id = 'media_addto';
    $('#slidedown').css('display', 'none');
    dialog_open = null;
  } else {

    $('#slidedown').load('/media/ajaxGetAddToDialog/'+id,
                         function() {
                            var image_pos = getAbsolutePos(caller_obj);

                            $('#slidedown').attr('className', '');
                            $('#slidedown').css('display',    'block');
                            $('#slidedown').css('width',      '80px');

                            $('#slidedown').css('top',  (image_pos.y + 24) + 'px');
                            $('#slidedown').css('left', (image_pos.x) + 'px');

                            caller_obj.id = 'media_addto_active';
                            $('#media_share_active').attr('id', 'media_share');

                            dialog_open = 'addto';
                         });
  }
}

/**
 * Öffnet den share-Dialog
 *
 * @author sweber
 */
function openShareDialog(caller_obj, id) {

  if (dialog_open == 'share') {

    caller_obj.id = 'media_share';
    $('#slidedown').css('display', 'none');
    dialog_open = null;
  } else {

    $("#slidedown").bind("clickoutside", function(event) {

      $('#media_share_active').attr('id', 'media_share');
      $(this).hide();
    });

    $('#slidedown').load('/media/ajaxGetShareDialog/'+id,
                         function() {
                            var image_pos = getAbsolutePos(caller_obj);

                            $('#slidedown').attr('className', 'slidewide');
                            $('#slidedown').css('display',    'block');
                            $('#slidedown').css('width',      '120px');

                            $('#slidedown').css('top',  (image_pos.y + 24) + 'px');
                            $('#slidedown').css('left', (image_pos.x + 7) + 'px');

                            caller_obj.id = 'media_share_active';
                            $('#media_addto_active').attr('id', 'media_addto');

                            dialog_open = 'share';
                         });
  }
}

save_buffer_calls = new Array();

/**
 * adds a savecall to the queue
 *
 * @author sweber
 */
function addToSaveBufferQueue(id, mode, step, savelink) {

  var already_exists = true;

  if (save_buffer_calls.length) {

    var total = save_buffer_calls.length;

    for (var i = 0; i < total; i++) {

      if (save_buffer_calls[i][0] != id   && save_buffer_calls[i][1] != mode &&
          save_buffer_calls[i][2] != step && save_buffer_calls[i][3] != savelink) {

        already_exists = false;
      }
    }
  } else {

    already_exists = false;
  }

  if (!already_exists) {

    save_buffer_calls.push(new Array(id, mode, step, savelink));
  }
}

/**
 * saving buffer function
 *
 * @author sweber
 */
function traverseSaveBuffer() {

  if (save_buffer_calls.length > 0) {

    if (file_uploading != false) {

      window.setTimeout("traverseSaveBuffer()", 1000);
    } else {

      var upload_element = save_buffer_calls.shift();
      $('#edit_step_three_'+upload_element[0]).ajaxSubmit({ success: function(data){ $('#data_'+upload_element[0]).html(data);
                                                                      savelink.className    = 'small-btn fr';
                                                                      savelink.onclick      = function() { ajaxSaveMediafile(upload_element[0], upload_element[1], upload_element[2], upload_element[3]); };
                                                                      window.onbeforeunload = function() {};
                                                           }});
    }
  }
}

function unloadPage() {

  return "";
}

/**
 * Speichert ein Mediafile
 *
 * @author sweber
 */
function ajaxSaveMediafile(id, mode, step, savelink) {

  if (!step) {

    step = 0;
  }

  var spinner        = $('#savebtn_'+step+'_'+id);
  var saveinfo_two   = $('#saved_info_2_'+id);
  var saveinfo_three = $('#saved_info_3_'+id);

  if (spinner) {

    /*
     * Benutzer warnen falls er den Upload Prozess vorzeitig verlassen will
     */
    window.onbeforeunload = unloadPage;

    spinner.css('display', 'block');
  }

  if (saveinfo_two) {

    saveinfo_two.css('display', 'none');
  }

  if (saveinfo_three) {

    saveinfo_three.css('display', 'none');
  }

  if ($(savelink).attr('id') == 'small-save-pic' || $(savelink).attr('id') == 'small-save-span') {

    $('#license_group_spinner').show();
    $('#big-save-link-three').attr('class', 'small-btn-grey fr');
    $('#big-save-link-three').attr('onclick', '');
    $('#big-save-link-two').attr('class', 'small-btn-grey fr');
    $('#big-save-link-two').attr('onclick', '');
  } else {

    savelink.className = 'small-btn-grey fr';
    savelink.onclick   = function() { return; };
    $('#small-save-pic').attr('onclick', '');
    $('#small-save-span').attr('onclick', '');
    $('#license_group_spinner').show();
  }


  $('#edit_step_three_'+id).attr('action', $('#edit_step_three_'+id).attr('action')+'/'+mode+'/'+step);

  if (file_uploading != false) {

    /*
     * #7163: delay.
     */
    addToSaveBufferQueue(id, mode, step, savelink);
    traverseSaveBuffer();

    /*
     * save is located in traverseSaveBuffer()
     */

    return;
  } else {
    $('#edit_step_three_'+id).ajaxSubmit(
      {
        success: function(data){
          $('#data_'+id).html(data);
          savelink.className    = 'small-btn fr';
          savelink.onclick      = function() { ajaxSaveMediafile(id, mode, step, savelink); };
          window.onbeforeunload = function() {};
        }
      }
    );
  }
}

/**
 * Speichert ein Mediafile beim Gastupload
 *
 * @author sweber
 */
function ajaxSaveMediafileGuest(id) {

  var spinner = $('#savebtn');

  if (spinner) {

    spinner.css('display', 'block');
  }

  $.post('/media/ajaxEditGuest/'+id,
            $('#guestupload').serialize(),
            function(data){
              $('#data_'+id).html(data);
            }
         );
}

/**
 * Wechselt in der Uploadmaske bei einem Mediafile zwischen Step2 und 3
 *
 * @author sweber
 */
function uploadSwitchStep(id, mode) {

  if (mode == 'steptwo') {

    $('#steptwo_'+id).css('display',          'block');
    $('#stepthree_'+id).css('display',        'none');
    $('#upl_btn_two_'+id).attr('className',   'heademu_active_tab');
    $('#upl_btn_three_'+id).attr('className', 'heademu');
  } else {

    $('#steptwo_'+id).css('display',          'none');
    $('#stepthree_'+id).css('display',        'block');
    $('#upl_btn_two_'+id).attr('className',   'heademu');
    $('#upl_btn_three_'+id).attr('className', 'heademu_active_tab');
  }

}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

Base64 = {

  // private property
  _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

  // public method for encoding
  encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = Base64._utf8_encode(input);

    while (i < input.length) {

      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }

      output = output +
      this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
      this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

    }

    return output;
  },

  // public method for decoding
  decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

      enc1 = this._keyStr.indexOf(input.charAt(i++));
      enc2 = this._keyStr.indexOf(input.charAt(i++));
      enc3 = this._keyStr.indexOf(input.charAt(i++));
      enc4 = this._keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }

    }

    output = Base64._utf8_decode(output);

    return output;

  },

  // private method for UTF-8 encoding
  _utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

      var c = string.charCodeAt(n);

      if (c < 128) {
        utftext += String.fromCharCode(c);
      }
      else if((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      }
      else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }

    return utftext;
  },

  // private method for UTF-8 decoding
  _utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

      c = utftext.charCodeAt(i);

      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      }
      else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      }
      else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }

    }

    return string;
  }

}


/**
 * base64_encode
 *
 * @author sweber
 */
function encode64(inp){

  var key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var chr1, chr2, chr3, enc3, enc4, i = 0, out = "";

  while (i < inp.length) {

    chr1 = inp.charCodeAt(i++);
    if (chr1 > 127) { chr1 = 88 };

    chr2 = inp.charCodeAt(i++);
    if (chr2 > 127) { chr2 = 88 };

    chr3 = inp.charCodeAt(i++);
    if (chr3 > 127) { chr3 = 88 };

    if (isNaN(chr3)) {

      enc4 = 64;
      chr3 = 0;
    } else {

      enc4 = chr3&63
    }

    if (isNaN(chr2)) {

      enc3 = 64;
      chr2 = 0;
    } else {

        enc3 = ((chr2<<2)|(chr3>>6))&63
    }

    out += key.charAt((chr1>>2)&63)+key.charAt(((chr1<<4)|(chr2>>4))&63)+key.charAt(enc3)+key.charAt(enc4);
  }

  return encodeURIComponent(out);
}


function detectBrowserCanFileUploadHTML5() {

  check_a = typeof FileReader != 'undefined';
  check_b = 'draggable' in document.createElement('span');

  return (check_a && check_b);
}

/**
 * Originale Query speichern
 *
 * @author kscheffelmeier
 */
function saveOriginalQuery() {

  $('#query_orig').attr('value', $('#sb-searchtext').attr('value'));
}

/**
 * Query in session speichern
 *
 * @author kscheffelmeier
 */
function saveQueryInSession() {

  var query = escape($('#sb-searchtext').attr('value'));

  $.post('/system/ajaxSaveQueryInSession?sess_query='+query, {}, function () {});
}

/**
 * Autocompleter Item speichern
 *
 * @author kscheffelmeier
 */
function acSaveToHiddenFIeld(ac_item) {

  /*
   * ID holen, was in dem fall den Typ bestimmt (Kategorie, Attribut ...)
   */
  var ac_elm_type = ac_item.toString().match(/id="(.*)"/g);

  if (ac_elm_type) {

    ac_elm_type     = ac_elm_type.toString().replace('id="', '');
    ac_elm_type     = ac_elm_type.toString().replace('"', '');

  }
  $('#ac-recog').attr('value', ac_elm_type);

  /*
   * Value in das hidden field, wenn keine Ueberschrift
   */
  var search_item = ac_item.toString();
  var find        = 'ac_results_headline';
  if (search_item.indexOf(find) == -1) {

    var ac_item_formatted = unescapeHTML(ac_item);

    $('#query_ac').attr('value', ac_item_formatted);
    if (ac_elm_type == null) acFormatItem();
    else {
    	$('#sb-searchtext').attr('value', '');
    	$('#search_form').submit();
    }
  } else {

    $('#sb-searchtext').attr('value', $('#query_orig').attr('value'));
  }
}

/*
 * Fix jQuery AC string
 *
 * @author kscheffelmeier
 */
function unescapeHTML(html) {

  var htmlNode       = document.createElement("DIV");
  htmlNode.innerHTML = html;

  if (htmlNode.innerText !== undefined) {

    return htmlNode.innerText;
  } else {

    return htmlNode.textContent;
  }
}

/**
 * Autocompleter Item formatieren
 *
 * @author kscheffelmeier
 */
function acFormatItem(ac_item) {

  /*
   * Value holen und bereinigen
   */
  var orig_value    = $('#query_ac').attr('value');
  var cleaned_value = orig_value.replace(/<\/?[^>]+(>|$)/g, '');
  var cleaned_value = cleaned_value.replace(/\&amp;/g,'&');

  /*
   * Value in das Suchfeld und das hidden field
   */
  $('#query_ac').attr('value', cleaned_value);
  $('#sb-searchtext').attr('value', '"' + cleaned_value + '"');

  /*
   * Suche abschicken
   */
  $('#search_form').submit();
}

/**
 * Sortierung bei der Suche aendern
 *
 * @author kscheffelmeier
 */
function changeSortOrder(sort_mode) {

  $('#sort_mode').val(sort_mode);
}

/**
 * Alle Attribute fuer ein Suchergebnis anzeigen/ausblenden
 *
 * @author kscheffelmeier
 */
function searchShowAllAttriutes(result_pk) {

  if ($('#search_file_attr_'+result_pk).css('display') == 'none') {

    $('#search_file_attr_'+result_pk).css('display', 'block');
  } else {

    $('#search_file_attr_'+result_pk).css('display', 'none');
  }
}

/**
 * Die ganze Beschreibung fuer ein Suchergebnis anzeigen/ausblenden
 *
 * @author kscheffelmeier
 */
function searchShowFullDescription(result_pk) {

  if ($('#search_file_desc_'+result_pk).css('display') == 'none') {

    $('#search_file_desc_'+result_pk).css('display', 'block');
  } else {

    $('#search_file_desc_'+result_pk).css('display', 'none');
  }
}

/**
 * Erweiterte Suche einblenden
 *
 * @author kscheffelmeier
 */
function showAdvancedSearch() {

  var container = $('#attribute_holder_search');

  if (container.is(':visible')) {

    /*
     * Filter-Bar anzeigen
     */
    if ($('#s_filter_options_bar')) {

      //$('#s_filter_options_bar').css('visibility', 'visible');
    }

    /*
     * Hoch fahren
     */
    container.slideUp(1000);
  } else {

    /*
     * Filter-Bar ausblenden
     */
    if ($('#s_filter_options_bar')) {

      //$('#s_filter_options_bar').css('visibility', 'hidden');
    }

    /*
     * Runter fahren
     */
    container.slideDown(1000);
  }
}

/**
 * Mediafile/Recht zum Merkzettel hinzufuegen
 *
 * @author kscheffelmeier
 * @author sweber
 */
function handleWishlistFile(mediafile_id, delete_file, class_name) {

  if (!class_name) {

    class_name = '';
  }

  if (delete_file == true) {

    $('#wishlist_'+mediafile_id).load('/system/ajaxAddToWishlist/'+mediafile_id+'/'+true+'?class_name='+class_name);
  } else {

    $('#wishlist_'+mediafile_id).load('/system/ajaxAddToWishlist/'+mediafile_id+'/'+false+'?class_name='+class_name);
  }
}

/**
 * Mediafile/Recht zum Warenkorb hinzufuegen
 *
 * @author kscheffelmeier
 */
function handleCartFile(mediafile_id, delete_file, license_group_id, exclusive) {

  if (delete_file == true) {

    if (license_group_id) {

      $('#cart_'+license_group_id+'_'+exclusive).load('/system/ajaxHandleCart/'+mediafile_id+'/'+true+'/'+license_group_id+'/'+exclusive);
    }
  } else {

    if (license_group_id) {

      $('#cart_'+license_group_id+'_'+exclusive).load('/system/ajaxHandleCart/'+mediafile_id+'/'+false+'/'+license_group_id+'/'+exclusive);
    }
  }
}

count_uploads = 0;
filesUpload   = null;
dropArea      = null;
fileList      = null;


/**
 * initialisiert den Anytimyupload für HTML5-fähige Browser
 *
 * @author sweber
 */
function initAnyTimeUpload(infotext_one_caption, infotext_two_caption, infotext_three_caption, upload_area_id) {

  if (detectBrowserCanFileUploadHTML5()) {

    var upl_btn = document.getElementById(upload_area_id);

    upl_btn.addEventListener("dragleave",
                              function (evt) {
                                removeClass(this, 'active');
                                evt.preventDefault();
                                evt.stopPropagation();
                              }, false);

    upl_btn.addEventListener("dragenter",
                              function (evt) {
                                addClass(this, 'active');
                                evt.preventDefault();
                                evt.stopPropagation();
                              }, false);

    upl_btn.addEventListener("dragover",
                              function (evt) {
                                addClass(this, 'active');
                                evt.preventDefault();
                                evt.stopPropagation();
                              }, false);

    upl_btn.addEventListener("drop",

      function (evt) {

        if ($('#drop-area').length == 0) {

          if ($('#uploadoverlay').css('display') == 'none') {

            $.ajax({ async: false,
                     url: '/ajaxUpload',
                     success: function(data) {

                        $('#uploadoverlay').html(data);
                        $('#uploadoverlay').css('display', 'block');
                        $('#uploadoverlay').css('padding', '10px');
                        $('#uploadoverlay').css('height',  ($(window).height() - 150)+'px');
                        $('#uploadoverlay').css('left',    ($(document).width() / 2 - 320)+'px');
                        $('#overlay').css('display', 'block');

                        wrapper            = document.createElement('div');
                        wrapper.id         = 'uploadbox_home';

                        infotext_one       = document.createElement('img');
                        infotext_one.id    = 'upload_icon_5';
                        infotext_one.src   = '/images/v2/upload_icon_5_small.png';
                        infotext_one.title = infotext_one_caption;
                        infotext_one.alt   = infotext_one_caption;

                        infotext_two           = document.createElement('a');
                        infotext_two.href      = 'javascript:;';
                        infotext_two.innerHTML = infotext_one_caption;

                        droparea    = document.createElement('p');
                        droparea.id = 'drop-area';

                        infotext_right           = document.createElement('p');
                        infotext_right.id        = 'upload_intro_5';
                        infotext_right.innerHTML = infotext_two_caption;

                        switchlink_right           = document.createElement('a');
                        switchlink_right.id        = 'upload_btn_5';
                        switchlink_right.innerHTML = infotext_three_caption;
                        switchlink_right.href      = '/upload/classic';

                        droparea.appendChild(infotext_one);
                        droparea.appendChild(infotext_two);

                        wrapper.appendChild(droparea);
                        wrapper.appendChild(infotext_right);
                        wrapper.appendChild(switchlink_right);

                        document.getElementById('mainuploadfield').appendChild(wrapper);

                        initHTML5Upload();
                      }
                    });
          }
        }

        traverseFiles(evt.dataTransfer.files);

        evt.preventDefault();
        evt.stopPropagation();

      }, false);

    if (typeof traverseFiles != 'function') {

      autoload = false;

      document.write('<SCR'+'IPT src="/js/html5upload.js"><\/SCR'+'IPT>');
    }
  }
}

/**
 * Öffnet ein Overlay zum Empfehlen per E-Mail
 *
 * @author sweber
 */
function openMailRecommendationOverlay(url) {

  $.get('/system/recommendByMail/'+url, {}, function (data) {

                                              $('#uploadoverlay').html(data);
                                              $('#uploadoverlay').css('display', 'block');
                                              $('#uploadoverlay').css('width',   '400px');
                                              $('#uploadoverlay').css('top',     '50px');
                                              $('#uploadoverlay').css('padding', '10px');
                                              $('#uploadoverlay').css('height',  '380px');
                                              $('#uploadoverlay').css('left',    ($(document).width() / 2 - 200)+'px');
                                              $('#overlay').css(      'display', 'block');
                                              $('#mypholder').css(    'display', 'none');
                                            });
}


/**
 *
 */
function doMailRecommendation() {

  $.post('/system/recommendByMail/false',
         $('#recommend_mail').serialize(),
         function(data){ $('#uploadoverlay').html(data); } );
}

/**
 * Schliesst das Uploadoverlay
 *
 * @author sweber
 */
function closeUploadOverlay() {

  $('#uploadoverlay').html('');
  $('#uploadoverlay').css( 'display', 'none');
  $('#overlay').css(       'display', 'none');
  $('#mypholder').css(     'display', 'block');
  count_uploads = 0;
}

/**
 * Schliesst ein Overlay
 *
 * @author kscheffelmeier
 */
function closeOverlay(overlay_name) {


  $('#'+overlay_name).css('display', 'none');
  $('#overlay').css(      'display', 'none');

  if ($('#mypholder')) {

    $('#mypholder').css('display', 'block');
  }
}

/**
 * Schliesst ein Overlay aus einem Iframe heraus
 *
 * @author nschulze
 */
function closeOverlayFromIframe(overlay_name) {

  $(top.document.getElementById(overlay_name));
  $(top.document.getElementById(overlay_name)).css( 'display', 'none');
  $(top.document.getElementById('overlay')).css(    'display', 'none');

  if ($(top.document.getElementById('mypholder'))) {

    $('#mypholder').css('display', 'block');
  }
}

/**
 * Account DD anzeigen
 *
 * @author kscheffelmeier
 */
function handleAccountDropDown(mouseout) {

  if (mouseout == true) {

    mouseout = true;
  } else {

    mouseout = false;
  }

  if (mouseout == true && account_dd == true) {

    $('#account_dd').css('display', 'none');
    account_dd = false;

    return true;
  } else if (mouseout == false && account_dd == false) {

    $('#account_dd').css('display', 'block');
    account_dd = true;

    return true;
  } else {

    return true;
  }
}

/**
 * Mediafile Report-Dialog anzeigen
 *
 * @author kscheffelmeier
 */
function showMediafileReportDialog(mediafile_id, logged_out) {

  if ($('#reportoverlay').css('display') == 'none') {

    $('#mypholder').css('display', 'none');

    if (logged_out === true) {

      var template = 'ajaxReportMediafileLoggedOut';
      var osize    = '225px';
    } else {

      var template = 'ajaxReportMediafile';
      var osize    = '375px';
    }

    $.get('/media/'+template+'?mediafile_id='+mediafile_id, {}, function (data) {

                                                $('#reportoverlay').html(data);
                                                $('#reportoverlay').css('display', 'block');
                                                $('#reportoverlay').css('width',   '400px');
                                                $('#reportoverlay').css('top',     '50px');
                                                $('#reportoverlay').css('padding', '10px');
                                                $('#reportoverlay').css('height',   osize);
                                                $('#reportoverlay').css('left',    ($(document).width() / 2 - 200)+'px');
                                                $('#overlay').css('display', 'block');
                                              });
  } else {

    $('#reportoverlay').css('display', 'none');
    $('#mypholder').css(    'display', 'block');
  }
}

/**
 * Mediafile-Report abschicken
 *
 * @author kscheffelmeier
 */
function sendMediafileReport(mediafile_id) {

  $.post('/media/ajaxReportMediafile?mediafile_id='+mediafile_id,
         $('#report_form').serialize(),
         function(data){

           $('#reportoverlay').html(data);
         });
}

/**
 * Mediafile-Report abschicken fuer nicht angemeldete Benutzer
 *
 * @author kscheffelmeier
 */
function sendMediafileReportLoggedOut(mediafile_id) {

  $.post('/media/ajaxReportMediafileLoggedOut?mediafile_id='+mediafile_id,
         $('#report_form').serialize(),
         function(data) {

           $('#reportoverlay').html(data);
         });
}

/**
 * Mediafile löschen
 *
 * @author kscheffelmeier
 * @author sweber
 */
function deleteMediafile(mediafile_id, mode) {

  if ($('#deleteoverlay').css('display') == 'none') {

    $('#mypholder').css('display', 'none');
    $.get('/media/ajaxDeleteMediafile/'+mediafile_id+'/'+mode, {}, function (data) {

                                                $(document).keypress(function(event) {

                                                  var keycode = (event.keyCode ? event.keyCode : event.which);

                                                  if (keycode == '13') {

                                                    $('#delete_flag').attr('value', 1); doDeleteFile(mediafile_id, mode);
                                                  }
                                                });

                                                $('#deleteoverlay').html(data);
                                                $('#deleteoverlay').css('display', 'block');
                                                $('#deleteoverlay').css('width',   '400px');
                                                $('#deleteoverlay').css('top',     ($(window).height() / 2 - 39)+'px');
                                                $('#deleteoverlay').css('padding', '10px');
                                                $('#deleteoverlay').css('height',  '78px');
                                                $('#deleteoverlay').css('left',    ($(document).width() / 2 - 200)+'px');
                                                $('#overlay').css('display', 'block');
                                              });

  } else {

    $('#deleteoverlay').css('display', 'none');
    $('#mypholder').css('display',     'block');
  }
}

/**
 * Mediafile löschen
 *
 * @author kscheffelmeier
 */
function doDeleteFile(mediafile_id, mode) {

  $.post('/media/ajaxDeleteMediafile/'+mediafile_id+'/'+mode,
         $('#delete_form').serialize(),
         function(data){ $('#deleteoverlay').html(data); } );
}

/**
 * Highlight Stern
 *
 * @author kscheffelmeier
 * @param  obj
 * @param  integer n
 */
function ratingStarOver(obj, n) {

  var i = 0;

  for (i; i < 5; i++) {

    obj.parentNode.getElementsByTagName('img')[i].src = '/images/v2/star_grey.png';
  }

  var i = 1;

  for (i; i <= n; i++) {

    obj.parentNode.getElementsByTagName('img')[(i-1)].src = '/images/v2/star_blue.png';
  }
}

/**
 * Hhighlight vom Stern entfernen
 *
 * @author kscheffelmeier
 * @param  obj
 * @param  string name
 */
function ratingStarOut(obj, name) {

  if (given[name] != 0) {

    setTo = given[name];
  } else {

    setTo = 0;
  }
  var i = 0;

  for (i; i < 5; i++) {

    obj.parentNode.getElementsByTagName('img')[i].src = '/images/v2/star_grey.png';
  }

  var i = 1;

  for (i; i <= setTo; i++) {

    obj.parentNode.getElementsByTagName('img')[(i-1)].src = '/images/v2/star_blue.png';
  }
}

/**
 * (de-)aktiviert das Enddatum einer Rechtegruppe
 *
 * @author sweber
 */
function handleLicenseGroupEnd(input, license_group_id) {

  $('#edit_step_three_'+license_group_id+'_enddate').attr('disabled', input.checked);
  if (input.checked) {

    $('#edit_step_three_'+license_group_id+'_enddate').css('background-color', '#D8D8D8');
    $('#edit_step_three_' + license_group_id + '_enddate_btn').removeClass('date-pik');
  } else {

    $('#edit_step_three_'+license_group_id+'_enddate').css('background-color', 'white');
    $('#edit_step_three_' + license_group_id + '_enddate_btn').addClass('date-pik');
  }
  $('#edit_step_three_'+license_group_id+'_enddate').val('');
}

/**
 * toggles the enddate input when the box is checked after an ajax call
 *
 * @author nschulze
 */
function toggleLicenseEnds( license_group_id ) {

  $('#license_set_' + license_group_id).ready(function() {

    var checkbox = $('#edit_step_three_'+license_group_id+'_is_openend')

    if (checkbox.is(':checked')) {

      $('#edit_step_three_' + license_group_id + '_enddate').attr('disabled', true);
      $('#edit_step_three_' + license_group_id + '_enddate').attr('value', '');
      $('#edit_step_three_' + license_group_id + '_enddate').css('background-color', '#D8D8D8');
      $('#edit_step_three_' + license_group_id + '_enddate_btn').removeClass('date-pik');
    } else {

      $('#edit_step_three_' + license_group_id + '_enddate').removeAttr('disabled');
      $('#edit_step_three_' + license_group_id + '_enddate').css('background-color', 'white');
      $('#edit_step_three_' + license_group_id + '_enddate_btn').addClass('date-pik');
    }
  });
}

/**
 * Stern setzen
 *
 * @author kscheffelmeier
 * @param  obj
 * @param  integer n
 * @param  string  name
 */
function ratingStarFix(obj, n, name) {

  var i = 0;

  for (i; i < 5; i++) {

    obj.parentNode.getElementsByTagName('img')[i].src = '/images/v2/star_grey.png';
  }

  var i = 1;

  for (i; i <= n; i++) {

    obj.parentNode.getElementsByTagName('img')[(i-1)].src = '/images/v2/star_blue.png';
  }

  document.getElementById('user_comment_rank').value = n;

  given[name] = n;

  obj.parentNode.className = 'fixed';

  return false;
}

/**
 * AC ausblenden
 *
 * @author kscheffelmeier
 */
function hideAC() {

  $('.ac_results').css('display', 'none');
}

/**
 * Feedback verschicken
 *
 * @author kscheffelmeier
 */
function sendFeedback() {

  $.post('/system/ajaxShowFeedbackOverlay',
         $('#feedback_form').serialize(),
         function(data){ $('#feedbackoverlay').html(data); } );
}

/**
 * Feedback verschicken
 *
 * @author kscheffelmeier
 * @author nschulze
 *
 * @version 1.0 initial
 * @version 1.1 fixed window.location and replaced it with a function
 */
function clearSearchField(location) {

  if (location) {

    $('#sb-searchtext').attr('value', '');
    $.post('/system/ajaxDeleteSearchStringFromSession', {}, function() {

      jsRedirect( location );
    });
  } else {

    $('#sb-searchtext').attr('value', '');
    $.post('/system/ajaxDeleteSearchStringFromSession', {}, function() {});
  }
}

/**
 * Zeigt oder versteckt die Länderliste im Warenkorb
 *
 * @author sweber
 */
function showCartEntryCountries(id) {

  var clist        = $('#cart_entry_'+id+'_countries');
  var closed_span  = $('#cart_entry_'+id+'_switch');
  var openend_span = $('#cart_entry_'+id+'_switch_hidden');

  if (clist.css('display') == 'none') {

    clist.css(       'display', 'block');
    closed_span.css( 'display', 'none');
    openend_span.css('display', 'block');
  } else {

    clist.css(       'display', 'none');
    closed_span.css( 'display', 'block');
    openend_span.css('display', 'none');
  }
}

/**
 * Aktualisiert eine Rechtegruppe anhand einer Vorlage
 *
 * @author sweber
 */
function setLicenseGroupFromPreset(license_group_id, preset_select) {

  var preset_id = preset_select.options[preset_select.options.selectedIndex].value;

  $.get('/media/ajaxLoadLicenseGroupPreset/'+license_group_id+'/'+preset_id, {}, function (data) { $('#buf_'+license_group_id).html(data); });
}

/**
 * Die ausgewaehlten Werte in der Advanced Search anzeigen
 *
 * @author kscheffelmeier
 */
function showSelectedAttributesForAds() {

  elements = $('.box-toggle-container input:checked');
  elements.each(function() {

    /*
     * Headline mit Wert befuellen
     */
    input_id      = $(this).attr('id');
    input_id      = input_id.replace('attr_', '');

    holder        = $(this).parent().parent().parent().parent();
    headline      = holder.children('a');

    headline_old  = headline.html();

    if (headline_old) {

      if (headline_old.search('[...]') == -1) {

        headline_new = headline_old+ ' '+$('#attr_txt_'+input_id).html()+ ' [...]';
      }

      headline.html(headline_new);
    }
  });

  elements = $('.box-toggle-container .attributeSelect');
  
  elements.each(function() {
    if ($(this).val() == '') return;
    holder = $(this).parent().parent().parent();
    headline = holder.children('a');
    headline_old = headline.html();
    if (headline_old) {
      if (headline_old.search('[...]') == -1) {
        headline_new = headline_old+ ' '+ $(this).children().children(':selected').text()+ ' [...]';
      }
      headline.html(headline_new);
    }
  });
}

/**
 * Cursor im Feld
 *
 * @author kscheffelmeier
 */
function placeCursorInField() {

  $('#entered_code').focus();
}

/**
 * Input-Felder leeren
 *
 * @author kscheffelmeier
 */
function clearInput(input_field, blur) {

  if (blur) {

    if ($('#'+input_field.id).val() == '') {

      $('#'+input_field.id).attr('value', $('#'+input_field.id).attr('title'));
    }
  } else {

    if ($('#'+input_field.id).attr('title') == $('#'+input_field.id).val()) {

      $('#'+input_field.id).attr('value', '');
    }
  }
}

/**
 * Input-Felder leeren
 *
 * @author kscheffelmeier
 */
function submitForm(form_id) {

  $('#'+form_id).submit();
}

/**
 * toggles the enddate field when open end is checked
 *
 * @author nschulze
 */
function toggleBidDate() {

  var checkbox = $('#bidding_is_openend');
  var element  = '#bidding_enddate';
  if (checkbox.is(':checked')) {


    $(element).attr('disabled', true);

    if ($(element).attr('type') == "checkbox") {

      $(element).attr('checked', false);
    } else {

      $(element).attr('value', '');
    }

    if ($(element).hasClass('rounded_input')) {

      $(element).css('background-color','#D8D8D8');
    }
  } else {

    $(element).removeAttr('disabled');
    if ($(element).hasClass('rounded_input')) {

      $(element).css('background-color','white');
    }
  }
}

/**
 * unchecks all countries or mediarights
 *
 * @author nschulze
 */
function uncheckAll( mode ) {

  if (mode == "countries") {

    $('#bid_countries input').each(function(i, elem) {

      $(elem).attr('checked', false);
    });

    $('#country_switch_uncheck').css('display','none');
    $('#country_switch_check').css('display','block');
  } else {

    $('#bid_mediarights input').each(function(i, elem) {

      $(elem).attr('checked', false);
    });

    $('#mediaright_switch_uncheck').css('display','none');
    $('#mediaright_switch_check').css('display','block');
  }
}

/**
 * checks all countries or mediarights
 *
 * @author nschulze
 */
function checkAll( mode ) {

  if (mode == "countries") {

    $('#bid_countries input').each(function(i, elem) {

      $(elem).attr('checked', true);
    });

    $('#country_switch_check').css('display','none');
    $('#country_switch_uncheck').css('display','block');
  } else {

    $('#bid_mediarights input').each(function(i, elem) {

      $(elem).attr('checked', true);
    });

    $('#mediaright_switch_check').css('display','none');
    $('#mediaright_switch_uncheck').css('display','block');
  }
}

function initBidMask( mode ) {

  if (mode == "create") {

    $('#bidding_bid_currency').attr('disabled', true);
    $('#bidding_bid_currency').css('background-color','#D8D8D8');

  } else if (mode == "counteroffer") {

      /*
       * set listener for counter price
       */
      //$('#bidding_bid_price').keypress(
      //  function() {

      //    counterofferBidPriceCheck();
      //  }
      //);

      $('#bid_form input').each(

      function(index, element) {

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

        if (id != 'bidding_bid_price' && id != 'bidding__csrf_token') {

          $(element).attr('disabled', true);
          if ($(element).hasClass('rounded_input')) {

            $(element).css('background-color','#D8D8D8');
          }
        }
      }
    );

    $('#bid_form select').each(

      function(index, element) {

        $(element).attr('disabled', true);
        if ($(element).hasClass('rounded_input')) {

          $(element).css('background-color','#D8D8D8');
        }
      }
    );

    $('#country_switch_check').css('display','none');
    $('#mediaright_switch_check').css('display','none');
    $('#country_switch_uncheck').css('display','none');
    $('#mediaright_switch_uncheck').css('display','none');

    $('#bidding_startdate_btn').removeClass('date-pik');
    $('#bidding_enddate_btn').removeClass('date-pik');

    $('#bidding_bid_price').removeAttr('disabled');
  } else {

    $('#bid_form input').each(

      function(index, element) {

        $(element).attr('disabled', true);

        if ($(element).hasClass('rounded_input')) {

          $(element).css('background-color','#D8D8D8');
        }
      }
    );

    $('#bid_form select').each(

      function(index, element) {

        $(element).attr('disabled', true);
        if ($(element).hasClass('rounded_input')) {

          $(element).css('background-color','#D8D8D8');
        }
      }
    );

    $('#country_switch_check').css('display','none');
    $('#mediaright_switch_check').css('display','none');
    $('#bidding_startdate_btn').removeClass('date-pik');
    $('#bidding_enddate_btn').removeClass('date-pik');
  }
}

/**
 * when reload the page toggle the right span with the right onclick
 * at the bid mask
 *
 * @author nschulze
 */
function toggleBidMaskCountrieMediarights() {

  var all_media_count     = $('#bid_mediarights > ul > li').size();
  var all_countries_count = $('#bid_countries > ul > li').size();

  var check_media_count     = 0;
  var check_countries_count = 0;

  $('#bid_countries input').each(function(i, elem) {

    if ($(elem).attr('checked') == true) {

      check_countries_count++;
    }
  });

  if (check_countries_count == all_countries_count) {

    $('#country_switch_check').css('display','none');
    $('#country_switch_uncheck').css('display','block');
  }

    $('#bid_mediarights input').each(function(i, elem) {

    if ($(elem).attr('checked') == true) {

      check_media_count++;
    }
  });

  if (check_media_count == all_media_count) {

    $('#mediaright_switch_check').css('display','none');
    $('#mediaright_switch_uncheck').css('display','block');
  }
}

/**
 * check the over all check box count
 * of all mediaright checkboxes to
 * toggle the "select all" span
 *
 * @author nschulze
 */
function checkMediarightCount() {

  var all_elements        = $('#bid_mediarights > ul > li > input');
  var all_media_count     = all_elements.size();
  var current_media_count = 0;

  all_elements.each(function(index, element) {

    if ($(element).attr('checked') == true) {

      current_media_count++;
    }
  });

  if (current_media_count == all_media_count) {

    $('#mediaright_switch_check').css('display','none');
    $('#mediaright_switch_uncheck').css('display','block');
  } else {

    $('#mediaright_switch_check').css('display','block');
    $('#mediaright_switch_uncheck').css('display','none');
  }
}

/**
 * check the over all check box count
 * of all countryright checkboxes to
 * toggle the "select all" span
 *
 * @author nschulze
 */
function checkCountryrightCount() {

  var all_elements          = $('#bid_countries > ul > li > input');
  var all_country_count     = all_elements.size();
  var current_country_count = 0;

  all_elements.each(function(index, element) {

    if ($(element).attr('checked') == true) {

      current_country_count++;
    }
  });

  if (current_country_count == all_country_count) {

    $('#country_switch_check').css('display','none');
    $('#country_switch_uncheck').css('display','block');
  } else {

    $('#country_switch_check').css('display','block');
    $('#country_switch_uncheck').css('display','none');
  }
}

/**
 * simple javscript redirect function
 *
 * @author nschulze
 */
function jsRedirect( url ) {
  window.location.href = url;
}

/**
 * processing function for the bid process
 *
 * @author nschulze
 */
function processBidding( url , id, redirect) {

  closeOverlay('feedbackoverlay');

  if (redirect === true) {

    jsRedirect( url );
  } else {

    $('#bid_' + id).load(url);
  }
}

/**
 * overlay "confirm()" function
 *
 * @author nschulze
 */
function confirmBidAction( url, type , view , bid_pk) {

  $.get(url, { btn_type: type, bid_view: view, bid_id: bid_pk }, function ( data ) {

      /*
       * load html to overlay
       */
      $('#feedbackoverlay').html(data);
      $('#feedbackoverlay').css('display', 'block');
      $('#feedbackoverlay').css('width',   '400px');
      $('#feedbackoverlay').css('top',     '50px');
      $('#feedbackoverlay').css('padding', '10px');
      $('#feedbackoverlay').css('height',  'auto');
      $('#feedbackoverlay').css('left',    ($(document).width() / 2 - 200)+'px');
      $('#overlay').css('display', 'block');
    }
  );
}

/**
 * overlay "confirm()" function
 *
 * @author nschulze
 */
function showConfirmBidCreate(url) {

  $.get(url, {}, function ( data ) {

      /*
       * load html to overlay
       */
      $('#feedbackoverlay').html(data);
      $('#feedbackoverlay').css('display', 'block');
      $('#feedbackoverlay').css('width',   '400px');
      $('#feedbackoverlay').css('top',     '50px');
      $('#feedbackoverlay').css('padding', '10px');
      $('#feedbackoverlay').css('height',  'auto');
      $('#feedbackoverlay').css('left',    ($(document).width() / 2 - 200)+'px');
      $('#overlay').css('display', 'block');
    }
  );
}

/**
 * submit bid create
 *
 * @author nschulze
 */
function confirmBidCreate() {

  closeOverlay('feedbackoverlay');
  window.setTimeout( function(){ $('#bid_form').submit(); } , 100);
}

/**
 * disables all inputs which are not allowed to set for bidding
 *
 * @author nschulze
 */
function toggleBiddingAllowed( id ) {

  $('#license_set_' + id).ready(function() {

    var checkbox = $('#edit_step_three_' + id + '_bidding_allowed');

    if (checkbox.is(':checked')) {

      $('#license_set_' + id + ' input').each(

        function(index, element) {

          jQelement = $(element);
          if (jQelement.attr('id') != 'edit_step_three_' + id + '_name' && jQelement.attr('id') != 'edit_step_three_' + id + '_bidding_allowed') {

            if (jQelement.attr('type') == 'checkbox') {

            //  jQelement.attr('checked', false);
              jQelement.attr('readonly', true);
            } else if (jQelement.attr('type') == 'text') {

            //  jQelement.attr('value', '');
              jQelement.attr('readonly', true);
            }

             if (jQelement.hasClass('rounded_input')) {

              jQelement.css('background-color','#D8D8D8');
            }
          }
        }
      );

      $('#license_set_' + id + ' select').each(

        function(index, element) {

          jQelement = $(element);
          if (jQelement.attr('id') != 'edit_step_three_' + id + '_instantbuy_currency' && jQelement.attr('id') != 'edit_step_three_' + id + '_licensegroup_presets') {

            jQelement.attr('readonly', true);

            if (jQelement.hasClass('rounded_input')) {

              jQelement.css('background-color','#D8D8D8');
            }
          }
        }
      );

      $('#country_' + id + '_switch').css('display', 'none');
      $('#mediaright_' + id + '_switch').css('display', 'none');
      $('#edit_step_three_' + id + '_startdate_btn').removeClass('date-pik');
      $('#edit_step_three_' + id + '_enddate_btn').removeClass('date-pik');
    } else {

      $('#license_set_' + id + ' input').each(

        function(index, element) {

          jQelement = $(element);
          if (jQelement.attr('id') != 'edit_step_three_' + id + '_name') {

            if (jQelement.attr('id') == 'edit_step_three_' + id + '_enddate') {

              if ($('#edit_step_three_' + id + '_is_openend').attr('checked') == false) {
                jQelement.removeAttr('readonly');
                $(element).css('background-color','white');
              } else {
                jQelement.attr('readonly', true);
                $('#edit_step_three_' + id + '_enddate_btn').removeClass('date-pik');
                jQelement.css('background-color','#D8D8D8');
              }
            } else {

              jQelement.removeAttr('readonly');

              if ($(element).hasClass('rounded_input')) {

                $(element).css('background-color','white');
              }
            }
          }
        }
      );

      $('#license_set_' + id + ' select').each(

        function(index, element) {

          jQelement = $(element);
          if (jQelement.attr('id') != 'edit_step_three_' + id + '_instantbuy_currency') {

            jQelement.removeAttr('readonly');

            if ($(element).hasClass('rounded_input')) {

               $(element).css('background-color','white');
            }
          }
        }
      );

      $('#country_' + id + '_switch').css('display', 'block');
      $('#mediaright_' + id + '_switch').css('display', 'block');
      $('#edit_step_three_' + id + '_startdate_btn').addClass('date-pik');
      if ($('#edit_step_three_' + id + '_is_openend').attr('checked') == false) {

        $('#edit_step_three_' + id + '_enddate_btn').addClass('date-pik');
      }
    }
  });
}

/**
 * check if the counteroffer price is lower or equal
 *
 * -- not in use --

 * @author nschulze
 */
function counterofferBidPriceCheck() {

  var note        = $('#counteroffer_note');
  var prebid_val  = $('#prebid_price').attr('value');
  var current_val = $('#bidding_bid_price').attr('value');

  if (current_val != "") {

    var prebid_price  = parseInt(prebid_val);
    var current_price = parseInt(current_val);

    if ( (!isNaN(prebid_price) && typeof(prebid_price) == 'number') && (!isNaN(current_price) && typeof(current_price) == 'number') ) {


      if (prebid_price >= current_price) {

        /*
         * note: old price was higher
         */
         note.text();
      }
    } else {

      /*
       * note: pls check value
       */
    }
  } else {

    /*
     * note: pls enter value
     */
  }
}

/**
 * Select mediafiles to edit
 *
 * @author kscheffelmeier
 */
function selectMediaFilesToEdit(option) {

   switch (option) {
     case 1:
      $('.sel_edit_checkbox').each(function() {
        $(this).attr('checked', true);
      });
      break;

     case 2:

      $('.sel_edit_checkbox').each(function() {

        if ($(this).attr('checked') === true) {

          $(this).attr('checked', false);
        }
      });
      break;

     case 3:

      $('.sel_edit_checkbox').each(function() {

        if ($(this).attr('checked') === false) {

          $(this).attr('checked', true);
        } else {

          $(this).attr('checked', false);
        }
      });
      break;
   }
}

/**
 * Post selected data for batch editing
 * to an action
 *
 * @author nschulze
 */
function loadEditMaskForSelectedData(mode, option, url) {

  /*
   * dont perform logic for default values
   */
  if (option == 0) {

    return;
  }
  /*
   * get pk's out of selected checkboxes
   */
  var pk_array = [];
  $('.sel_edit_checkbox').each(function(index, element) {

    if ($(element).is(':checked')) {

      var current_pk = $(element).attr('id');
      var striped_pk = current_pk.replace(/sel_edit_/g, "");
      pk_array.push(striped_pk);
    }
  });

  $.post(url, { edit_mode: mode, edit_option: option, mediafile_ids: pk_array }, function ( data ) {

      /*
       * load html to overlay
       */
      var padding = 200;
      if (mode == 'tags' && option == 3) {

        padding = 300;
      }
      $('#feedbackoverlay').html(data);
      $('#feedbackoverlay').css('display', 'block');
      $('#feedbackoverlay').css('width',   'auto');
      $('#feedbackoverlay').css('top',     '50px');
      $('#feedbackoverlay').css('padding', '10px');
      $('#feedbackoverlay').css('height',  'auto');
      $('#feedbackoverlay').css('left',    ($(document).width() / 2 - padding)+'px');
      $('#overlay').css('display', 'block');
    }
  );
}

/**
 * processing function for batch process
 *
 * @author nschulze
 */
function processBatch() {

  var url = location.href;

  $('#content').load(url, function() { closeOverlay('feedbackoverlay'); });

}

/**
 * processing function for batch process out of an iframe
 *
 * @author nschulze
 */
function processBatchOutOfIframe() {

  var url = top.location.href;

  /*
   * ie8 wont load and ie9 wont close the overlay
   * out of the iframe so we treat them special
   */
  var ver = getInternetExplorerVersion();
  if (ver == 8.0 || ver == 9.0) {

    top.location.href = url
  } else {

    $(top.document.getElementById('content')).load(url, function() { closeOverlayFromIframe('feedbackoverlay'); });
  }
}

/**
 * loads the action to delete selected mediafiles
 *
 * @author nschulze
 */
function ajaxProcessDeleteBatchForm(url) {

  /*
   * display the spinner and disable the buttons
   * to avoid multiple ajax calls
   */
  $('#batch_spinner').css('display', 'block');
  $('#batch_form a').each(
    function(index, element) {

      $(element).attr('onclick', '');
    }
  );
  $('#close_batch_overlay_img').attr('onclick', '');

  $.post(url, $('#batch_form').serializeArray(), function() {

      /*
       * to avoid js/css failures
       * we set the spinner to display none afterwards
       */
      $('#batch_spinner').css('display', 'none');
      processBatch();
    }
  );
}

/**
 * send the post data via ajax for batching inside the overlay
 *
 * @author nschulze
 */
function ajaxProcessBatchForm(url) {

  /*
   * display the spinner and disable the buttons
   * to avoid multiple ajax calls
   */
  $('#batch_spinner').css('display', 'block');
  $('.batch_btn_holder a').each(
    function(index, element) {

      $(element).attr('onclick', '');
    }
  );

  $('#batch_form a').each(
    function(index, element) {

      $(element).attr('onclick', '');
    }
  );

  $('#close_batch_overlay_img').attr('onclick', '');

  $.post(url, $('#batch_form').serializeArray(), function ( data ) {

      /*
       * load html to overlay
       */
      $('#feedbackoverlay').html(data);
      $('#feedbackoverlay').css('display', 'block');
      $('#feedbackoverlay').css('width',   'auto');
      $('#feedbackoverlay').css('top',     '50px');
      $('#feedbackoverlay').css('padding', '10px');
      $('#feedbackoverlay').css('height',  'auto');
      $('#feedbackoverlay').css('left',    ($(document).width() / 2 - 200)+'px');
      $('#overlay').css('display', 'block');

      /*
       * to avoid js/css failures
       * we set the spinner to display none afterwards
       */
      $('#batch_spinner').css('display', 'none');
    }
  );
}

/**
 * send the post data via ajax for batching attributes
 * inside the overlay
 *
 * @author nschulze
 */
function ajaxProcessBatchFormForAttributes(url) {

  /*
   * display the spinner and disable the buttons
   * to avoid multiple ajax calls
   */
  $('#batch_spinner').css('display', 'block');
  $('.batch_btn_holder a').each(
    function(index, element) {

      $(element).attr('onclick', '');
    }
  );

  $('#batch_form a').each(
    function(index, element) {

      $(element).attr('onclick', '');
    }
  );

  $('#close_batch_overlay_img').attr('onclick', '');

  $.post(url, $('#batch_form').serializeArray(), function ( data ) {

      /*
       * load html to overlay
       */
      $('#feedbackoverlay').html(data);
      $('#feedbackoverlay').css('display', 'block');
      $('#feedbackoverlay').css('width',   'auto');
      $('#feedbackoverlay').css('top',     '50px');
      $('#feedbackoverlay').css('padding', '10px');
      $('#feedbackoverlay').css('height',  'auto');
      $('#feedbackoverlay').css('left',    ($(document).width() / 2 - 300)+'px');
      $('#overlay').css('display', 'block');

      /*
       * to avoid js/css failures
       * we set the spinner to display none afterwards
       */
      $('#batch_spinner').css('display', 'none');
    }
  );
}

/**
 * loads the action to delete selected mediafiles
 *
 * @author nschulze
 */
function loadBatchDelete(url) {

  /*
   * get pk's out of selected checkboxes
   */
  var pk_array = [];
  $('.sel_edit_checkbox').each(function(index, element) {

    if ($(element).is(':checked')) {

      var current_pk = $(element).attr('id');
      var striped_pk = current_pk.replace(/sel_edit_/g, "");
      pk_array.push(striped_pk);
    }
  });

  $.get(url, { mediafile_pks: pk_array }, function ( data ) {

      /*
       * load html to overlay
       */
      $('#feedbackoverlay').html(data);
      $('#feedbackoverlay').css('display', 'block');
      $('#feedbackoverlay').css('width',   'auto');
      $('#feedbackoverlay').css('top',     '50px');
      $('#feedbackoverlay').css('padding', '10px');
      $('#feedbackoverlay').css('height',  'auto');
      $('#feedbackoverlay').css('left',    ($(document).width() / 2 - 200)+'px');
      $('#overlay').css('display', 'block');
    }
  );
}

/**
 * loads the action to delete selected mediafiles
 *
 * @author nschulze
 */
function ajaxProcessIframeUploadBatchForm() {

  /*
   * display the spinner and disable the buttons
   * to avoid multiple ajax calls
   */
  $(document.getElementById('batch_spinner')).css('display', 'block');
  $(document.getElementById('iframe_btn_holder')).children('a').each(
    function(index, element) {

      $(element).attr('onclick', '');
    }
  );
  $(document.getElementById('close_batch_overlay_img')).attr('onclick', '');

  $('#batch_form').submit();
}

/**
 * Copyright: add another copyright row
 *
 * @author kscheffelmeier
 */
function addAnotherCopyrightRow(holder_id, holder_class) {

  /*
   * Original element
   */
  holder_elm = $('#'+holder_id);

  /*
   * Clone original element and insert after
   */
  var elm_to_add_after = $('.'+holder_class+':last');
  var clone_holder_elm = holder_elm.clone();
  clone_holder_elm.insertAfter(elm_to_add_after);
  clone_holder_elm.attr('id', clone_holder_elm.attr('id')+'_'+$('.edit_step_two_copyright_composed').length);
  clone_holder_elm.find('input').attr('value', '');

  /*
   * Find add icon, replace it with an delete icon
   */
  var clone_img = clone_holder_elm.find('img');
  clone_img.attr('src', '/images/v2/delete.png');

  /*
   * Remove old onclick function and bind a new one
   */
  clone_img.removeAttr('onclick');
  clone_img.bind('click', function() {

    clone_holder_elm.remove();
  });
}

/**
 * Check if preview length has changed
 *
 * @author kscheffelmeier
 */
function checkPreviewLengthChange() {

  $('#edit_step_two_preview_length, #edit_step_two_preview_start').bind('keyup', function() {

    $('#edit_step_two_preview_full_length').removeAttr('checked');
  });
}

/**
 * Check if full preview length has changed
 *
 * @author kscheffelmeier
 */
function checkFullPreviewLengthChange() {

  $('#edit_step_two_preview_full_length').change(function() {

    if ($('#edit_step_two_preview_full_length').attr('checked') === true) {

      $('#edit_step_two_preview_start').val('0');
      $('#edit_step_two_preview_length').val($('#edit_step_two_preview_full_length_value').val());
    }
  });
}

/**
 * Close saved license group and open a new one
 *
 * @author kscheffelmeier
 */
function closeSavedLicensegroupAndOpenNew(mediafile_id) {

  /*
   * Close saved license group
   */
  $('#toggle_box_0').removeClass('box-open');

  /*
   * Add new license group
   */

  //addLicenseGroup(mediafile_id);
}

/**
 * Advanced Search: select/deselect all countries
 *
 * @author kscheffelmeier
 */
function adCheckAllCountries() {

  if ($('#advanced-search-country-check').html() == 'None') {

    $('.country_input').each(function() {

      $(this).removeAttr('checked');
    });

    $('#advanced-search-country-check').html('Check all');
  } else {

    $('.country_input').each(function() {

      $(this).attr('checked', 'checked');
    });

    $('#advanced-search-country-check').html('None');
  }
}

function bindSelectAttributesButtons(attribute) {
	$('.box-toggle-container a[rel="' +  attribute + '-delete-btn"]').click(function() {
		$(this).parent().slideUp('fast', function() {
			$(this).children('select').selectOptions('', true);
			$(this).children('a[rel="' +  attribute + '-add-btn"]').hide();
			result = scanFreeUsedSelectAttributes(attribute);
			if (result.used.length != 0) {
				if (result.free.length > 0) $('#' + attribute + '-add-btn-' + result.used.pop()).fadeIn();
			}
		});
		return false;
	});
	$('.box-toggle-container a[rel="' +  attribute + '-add-btn"]').each(function() {
		$(this).prev().change(function() {
			selectedValue = $(this).val();
			if (selectedValue != '') {
				id = $(this).attr('id');
				id = id.split('_');
				id = id[1];
				result = scanFreeUsedSelectAttributes(attribute);
				if (result.used.length != 0) {
					selectedValue = selectedValue.split('_');
					selectedValue = selectedValue[1];
					$.each(result.used, function(index, value) {
						if (value != id) {
							comparedValue = $('#attr_' + value).val().split('_');
							comparedValue = comparedValue[1];
							if (selectedValue == comparedValue) {
								$('#attr_' + id).selectOptions('', true);
							}
						}
					});
				}
			}
		});
	});
	$('.box-toggle-container a[rel="' +  attribute + '-add-btn"]').click(function() {
		var result;
		result = scanFreeUsedSelectAttributes(attribute);
		if (result.free.length == 0) return false;
		$(this).fadeOut();
		id = result.free.shift();
		$('#attr_' + id).parent().slideDown();
		$('#attr_' + id).bind('change', {attribute: attribute}, changeSelectAttributesCallback);
		return false;
	});
	initSelectAttributes(attribute);
}

function initSelectAttributes(attribute){
    var result, id, deleteButtonId;
    result = scanFreeUsedSelectAttributes(attribute);
    if (result.free.length > 0) {
        $.each(result.free, function(index, value) { 
            $('#attr_' + value).parent().hide();
            $('#' + attribute + '-add-btn-' + value).hide();
        });
    }
    if (result.used.length == 0) {
        id = result.free.shift();
        $('#attr_' + id).parent().show();
        $('#attr_' + id).bind('change', {attribute: attribute}, changeSelectAttributesCallback);
        deleteButtonId = id;
    } else {
        $.each(result.used, function(index, value) {
            $('#attr_' + value).parent().show();
            $('#' + attribute + '-add-btn-' + value).hide();
        });
        deleteButtonId = result.used.shift();
        if (result.free.length > 0) {
            id = result.used.length > 0 ? result.used.pop() : deleteButtonId;
            $('#' + attribute + '-add-btn-' + id).show();
        }
    }
    $('#' + attribute + '-delete-btn-' + deleteButtonId).hide();
}

function changeSelectAttributesCallback(event) {
	if ($(event.target).val() != '') {
		result = scanFreeUsedSelectAttributes(event.data.attribute);
		if (result.used.length != 0) {
			if (result.free.length > 0) $('#' + event.data.attribute + '-add-btn-' + result.used.pop()).fadeIn();
		}
		$(event.target).unbind('change', changeSelectAttributesCallback);
	}
}

function scanFreeUsedSelectAttributes(attribute) {
	var from = 0, to = 0, id, free = [], used = [];
	switch (attribute) {
		case "mood":
			from = 11;
			to = 18;
			break;
		case "genre":
			from = 64;
			to = 65;
			break;
		case "music_for":
			from = 67;
			to = 71;
			break;
		case "cd_category":
			from = 72;
			to = 74;
			break;
	}
	for (id = from; id <= to; id++) {
		if ($('#attr_' + id).val() == '') free.push(id);
		else used.push(id);
	}
	return {free: free, used: used};
}

function copyAttributes(type,group_id,sendAll) {
	var container = $('#attribute_group_box_' + group_id);
    switch (type) {
        case 'radiobox':
            var element = container.find('input[type=radio]:checked');
            if (element.length) {
                attributes[group_id]['values'] = element.val();
            } else {
                attributes[group_id]['values'] = null;
            }
        break;
        case 'checkbox':
            var elements = container.find('input[type=checkbox]:checked');
            if (elements.length) {
                attributes[group_id]['values'] = new Array();
                for (var i = 0; i < elements.length; i++) {
                    attributes[group_id]['values'][i] = $(elements[i]).val();
                }
            } else {
                attributes[group_id]['values'] = null;
            }
        break;
        case 'select':
            var elements = container.find('select');
            if (elements.length) {
                for (var i = 0; i < elements.length; i++) {
                    var id = $(elements[i]).attr('id').substring(5);
                    var selected = $(elements[i]).find('option:selected').val();
                    if ( selected ) {
                        var str = id+'_';
                        attributes[group_id]['values'][id] = selected.replace(str,'');
                    } else {
                        attributes[group_id]['values'][id] = null;
                    }
                }
            } else {
                attributes[group_id]['values'] = new Array();
            }
        break;
    }
    if (!sendAll) {
        $.post(
            '/batch/ajaxSaveAttributes/',
            {'attributes':attributes},
            function(data){}
        );
    }
    
}

function pasteAttributes(type,group_id) {
    var container = $('#attribute_group_box_' + group_id);
    switch (type) {
        case 'radiobox':
            var elements = container.find('input[type=radio]');
            elements.each(function(){
                if ( $(this).val() == attributes[group_id]['values'] ) {
                    $(this).attr('checked', true);
                } else {
                    $(this).attr('checked', false);
                }
            });
        break;
        case 'checkbox':
            var elements = container.find('input[type=checkbox]');
            elements.each(function(){
                if ( jQuery.inArray($(this).val(),attributes[group_id]['values']) != -1 ) {
                    $(this).attr('checked', true);
                } else {
                    $(this).attr('checked', false);
                }
            });
        break;
        case 'select':
            for ( var key in attributes[group_id]['values']) {
                if ( attributes[group_id]['values'][key] != 'null' && key ) {
                    container.find('select option[value="'+key+'_'+attributes[group_id]['values'][key]+'"]').attr('selected',true);
                    
                }
            };
            initSelectAttributes(attributes[group_id]['title']);
        break;
    }
}

function copyAllAttributes() {
    for (var j in attributes) {
        if (attributes.hasOwnProperty(j)) {
            copyAttributes(attributes[j]['type'],j,true);
        }
    }
    $.post(
        '/batch/ajaxSaveAttributes/',
        {'attributes':attributes},
        function(data){}
    );
}

function pasteAllAttributes() {
    for (var j in attributes) {
        if (attributes.hasOwnProperty(j)) {
            pasteAttributes(attributes[j]['type'],j);
        }
    }
}
