//  handle display of shadows on an art item
function adjustShadow() {
  jQuery('.artItem_bm,.artItem_bm img,.artItem_tm,.artItem_tm img,.artItemWrap_mm').each(
    function() {
      var mW = jQuery(this).parents('.artItemWrap').find('.artItemWrap_mm').find('.artItemFrame').find('img').width()+42+'px';
      jQuery(this).width(mW);
    }
  );
 jQuery('.artItemWrap_ml,.artItemWrap_ml img,.artItemWrap_mr,.artItemWrap_mr img').each(
    function() {
      var mH = jQuery(this).parents('.artItemWrap').find('.artItemWrap_mm').find('.artItemFrame').find('img').height()+40+'px';
      jQuery(this).height(mH);
    }
  );
  jQuery('.artItemWrap').each(
    function() {
      var wrapW = jQuery(this).find('.artItemWrap_mm').find('.artItemFrame').find('img').width()+42+6+13+'px';
      jQuery(this).width(wrapW);
      jQuery(this).find('.artItemWrap_t,.artItemWrap_b').width(wrapW);
    }
  );
  jQuery('.artItemWrap_t,.artItemWrap_ml,.artItemWrap_mr,.artItemWrap_b').show();
}

//  Equalize columns
//  TODO: keep them in sync during certain events
//  call this function in case that content is added programatically to a column
function equalizeCols() {
  jQuery('.subLeft,.subMiddle,.subRight').css('height','auto');
  var temp_highestCol = Math.max(jQuery('.subLeft').height(),jQuery('.subRight').height());
  highestCol = Math.max(temp_highestCol,jQuery('.subMiddle').height());
  jQuery('.subLeft,.subMiddle,.subRight').height(highestCol);
}

/*
 * search field 
 * set default value
 * */
function setSearchDefault(defVal) {
	var searchField = jQuery('input#searchTextInput');
	searchField.val(defVal);
	
	searchField.focus(function() {
		thisVal = searchField.val();
		if (thisVal == defVal) searchField.val('');
	});
	
	searchField.blur(function() {
		thisVal = searchField.val();
		if (thisVal == '') searchField.val(defVal);
	});
}

jQuery.noConflict();

jQuery(document).ready(function() {

  fontResizer("10px", "12px", "17px");
  
  //jQuery(document).pngFix(); 
  
  jQuery('#sizeTgl, #func').css('visibility','visible');

  function doNothing() {
    return false;
  }
  
  urlVars = getUrlVars();
  if(urlVars['print'] == 1) {
    jQuery("head link[href*=print.css]").removeAttr("media");
  }
  
  function getUrlVars() {
      var vars = [], hash;
      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
      for(var i = 0; i < hashes.length; i++)
      {
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
      }
      return vars;
  }
  
  function slideUpProg() {
    jQuery('.slideOut').slideUp();
  }
  function slideUpProgTimed() {
    slideOutTimeout = setTimeout(slideUpProg,500);
  }
  
  jQuery(".layerBodyContent").hide();
  
  jQuery(".layerBody a").click(function() {
    jQuery("#"+jQuery(this).attr('id')+"Content").addClass('slideOut').slideToggle().bind('mouseleave',slideUpProgTimed);
    return false;
  });
  
  //jQuery('body').bind('click',slideUpProg);
  
  //dropdown function
  //  hide all dropdowns
  jQuery('.DrpDwnCont').hide();
  
  //  open dropdown
  function tglDropDwnOn(e) {
      jQuery(this).next('.DrpDwnCont').slideDown('fast').css('z-index','99');
      jQuery(this).addClass('DrpDwnTglOpen');
      e.preventDefault;
  }
  //  close dropdown
  function tglDropDwnOff(e) {
      jQuery(this).next('.DrpDwnCont').slideUp('fast');
      jQuery(this).removeClass('DrpDwnTglOpen');
      e.preventDefault;
  }

  //  bind toggle functions
  jQuery('.DrpDwnTgl').each(
    function() {
      nextEl = jQuery(this).next();
      activeEl = jQuery(nextEl).find("a.active");
      if (activeEl.length) {
        jQuery(this).text(jQuery(activeEl).text());
      }
      jQuery(this).toggle(tglDropDwnOn,tglDropDwnOff);
    }
  );
  
  jQuery('body').bind('click',function(){
    jQuery('.DrpDwnTglOpen').click();
  });
  
  //  add an asterisk to forms with required fields inside the content
  /*
  jQuery('.contentElement form').each(
      function() {
        //@todo sollte serverseitig kommen, bitte um kurzes feedback was du brauchst
        reqText = '<span class="requiredFieldsMsg">* Pflichtfeld<\/span>';
        reqEl = jQuery(this).find('label.required');
        targetEL = jQuery(this).find('.element:last').prepend(reqText);
      }
  );
  */
  
  //  handle map and flags
  var hideMapLayerTimeout = '0';
  function hideMapLayer() {
    jQuery('.subRight').css('position','relative');
    jQuery('.subRight').css('overflow','visible');
    jQuery('#mapLayer').empty();
    jQuery('#mapLayer').hide();
    jQuery('#pointerArrow').hide();
  }
  function hideMapLayerTimed() {
    hideMapLayerTimeout = setTimeout(hideMapLayer,1500);
  }

  function showMapLayer() {
    clearTimeout(hideMapLayerTimeout);
    var flagCountry = jQuery(this).find('strong').text();
    //@todo mehrsprachigkeit?
    //alert('Sie interessieren sich für unsere Standorte in '+flagCountry+'?');
    
    var flagContent = jQuery(this).parents('li').find('div:first').html();
    
    jQuery('#mapLayer').empty();
    jQuery('#mapLayer').append('<div class="countryInfo vcard">'+flagContent+'</div>');
    
    var mapLayerX = parseInt(jQuery(this).parents('li').css('left'));
    var mapLayerY = parseInt(jQuery(this).parents('li').css('top'));
    var mapLayerH = jQuery('#mapLayer').height();
    
    var mapLayerCSS = {
        'left':mapLayerX+29+20+'px',
        'top':mapLayerY-(mapLayerH/2)+'px'
    }
    var pointerArrowCSS = {
        'left':mapLayerX+20+'px',
        'top':mapLayerY-4+'px'
    }
    
    jQuery('#mapLayer').css(mapLayerCSS).show();
    jQuery('#pointerArrow').css(pointerArrowCSS).show();
  }

  jQuery('.flag').each(
      function() {
        jQuery(this).mouseenter(
          showMapLayer
        );
        jQuery(this).mouseleave(
          hideMapLayerTimed
        );
      }
  );

  jQuery('#mapLayer').mouseenter(
    function() {
      clearTimeout(hideMapLayerTimeout);
    }
  );
  
  jQuery('#mapLayer').mouseleave(
  function() {
    hideMapLayer();
  }
  );
  
  
  //  handle tabbed boxes
  var theTab;
  var tabIndex;
  var tabBoxIndex;
  var tabBoxConIndex;
  var tabBoxToggleIndex;
  var tabShow;

  function toggleTabs() {
    if(jQuery(this).parents('.tab').hasClass('active')) {
      return false;
    }
    else {
      jQuery(this).parents('.tabs').find('.tab').toggleClass('active');
      tabShow = jQuery(this).attr('href').split('#')[1];
      jQuery(this).parents('.tabs').next('.tabBox').find('.tabBoxCon').hide();
      jQuery('.tabBoxCon#'+tabShow).show();
    }
    return false;
  }

  jQuery('.tabBox').each(
    function() {
      tabBoxIndex = jQuery(this).parents('body').find('.tabBox').index(this);
      var tabList = '<ul class="tabs" id="tabs'+tabBoxIndex+'"><\/ul>';
      
      jQuery(this).attr('id','tabBox'+tabBoxIndex).addClass('tabbed');

      jQuery(this).wrap('<div class="tabBoxHolder"></div>');
      
      jQuery(this).before(tabList);
        
      
      
      jQuery(this).find('.tabBoxCon').each(
        function() {
          tabBoxConIndex = jQuery(this).parent('.tabBox').find('.tabBoxCon').index(this);
          jQuery(this).attr('id','tabBoxCon'+tabBoxIndex+'_'+tabBoxConIndex);
        }
      );
      
      
      jQuery(this).find('.tabBoxCon').not('.tabBoxCon:first').hide();
      
      jQuery(this).find('h4').each(
        function(index) {
        jQuery(this).addClass('tabCon')
          tabBoxToggleIndex = jQuery(this).parents('.tabBox').find('h4').index(this);
        
          jQuery(this).find('a').attr('href','#tabBoxCon'+tabBoxIndex+'_'+tabBoxToggleIndex).attr('tabindex','0');
          jQuery(this).find('a').attr('href','#tabBoxCon'+tabBoxIndex+'_'+tabBoxToggleIndex).attr('tabindex','0');
          
          if(index == 0) {
            jQuery(this).wrap('<li class="tab active" id="tab'+tabBoxIndex+'_'+index+'"><\/li>');
          }
          else {
            jQuery(this).wrap('<li class="tab" id="tab'+tabBoxIndex+'_'+index+'"><\/li>');
          }
          
        }
      );
      
      jQuery(this).find('li').appendTo('#tabs'+tabBoxIndex);
      jQuery(this).parents('.tabBoxHolder').find('#tabs'+tabBoxIndex).find('a').bind('click',toggleTabs);
      jQuery(this).parents('.tabBoxHolder').find('#tabs'+tabBoxIndex).find('a').bind('focus',toggleTabs);
      
      //  equalize height of content boxes to avoid 'jumping' pages
      var highestCol = Math.max(jQuery('.tabBoxCon').height());
      jQuery('.tabBoxCon').height(highestCol);
    }
  );

  //  handle image animation on "Kunstforum" homepage
  var actImgMainStage = jQuery('#mainStageKF').find('#keyvisKF').find('img').attr('src');
  //alert('Das aktive Bild auf der Kunstforum-Bühne ist: '+aindexctImgMainStage+'!');

  //  fix display of the searchbox and last browsebox
  jQuery('.tx-indexedsearch-searchbox').appendTo('.tx-indexedsearch');
  jQuery('.tx-indexedsearch-browsebox:last').removeClass().addClass('tx-indexedsearch-browsebox-last');

  //  fix display of FCEs on the homepage
  jQuery('.contentBottomLeft .fceLinkContainer, .contentBottomRight .fceLinkContainer').find('li:last').addClass('last');

  jQuery('#jobApplicationNewFileUpload').click(function() {
    jQuery("#jobApplicationFileUploadEditPanel").remove();
    jQuery('#jobApplicationFileUploadPanel').show();
  });

  //  add a title to all Links without title using the linktext
  /*
  jQuery('a').each(
    function() {
      var linkTitle;
      
      var linkTitleTitle = jQuery(this).attr('title');
      var linkTitleText = jQuery(this).text();
      var linkTitleAlt = jQuery(this).find('img').attr('alt');
      var linkTitleInnerElem = jQuery(this).find('*:first').text();
      
      jQuery(this).append('<div style="position:absolute;z-index:5;pading:3px;border:1px solid #000;background:#CCC;">title:'+linkTitleTitle+' text: '+linkTitleText+' alt: '+linkTitleAlt+' inner text: '+linkTitleInnerElem+'</div>');
    }
  );
  */
  
  //  handle scrollable Boxes
  var scrollBoxHolder = '<div class="scrollBoxHolder"></div>';
  var leftScroller = '<a class="scroller leftScroller" title="Klicken Sie hier, um ein Bild nach links zu scrollen!"><span>&laquo;</span></a>';
  var rightScroller = '<a class="scroller rightScroller" title="Klicken Sie hier, um ein Bild nach rechts zu scrollen!"><span>&raquo;</span></a>';
  var scConInitCSS = {
    'left':'-96px'
  }

  
  function toggleFullsize() {
    largeImgActSrc = jQuery(this).find('a').attr('href');
    largeImgActAlt = jQuery(this).find('a img').attr('alt');
    largeImgActTitle = jQuery(this).find('a').attr('title');
    
    largeImgPrevSrc = jQuery(this).prev('.sObj').find('a').attr('href');
    largeImgPrevTitle = jQuery(this).prev('.sObj').find('a').attr('title');
    
    largeImgNextSrc = jQuery(this).next('.sObj').find('a').attr('href');
    largeImgNextTitle = jQuery(this).next('.sObj').find('a').attr('title');
    
    //jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink').attr('href',largeImgActSrc);
    jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink .artItem').attr('alt',largeImgActAlt);
    jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink .artItem').attr('src',largeImgActSrc);
    //jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink').attr('title',largeImgActTitle);
    
    //jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink').attr('href',largeImgNextSrc);
    //jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink').attr('href',largeImgNextTitle);
    
    jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink').bind(
    'click',function() {
          //alert(largeImgNextSrc);
          return false;
        }
     );
    
    adjustShadow();
    return false;
  }


      jQuery('.scrollBox').each(
        function(index) {
          jQuery(this).attr('id','scrollBox_'+index);
          jQuery(this).wrap(scrollBoxHolder);
          jQuery(this).addClass('scrollable');
          
          largeImgActSrc = jQuery(this).find('.scrollCon').find('.sObj:eQ(1) a').attr('href');
          largeImgActAlt = jQuery(this).find('.scrollCon').find('.sObj:eQ(1) a img').attr('alt');
          largeImgActTitle = jQuery(this).find('.scrollCon').find('.sObj:eQ(1) a').attr('title');
          
          //jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink').attr('href',largeImgActSrc);
          jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink .artItem').attr('alt',largeImgActAlt);
          jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink .artItem').attr('src',largeImgActSrc);
          //jQuery(this).parents('.scrollBoxHolder').next('.imgNav').next('.artItemWrap').find('.artItemFrame .artItemLink').attr('title',largeImgActTitle);
          
          adjustShadow();
        }
      );


      jQuery('.scrollCon').each(
        function() {
          var sObjCnt = jQuery(this).find('.sObj').size();
          
          jQuery(this).parents('.scrollBoxHolder').next('.imgNav').find('.absNum').text(sObjCnt);
          
          jQuery(this).css('width',sObjCnt*96+'px');
          
          jQuery(this).find('.sObj').each(
            function(index) {
              jQuery(this).css('left',(index*96)+'px');
              jQuery(this).attr('id','sObj_'+index);
              
              jQuery(this).bind('click',toggleFullsize);
              
              jQuery(this).click(
                function() {
                  jQuery(this).parents('.scrollBoxHolder').next('.imgNav').find('.actNum').text(index+1);
                }
              );
            }
          );
          jQuery(this).find('.sObj:last').css('left','-96px').insertBefore(jQuery(this).find('.sObj:first'));
        }
      );


      jQuery('.scrollBoxHolder').each(
        function() {
          jQuery(leftScroller).prependTo(this);
          jQuery(rightScroller).appendTo(this);
        
          jQuery(this).next('.imgNav').show();
          
           jQuery(this).next('.imgNav').find('.prev a').click(
            function() {
              jQuery(this).parents('.imgNav').prev('.scrollBoxHolder').find('a[class*="leftScroller"]').click();
              
              return false;
            }
          );
          jQuery(this).next('.imgNav').find('.next a').click(
            function() {
              jQuery(this).parents('.imgNav').prev('.scrollBoxHolder').find('a[class*="rightScroller"]').click();
              
              return false;
            }
          );

          jQuery(this).find('a[class*="leftScroller"]').click(
            function() {
              var parentCon = jQuery(this).next('.scrollBox.scrollable').find('.scrollCon');
              
              /**/
              parentCon.find('.sObj:last').insertBefore(parentCon.find('.sObj:first'));
              parentCon.animate(
                {
                  left:'+=96px'
                },function() {
                  //  if we need a callback
                  jQuery(this).css(scConInitCSS);
                  
                  jQuery(this).find('.sObj').each(
                        function(index) {
                          jQuery(this).css('left',(index*96)+'px');
                        }
                     );
                 }
              );
              /**/
              return false;
            }
          );


          jQuery(this).find('a[class*="rightScroller"]').click(
            function() {
              var parentCon = jQuery(this).prev('.scrollBox.scrollable').find('.scrollCon');

              /**/
              parentCon.find('.sObj:first').insertAfter(parentCon.find('.sObj:last'));
              parentCon.animate(
                {
                  left:'-=96px'
                },function() {
                  //  if we need a callback
                  jQuery(this).css(scConInitCSS);
                  
                 jQuery(this).find('.sObj').each(
                    function(index) {
                      jQuery(this).css('left',(index*96)+'px');
                    }
                 );
                  }
              );
              /**/
              return false;
            }
          );

        }
      );
      
      // fix issues with large font display
      if(jQuery('#sizeTglLarge').hasClass('on')) {
        jQuery('.contentBottom').addClass('enlarged');
      }
      else {
        jQuery('.contentBottom').removeClass('enlarged');
      }
      jQuery('.sizeTglLink').each(
          function() {
            jQuery(this).find('a').click(
                function() {
                  if(jQuery(this).attr('id') == 'sizeTglLarge') {
                    jQuery('.contentBottom').addClass('enlarged');
                  }
                  else {
                    jQuery('.contentBottom').removeClass('enlarged');
                  }
                }
              );
          }
        );
      
      
      //  Trigger equalizeCols when choosing font-size
      jQuery('#sizeTgl li a').bind('click',equalizeCols);
      
      //  Add a title to all box headlines eg in "Kunstforum"
      jQuery('.boxShadow').each(
          function() {
          var headline = jQuery(this).find('.boxHeadline');
          var headlineTitle = headline.text();
          headline.attr('title',headlineTitle);
          }
      );
      
      //  If the conditions for the application are not accepted, format the last paragraph
      /*
      jQuery('button#notAccepted').click(
        function(){
          jQuery('#jobApplicationContainer div.jobApplicationStep1 p:last').css('font-weight','bold');
        }
      );
      */
      
      
// external links: add target blank
// and if no title add stnd-title
      
      //find all ext-links exept the toplinks
      var extLinks = jQuery("a[href^='http://'], a[href^='https://'], a[href*=.pdf], a[href*=.doc], a[href*=.zip]]");
      //add target blank to all
      extLinks.not("a.topLink").attr('target', '_blank');
      
      //set title-tag if needed
      var stndTitleText = "Dieser Link öffnet sich in einem neuen Fenster";
      jQuery.each(extLinks, function(key, value) { 
          var thisTitleText = jQuery(this).attr('title');
          if (thisTitleText == "") {
              jQuery(this).attr('title', stndTitleText);
          }
      });
      
      
// backlinks for faq-pages
    var extLinks = jQuery("a.linkBack").click(function() {
        history.back();
        return false;
    });
        
// login unsubmit refresh topFrame
    jQuery('li#cwa form, li#doccheck form#form_doccheck').submit(function(){
        parent.headerFrame.waitForLogin();
    });
});

jQuery(window).load(function(){
  //  jQuery functions to initialize after the page has loaded.
  adjustShadow();
  equalizeCols();
  
  /*
   var srcVal = jQuery('input.searchText').val();
  jQuery('input#tx-indexedsearch-searchbox-sword').val(srcVal);
  */
});
