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

function wOpenURL(url){
  if(location.pathname.indexOf('/weblication/grid5/') != 0){
    top.location.href = url;
  }
}

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

function wOpenPopupURL(url, width, height, name){

  var name = name || '';
  
  if(width == '' || width == ' ' || typeof(width) == 'undefined'){
    width = 786;
  }
  if(height == '' || height == ' ' || typeof(height) == 'undefined'){
    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);
  alert(name);
  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('|', '@');
}

////////////////////////////////////////////////////////////////
//
// @method void wEmbedNavpoint(id, url, mode)
//
// @desc Öffnet einen eingebetteten Navigationspunkt
//
// @return void
//
////////////////////////////////////////////////////////////////

function wEmbedNavpoint(id, url, mode){

  if(typeof wEditor == 'object'){
    return false;
  }

  if(jQuery('#navpoint_' + id).data('hasLoaded') == '1'){             
    jQuery('#navEmbed_' + id).show();
  }
  else{
    if(mode == 'embed'){
      url = url.indexOf('?') == -1 ? url + '?viewmode=embed' : url + '&viewmode=embed';
      url = url.replace('[URL]', location.pathname + location.search);
      jQuery.ajax({
        type: "GET",
        url: url,
        success: function(result){
        
          result = result.replace(/\n/g, '_wNL-').replace(/\s+id="[^"]+"/gim, '').replace(/_wNL-/g, "\n");
  
          jQuery('#navpoint_' + id).data('hasLoaded', '1');                  
          jQuery('#navEmbed_' + id).html(result);
          
          var navpointLeft = jQuery('#navpoint_' + id).offset().left;
          
          jQuery('#navEmbed_' + id).show();
          
          var layerLeft = jQuery('#navEmbed_' + id).offset().left;
          
          var blockMainRight = jQuery('#blockMain').offset().left + jQuery('#blockMain').width();        
          
          if(layerLeft < navpointLeft){
            jQuery('#navEmbed_' + id).css('left', String(navpointLeft - layerLeft - 6) + 'px');
          }
          
          var layerRight = jQuery('#navEmbed_' + id).offset().left + jQuery('#navEmbed_' + id).width();
                       
          if(layerRight > blockMainRight){
            jQuery('#navEmbed_' + id).css('left', String(parseInt(jQuery('#navEmbed_' + id).css('left')) - (layerRight - blockMainRight)) + 'px');
          }
          
          jQuery('#navpoint_' + id).mouseout(function(){
            jQuery('#navEmbed_' + id).hide();
          });
          
          jQuery('#navEmbed_' + id).mouseover(function(){
            jQuery('#navEmbed_' + id).show();
          });
          
          jQuery('#navEmbed_' + id).mouseout(function(){
            jQuery('#navEmbed_' + id).hide();
          });          
        }
      });
    }
    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);
      jQuery('#navpoint_' + id).data('hasLoaded', '1');                  
      
      var iframeEmbed    = document.createElement('iframe');

      iframeEmbed.id        = '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 = jQuery('#navpoint_' + id).offset().left;
      
      jQuery('#navEmbed_' + id).show();
      
      var layerLeft = jQuery('#navEmbed_' + id).offset().left;
      
      var blockMainRight = jQuery('#blockMain').offset().left + jQuery('#blockMain').width();        
      
      if(layerLeft < navpointLeft){
        jQuery('#navEmbed_' + id).css('left', String(navpointLeft - layerLeft - 6) + 'px');
      }
      
      var layerRight = jQuery('#navEmbed_' + id).offset().left + jQuery('#navEmbed_' + id).width();
                   
      if(layerRight > blockMainRight){
        jQuery('#navEmbed_' + id).css('left', String(parseInt(jQuery('#navEmbed_' + id).css('left')) - (layerRight - blockMainRight)) + 'px');
      }
      
      jQuery('#navpoint_' + id).mouseout(function(){
        jQuery('#navEmbed_' + id).hide();
      });
      
      jQuery('#navEmbed_' + id).mouseover(function(){
        jQuery('#navEmbed_' + id).show();
      });
      
      jQuery('#navEmbed_' + id).mouseout(function(){
        jQuery('#navEmbed_' + id).hide();
      });  
      
      //jQuery('.blockContentEmbed').attr('id', 'blockContent');  
      //jQuery('.blockContentEmbedInner').attr('id', 'blockContentInner');        
    }  
  }
}

////////////////////////////////////////////////////////////////
//
// @method void wShowLayerBookmarklet()
//
// @desc Schlägt vor, diese Webseite als App abzulegen
//
// @return void
//
////////////////////////////////////////////////////////////////

function wShowLayerBookmarklet(){

  if(/iPhone|iPod/.test(window.navigator.userAgent)){
    if(window.localStorage){             
      if(typeof(window.localStorage['numberBookmarketShown']) == 'undefined' || Number(window.localStorage['numberBookmarketShown']) < 2){
        window.localStorage['numberBookmarketShown'] = String(Number(window.localStorage['numberBookmarketShown'] || 0) + 1);
        var bookmarkletInfo = document.createElement('div');   
        
        bookmarkletInfo.id             = 'wBookmarkletInfo';
        bookmarkletInfo.style.width    = '100%';
        bookmarkletInfo.style.position = 'absolute';
        bookmarkletInfo.style.bottom   = '0';                
        
        var bookmarkletInfoInner = document.createElement('div');
        bookmarkletInfoInner.style.color      = '#ffffff';
        bookmarkletInfoInner.style.border     = 'solid 4px #ffffff';                                                                       
        bookmarkletInfoInner.style.margin     = '20px';
        bookmarkletInfoInner.style.padding    = '8px';
        bookmarkletInfoInner.style.overflow   = 'hidden';
        bookmarkletInfoInner.style.position   = 'relative';                
        bookmarkletInfoInner.style.background = '#cddcf3 -webkit-gradient(linear, left top, left bottom, from(#B5C9D9), to(#6886B0)) no-repeat bottom';                  
        bookmarkletInfoInner.style.WebkitBorderRadius = '8px';
        bookmarkletInfoInner.style.WebkitBoxShadow    = '0 4px 6px #a0a0a0';   
        
        bookmarkletInfo.appendChild(bookmarkletInfoInner);
        
        var bookmarkletInfoIcon = document.createElement('img');
        bookmarkletInfoIcon.style.margin = '8px';
        bookmarkletInfoIcon.style.position = 'absolute';                               
        
        var linkTags = document.getElementsByTagName('link');
        for(var i = 0; i != linkTags.length; i++){
          if(linkTags[i].getAttribute('rel') == 'apple-touch-icon'){
            bookmarkletInfoIcon.src = linkTags[i].getAttribute('href');
          }
        }
        
        bookmarkletInfoInner.appendChild(bookmarkletInfoIcon);
        
        var bookmarkletInfoCloser = document.createElement('img');
        bookmarkletInfoCloser.src = '/weblication/grid5/gui/images/style/bookmarklet_close.png';
        bookmarkletInfoCloser.style.margin = '-4px';
        bookmarkletInfoCloser.style.padding = '2px';
        bookmarkletInfoCloser.style.background = '#ffffff';
        bookmarkletInfoCloser.style.border = 'solid 1px #c0c0c0';
        bookmarkletInfoCloser.style.float  = 'right';
        
        bookmarkletInfoCloser.onclick = function(){document.getElementById('wBookmarkletInfo').parentNode.removeChild(document.getElementById('wBookmarkletInfo'));window.localStorage['numberBookmarketShown'] = '99'};                            
        bookmarkletInfoInner.appendChild(bookmarkletInfoCloser);                
        
        var bookmarkletInfoText = document.createElement('div');
        bookmarkletInfoText.style.margin = '8px 8px 8px 100px';
        bookmarkletInfoText.style.position  = 'left';
        bookmarkletInfoText.style.backgroundColor  = 'none';  
        bookmarkletInfoText.innerHTML    = 'Klicken Sie unten auf das "+" Zeichen und dann auf "Zum Home-Bildschirm hinzufügen", um diese Seiten als App abzulegen.';   
        
        bookmarkletInfoInner.appendChild(bookmarkletInfoText); 
        
        var bookmarkletArrow = document.createElement('div');
        bookmarkletArrow.style.height             = '23px';
        bookmarkletArrow.style.width              = '100%';
        bookmarkletArrow.style.marginTop          = '-23px';
        bookmarkletArrow.style.position           = 'absolute';                         
        bookmarkletArrow.style.zIndex             = '10';        
        bookmarkletArrow.style.backgroundRepeat   = 'no-repeat';
        bookmarkletArrow.style.backgroundPosition = 'center';        
        bookmarkletArrow.style.backgroundImage    = 'url(/weblication/grid5/gui/images/style/arrow_bookmarklet.png)'; 
        
        bookmarkletInfo.appendChild(bookmarkletArrow);                                                               
        
        document.body.appendChild(bookmarkletInfo);
      }
      else{
      }  
    }
  }
}

////////////////////////////////////////////////////////////////
//
// Initialisieren der Seite
//
////////////////////////////////////////////////////////////////

jQuery(document).ready(function(){
  if(typeof wInitBrowseEdit == 'function'){
    wInitBrowseEdit();
  }

  // Sortieren der Listen
  //jQuery('.listDefault').reorder('.last');
  
  // Hover Basket
  jQuery('#basket').hover(function(){
    jQuery(this).addClass('hover');
  },function(){
    jQuery(this).removeClass('hover');  
  });
  // Weiterleitung auf Warenkorb
  jQuery('#basket').click(function(){
    location.href = '/aurix/shop/warenkorb.php';
  });
  
  // Select-Box Filter in Listen
  jQuery('.selectProdukt').change(function(){
    var cat = jQuery('#selectCategoryProdukt').val();
    if(jQuery('#selectSortProdukt').length > 0) {
      var orderBy = jQuery('#selectSortProdukt').val();
    } else {
      var orderBy = '';
    }
    if(jQuery('#selectEntriesProdukt').length > 0) {
      var entriesPage = jQuery('#selectEntriesProdukt').val();
    } else {
      var entriesPage = '';
    }
    location.href = window.location.pathname+'?orderBy='+orderBy+'&entriesPage='+entriesPage;
  });

  // Warenkorb
  jQuery('.basketAmount').focus(function(){
    jQuery(this).select();
  });
  jQuery('.basketAmount').keyup(function(){
  	var name 		= jQuery(this).attr('name');
    var amount 	= jQuery(this).val();
    var path 		= jQuery('input[name = "'+name+'_path"]').val();
    addURLToBasket(path, amount);
    
    setBasketPrices();
  });
  
  //Versandart ändern
  jQuery('select[name="versandart"]').change(function(){
  	setOrderPrices();
  });
  jQuery('.basketAmount').keyup(function(){
  	var name 		= jQuery(this).attr('name');
    var amount 	= jQuery(this).val();
    var path 		= jQuery('input[name = "'+name+'_path"]').val();
    addURLToBasket(path, amount);
    
    setBasketPrices();
  });
  
  //Produkt entfernen
  jQuery('.delete a').click(function(e){
  	e.preventDefault();
  	var name 		= jQuery(this).attr('id');
    var path 		= jQuery('input[name = "'+name+'path"]').val();
    removeURLFromBasket(path);
    jQuery('#'+name+'tr').remove();
  	return;
  });

  //Abweichende Lieferadresse einblenden
  jQuery('select[name="lieferadresse"]').change(function(){
    if(jQuery(this).val() == "abweichend"){
      jQuery('#lieferadresseContainer').show();
    } else {
      jQuery('#lieferadresseContainer').hide();
    }
  });
  
  //Weitere Zahlungseingaben einblenden
  jQuery('select[name="zahlungsart"]').change(function(){
    if(jQuery(this).val() == "Bankeinzug"){
      jQuery('#bankeinzugContainer').show();
    } else {
      jQuery('#bankeinzugContainer').hide();
    }
  });
  
  // Warenkorb initialisieren
  setMetaBasketCounter();
});


var shopId = 'shop';

function correctPrice(s) {
	if(s != null) {
		return s.replace(/,/, ".");
	}
	return "";
}

function formatPrice(zahl) {
  wert = parseInt(zahl * 100);
  wert = wert / 100;
  wert = wert.toFixed(2);
  wert = wert.replace(/\./,",");
  while(wert.match(/^(\d+)(\d{3}\b)/)) {
      wert = wert.replace(/^(\d+)(\d{3}\b)/, RegExp.$1 + '.' + RegExp.$2);
  }
  return wert;
}

function setBasketPrices() {
  var products = jQuery('input[name = "formProducts"]').val();
	if(products > 0) {
		var priceSum = 0;
  	for(i=0; i<products; i++) {
  		var amount 	= jQuery('input[name = "prod_'+i+'"]').val() * 1;
	    var price 	= correctPrice(jQuery('input[name = "prod_'+i+'_price"]').val()) * 1;
	    var path 		= jQuery('input[name = "prod_'+i+'_path"]').val();
	    var pricePr = formatPrice(amount * price);
	    jQuery('#prod_'+i+'_sum').html(pricePr);
	    priceSum 	 += (amount * price);
  	}
  	jQuery('#basketPrice').html(formatPrice(priceSum));
  	
  	//Gesamtsumme berechnen
  	setOrderPrices();
	}
}

function setOrderPrices() {
	var deliveryFree 	= correctPrice(jQuery('input[name = "versandkostenFrei"]').val());
	var basketPrice 	= correctPrice(jQuery('#basketPrice').html());
	var deliveryCosts = '0.00';
	var orderPrice 		= '0.00';
	
	//Aktuelle Versandart teilen
	var val 	= jQuery('select[name="versandart"]').val();
	var vals 	= val.split('|');
	var type 	= vals[0];
	var price = vals[1];

	//Prüfen
  if(basketPrice < deliveryFree){
    orderPrice = (basketPrice * 1) + (price * 1);
    deliveryCosts = price;
  } else {
    orderPrice = basketPrice;
  }
	//alert(deliveryFree+"\n"+basketPrice+"\n"+price+"\n"+type+"\n"+orderPrice+"\n"+deliveryCosts);
	jQuery('#versandkostenart').html(type);
	jQuery('#deliveryCosts').html(formatPrice(deliveryCosts));
	jQuery('input[name = "versandkosten"]').attr('value', deliveryCosts);
	jQuery('#orderPrice').html(formatPrice(orderPrice));
}

function addURLToBasket(url, amount, type) {

  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 {
        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'){
    jQuery.fancybox(
		'<h2>Artikel dem Warenkorb hinzugefügt!</h2><div><div class="basketButtonBack"><a href="#" onclick="jQuery.fancybox.close();" title="weiter shoppen">weiter shoppen</a></div><div class="basketButton"><a href="#" onclick="location.href = \'/aurix/shop/warenkorb.php\'" title="zum Warenkorb">zum Warenkorb</a></div><div class="clearBoth">&#160;</div></div>',
		{
      '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('#actBasketAmount').text(basketNumbers);
  
  // Preis
  var urlsBasket = getUrlsBasket();
  var parameter = 'action=getPriceBasket&basketContent='+urlsBasket;
  jQuery.ajax({
    url: "/wLayout/wGlobal/scripts/php/items/ajax.shop.wItem.php",
    data: parameter,
    success: function(result){
      jQuery("#actBasketPrice").html(result);
    }
  });
}

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

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 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 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];
}
