////////////////////////////////////////////////////////////////
//
// @method void wOpenURL(url)
//
// @desc Öffnet eine Seite
//
// @return void
//
////////////////////////////////////////////////////////////////

function wOpenURL(url){
  if(location.pathname.indexOf('/weblication/grid5/') != 0){
    if(url.match(/\.php$/) || url.match(/\/[^\.]+$/)){
      top.location.href = url;    
    }
    else{
      window.open(url);
    }
  }
}

////////////////////////////////////////////////////////////////
//
// @method void wOpenPopupURL(url, width, height)
//
// @desc Öffnet eine Seite in einem Popup
//
// @return void
//
////////////////////////////////////////////////////////////////

function wOpenPopupURL(url, width, height){

  var name = '';
  
  if(width == '' || width == ' '){
    width = 786;
  }
  if(height == '' || height == ' '){
    height = 677;
  }
  
  url = url.replace(/&amp;/g, '&');
  options = ',location=no, menubar=no,toolbar=no,resizable=no,scrollbars=no,status=no';
  width   = parseInt(width);
  height  = parseInt(height);

  var posLeft = (screen.width / 2)  - (width  / 2);
  var posTop  = (screen.height / 2) - (height / 2);
  window.open(url, name, 'top='+posTop+',left='+posLeft+',width='+width+',height='+height+',' + options);
}

////////////////////////////////////////////////////////////////
//
// @method void wSendMailNospam(data)
//
// @desc Öffnet eine E-Mail zum Versenden
//
// @return void
//
////////////////////////////////////////////////////////////////

function wSendMailNospam(data){
  location.href = 'mailto:' + data.replace('|', '@');
}

function wEmbedNavpoint(id, url, mode){

  if(typeof wEditor == 'object'){
    return false;
  }         
 
  if(mode == 'embed'){ 
    if($('#navpoint_' + id).data('hasLoaded') == '1'){             
      $('#navEmbed_' + id).show();                                    
    }
    else{        
      jQuery('#navpoint_' + id).mouseout(function(){
        $('#navEmbed_' + id).hide();
      });    
       
      url = url.indexOf('?') == -1 ? url + '?viewmode=embed' : url + '&viewmode=embed';
      url = url.replace('[URL]', location.pathname + location.search);
      $.ajax({
        type: "GET",
        url: url,
        success: function(result){
        
          result = result.replace(/\n/g, '_wNL-').replace(/\s+id="[^"]+"/gim, '').replace(/_wNL-/g, "\n");
  
          $('#navpoint_' + id).data('hasLoaded', '1');                  
          $('#navEmbed_' + id).html(result);
          
          var navpointLeft = $('#navpoint_' + id).offset().left;
          
          $('#navEmbed_' + id).show();
          
          var layerLeft = $('#navEmbed_' + id).offset().left;
          
          var blockMainRight = $('#blockMain').offset().left + $('#blockMain').width();        
          
          if(layerLeft < navpointLeft){
            $('#navEmbed_' + id).css('left', String(navpointLeft - layerLeft - 6) + 'px');
          }
          
          var layerRight = $('#navEmbed_' + id).offset().left + $('#navEmbed_' + id).width();
                       
          if(layerRight > blockMainRight){
            $('#navEmbed_' + id).css('marginLeft', String( - (layerRight - blockMainRight) - 22) + 'px');
          }          
          
          jQuery('#navEmbed_' + id).mouseover(function(){
            $('#navEmbed_' + id).show();
          });
          
          jQuery('#navEmbed_' + id).mouseout(function(){
            $('#navEmbed_' + id).hide();
          });          
        }
      });
    }  
  }
  else{ 
    if($('#navpoint_' + id).data('hasLoaded') == '1'){             
      $('#navEmbed_' + id).show();                                 
      try{$('#navEmbedIframe_' + id).height(frames['navEmbedIframe_' + id].$('#blockContent').height() + 50);}catch(e){}
      $('#navEmbed_' + id).height(frames['navEmbedIframe_' + id].$('#blockContent').height() + 60);            
    }
    else{                      
      url = url.indexOf('?') == -1 ? url + '?viewmode=blank&parentIframeId=navEmbedIframe_'+id : url + '&viewmode=blank&parentIframeId=navEmbedIframe_'+id;
      url = url.replace('[URL]', location.pathname + location.search);
      $('#navpoint_' + id).data('hasLoaded', '1');                  
      
      var iframeEmbed    = document.createElement('iframe');

      iframeEmbed.id        = 'navEmbedIframe_' + id;
      iframeEmbed.name      = 'navEmbedIframe_' + id;
      iframeEmbed.className = 'navLevel1Embed';
      iframeEmbed.frameBorder = '0';
      iframeEmbed.scrolling   = 'no';
      iframeEmbed.src       = url;
             
      var embedContainer = document.getElementById('navEmbed_' + id);                
      embedContainer.appendChild(iframeEmbed);
      
      var navpointLeft = $('#navpoint_' + id).offset().left;
      
      $('#navEmbed_' + id).show();
      
      var layerLeft = $('#navEmbed_' + id).offset().left;
      
      var blockMainRight = $('#blockMain').offset().left + $('#blockMain').width();        
                      
      if(layerLeft < navpointLeft){
        $('#navEmbed_' + id).css('left', String(navpointLeft - layerLeft - 6) + 'px');
      }
      
      var layerRight = $('#navEmbed_' + id).offset().left + $('#navEmbed_' + id).width();
                   
      if(layerRight > blockMainRight){
        //$('#navEmbed_' + id).css('left', String(parseInt($('#navEmbed_' + id).css('left')) - (layerRight - blockMainRight)) + 'px');
        $('#navEmbed_' + id).css('marginLeft', String( - (layerRight - blockMainRight) - 22) + 'px');
      }
      
      jQuery('#navpoint_' + id).mouseout(function(){
        $('#navEmbed_' + id).hide();
      });
      
      jQuery('#navEmbed_' + id).mouseover(function(){
        $('#navEmbed_' + id).show();
      });
      
      jQuery('#navEmbed_' + id).mouseout(function(){
        $('#navEmbed_' + id).hide();
      });        
    }       
  }  
} 


$(document).ready(function(){
  
   $('a[rel = "fancybox"]').fancybox({
     'titleShow': false
   });
  
  // Hover Basket
  $('#basket').hover(function(){
    $(this).addClass('hover');
  },function(){
    $(this).removeClass('hover');  
  });
  
  // Select-Box Filter in Listen
  $('.selectBuch').change(function(){
    var cat = $('#selectCategoryBuch').val();
    if($('#selectSortBuch').length > 0){
      var orderBy = $('#selectSortBuch').val();
    }
    else{
      var orderBy = '';
    }
    if($('#selectEntriesBuch').length > 0){
      var entriesPage = $('#selectEntriesBuch').val();
    }
    else{
      var entriesPage = '';
    }
    location.href = window.location.pathname+'?orderBy='+orderBy+'&entriesPage='+entriesPage;
  });
  
  // Select-Box Filter in Listen
  $('.selectBuchDetail').change(function(){
    var cat = gup('filterBuch');
    if($('#selectSortBuch').length > 0){
      var orderBy = $('#selectSortBuch').val();
    }
    else{
      var orderBy = '';
    }
    if($('#selectEntriesBuch').length > 0){
      var entriesPage = $('#selectEntriesBuch').val();
    }
    else{
      var entriesPage = '';
    }
    location.href = '/de-kaufmann/buecher/liste-detail.php?filterBuch='+cat+'&orderBy='+orderBy+'&entriesPage='+entriesPage;
    
  });

  // Weiterleitung auf Warenkorb
  $('#basket').click(function(){
    var projectPath = $(this).attr('rel');
    location.href = projectPath + '/shop/warenkorb.php';
  });
  
  // Warenkorb
  $('.wkAmount').focus(function(){
    $(this).select();
  });
  
  $('.wkAmount').focusout(function(){
    var amount = $(this).val();
    var path = $(this).attr('rel');
    addURLToBasket(path, amount);
  });
  
  $('.refreshBasket').click(function(){
    var amount = $(this).parent().children('input').val();
    var path = $(this).parent().children('input').attr('rel');
    if(!isNaN(parseFloat(amount)) && amount >= 0 && amount.substr(0,1) != '-'){
      addURLToBasket(path, amount);
      location.reload();
    }
    else{
      alert('Bitte positive Zahl eingeben.');
      location.reload();
    }
    
  });
  $('.refreshBasket').hover(function(){
    $(this).children('img').attr('src', '/wLayout-kaufmann/wGlobal/layout/images/refresh_a.gif');
  },
  function(){
    $(this).children('img').attr('src', '/wLayout-kaufmann/wGlobal/layout/images/refresh.gif');
  });
  
  $('input[name = "selectVersand"]').change(function(){
    var val = $(this).val();
    var arr = val.split('|');
    var type = arr[0];
    var price = arr[1];
    var parameter = 'action=setVersand&type='+type+'&price='+price;
    $.ajax({
      url: "/wLayout-kaufmann/wGlobal/scripts/php/ajax.php",
      data: parameter,
      success: function(result){
        location.reload();
      }
    });
  });
  
  $('input[name = "selectPayment"]').change(function(){
    var val = $(this).val();
    var parameter = 'action=setPayment&type='+val;
    $.ajax({
      url: "/wLayout-kaufmann/wGlobal/scripts/php/ajax.php",
      data: parameter,
      success: function(result){
        location.reload();
      }
    });
    
  });
  
  // Warenkorb Counter
  setMetaBasketCounter();

  $('#checkLiefer_1').click(function(){
    if(this.checked){
      $('#lieferadresseContainer').show();
    }
    else{
      $('#lieferadresseContainer').hide();
    }
  });
  
});


//var shopId = 'shop';

function getUrlsBasket(info, option){

  var urlStr = getCookie(shopId);

  var urls = urlStr.split('~___');
  
  var urlsChecked = new Array();

  for(var i = 0; i < urls.length; i++){
    if(urls[i] != ''){
      urlsChecked.push(urls[i].replace(/p\:/, ''));       
    }       
  }    
  return urlsChecked;  
}


function getNumberUrls(){

  var urlStr = getCookie(shopId);
  var urls = urlStr.split('~___');
  
  return urls.length - 1;    
}

function isURLInBasket(url){

  var urlStr = getCookie(shopId);
  var regExpStr;

  var urlReg = url.replace(/\//g, '\\/');
  
  var existsUrl = new RegExp(urlReg + "~_~");
  if(existsUrl.test(urlStr) == true){
    return true;
  }
  return false;
}  


function addURLToBasket(url, amount, type){

  document.cookie="testcookie";
  var cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false;
  
  if (!cookieEnabled) {
    $.fancybox(
  		'<h2>Keine Cookies erlaubt!</h2>Zur Benutzung des Online-Shops muss Ihr Browser Cookies akzeptieren. Bitte aktivieren Sie Cookies in Ihrem Browser.',
  		{
        'autoDimensions'	: false,
  			'width'         		: 350,
  			'height'        		: 'auto',
  			'scrolling'         : 'no'
  		});
  }

  var urlStr = getCookie(shopId);
  var regExpStr;
  
  var urlReg = url.replace(/\//g, '\\/').replace(/\(/g, '\\(/').replace(/\)/g, '\\)/');   
  
  var existsUrl = new RegExp(urlReg + "~_~");
  if(existsUrl.test(urlStr) == true){
    if(!isNaN(parseFloat(amount))){
      if(amount == 0){
        removeURLFromBasket(url);
      }
      else if(amount < 0){
      }
      else{
        var pattern = url + "~_~" + "[0-9]+" + "~___";
        var re = new RegExp(pattern);
        var urlNew = url + "~_~" + amount + "~___";
        urlStr = urlStr.replace(re, urlNew);
        setUrls(urlStr);
      }
    }
    else{
      alert('Bitte Zahl eingeben.');
    }
  }
  else{
    urlStr = urlStr + url + "~_~" + amount + "~___";
    setUrls(urlStr);
  }
  setMetaBasketCounter();
  
  if(type == 'fancy'){
    $.fancybox(
		'<h2>Artikel dem Warenkorb hinzugefügt!</h2><div class="basketButtonBack" style="float:left"><a href="#" onclick="$.fancybox.close();" title="weiter shoppen">weiter shoppen<span>&#160;</span></a></div><div class="basketButton" style="float:right"><a href="#" onclick="location.href = \''+projectPath+'/shop/warenkorb.php\'" title="zum Warenkorb">zum Warenkorb<span>&#160;</span></a></div></p>',
		{
      'autoDimensions'	: false,
			'width'         		: 350,
			'height'        		: 'auto',
			'scrolling'         : 'no'
		}
	);

  }
} 


function removeURLFromBasket(url){

  var urlStr = getCookie(shopId);
  var regExpStr;
  
  var urlReg = url.replace(/\//g, '\\/').replace(/\(/g, '\\(/').replace(/\)/g, '\\)/');    
  
  var existsUrl = new RegExp(urlReg + "~_~");
  
  if(existsUrl.test(urlStr) == true){
    var pattern = url + "~_~" + "[0-9]+" + "~___";
    var re = new RegExp(pattern);
    urlStr = urlStr.replace(re, "");
  }      

  setUrls(urlStr);
  setMetaBasketCounter();
}  


function setMetaBasketCounter(){
  // Artikel
  var basketNumbers = getNumberUrls();
  jQuery('#basketAmount').text(basketNumbers);
  
  // Preis
  var urlsBasket = getUrlsBasket();
  var parameter = 'action=getPriceBasket&basketContent='+urlsBasket;
  jQuery.ajax({
    url: "/wLayout-kaufmann/wGlobal/scripts/php/ajax.php",
    data: parameter,
    success: function(result){
      $("#basketPrice").html(result);
    }
  });
  /*    
  for(var i = 0; i < urlsBasket.length; i++){
    var dataEntry = urlsBasket[i].split("~_~");
    var url = dataEntry[0];
    var amount = dataEntry[1];
  }
  */
}

function clearBasket (){
  
  document.cookie = shopId + "=; path=/;";
}
  
function setUrls(urlStr){

  document.cookie = shopId + "=" + urlStr + "; path=/;";
}


function getCookie(name){

  var cookieStr = document.cookie;
  if(name && name != ''){        
    var nameReg = new RegExp(name + '=');
    
    cookiePos = cookieStr.search(nameReg);
    
    if(cookiePos != -1){
      cookieStr = cookieStr.substring(cookiePos);   
      cookieStr = cookieStr.replace(nameReg, '');
      cookieStr = cookieStr.replace(/;.*/, '');
    }
    else{
      cookieStr = "";
    }  
  }
  return cookieStr;
} 

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
