var pageloadComplete=false;
var configFinishedFlag=false;
var popUpWindow;

function fancyBoxIframeOpen(url){
  $.fancybox({ 
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
  	'width'         : 530,
  	'height'        : 400,
    'type'          : 'iframe',
  	'href'          : url
  });
}

function popUpContent(contentId){
  var url=shopPath +'popup_content.php?coID='+contentId;
  fancyBoxIframeOpen(url);
}

function moveInfo(event, info){
	var eventSrc=event.target || event.srcElement;
	//delete alt info in event trigger object (img)
	eventSrc.alt="";
  var event=new Event(event);
  var x_pos=event.page.x;
	var y_pos=event.page.y+8;
	var objBody=document.getElementsByTagName("body").item(0);
	if(!document.getElementById("infoElement")){
		objInfoElement=document.createElement("div");
		objInfoElement.setAttribute('id','infoElement');
		
		objInfoElementContent=document.createElement("div");
		objInfoElementContent.setAttribute('id','infoElementContent');
		objInfoElement.appendChild(objInfoElementContent);
		
		objInfoElementBottom=document.createElement("div");
		objInfoElementBottom.setAttribute('id','infoElementBottom');
		objInfoElement.appendChild(objInfoElementBottom);		
		
		objBody.appendChild(objInfoElement);
		objInfoElementContent.innerHTML=info;
		
	}
	else{
		objInfoElement=document.getElementById("infoElement");
	}
	if(objInfoElement){			
		objInfoElement.style.top=(y_pos)+"px";
		objInfoElement.style.left=(x_pos+4)+"px";
	}
}

function hideInfo(){
	var tmpObj=document.getElementById("infoElement");
	if(tmpObj){
		var objBody = document.getElementsByTagName("body").item(0);
		objBody.removeChild(tmpObj);
	}
}

// option recalc price functions
function toDecimalPlaces(x, n){	
	if (n < 1 || n > 14) return false;
	var e = Math.pow(10, n);
	var k = (Math.round(x * e) / e).toString();
	if (k.indexOf('.') == -1) k += '.';
	k += e.toString().substring(1);
	return k.substring(0, k.indexOf('.') + n+1);  	
}

function currencyToXTC(str){
	var decimal_point = ',';
	var decimal_places = 2;
	var thousands_point = '.';
	str = toDecimalPlaces(str,decimal_places);
	var predecimal_part = str.substring(0,str.length-decimal_places-1);
	var deicmal_part = str.substr(str.length-decimal_places,decimal_places);
	if(thousands_point != "" && predecimal_part.length > 3){
		var predecimal_temp = predecimal_part;
		var predecimal_part = "";
		for(j = 3; j < predecimal_temp.length ; j+=3){
		  var extrakt = predecimal_temp.slice(predecimal_temp.length - j, predecimal_temp.length - j + 3);
		  predecimal_part = thousands_point + extrakt +  predecimal_part + "";
		}
		var str_first = predecimal_temp.substr(0, (predecimal_temp.length % 3 == 0)?3:(predecimal_temp.length % 3));
		predecimal_part = str_first + predecimal_part;
	  }
	return predecimal_part + decimal_point + deicmal_part;  	
}

function currencyToJavaScript(str){	
	var decimal_places = 2;
	var thousands_point = '.';
	str = str.toString()
	var predecimal_part = str.substring(0,str.length-decimal_places-1);
	var deicmal_part = str.substr(str.length-decimal_places,decimal_places);
	if(thousands_point != "" && predecimal_part.length > 3)
		predecimal_part = predecimal_part.replace(eval('/\\'+thousands_point+'/g'),'');
	return Number(predecimal_part + '.' + deicmal_part);  	
}

// xtc functions from header.phpvar selected;
var submitter = null;

function submitFunction() {
    submitter = 1;
}
var popUpWindow;
function popupWindow(url) {
  popUpWindow=window.open(url,'popupWindow','scrollbars=yes,resizable=yes,toolbar=0,width=630,height=630,screenX=50,screenY=50,top=50,left=50')
  popUpWindow.focus();
} 

var selected="";
function selectRowEffect(object, buttonSelect) {
  if (!selected) selected=document.getElementById('defaultSelected');
  if (selected) selected.className='moduleRow';
  object.className='moduleRowSelected';
  selected=object;
  var radioArr=document.getElementsByName('payment');
  if(radioArr.length==0) var radioArr=document.getElementsByName('address');
  var cRadioSelect=radioArr[buttonSelect];
  cRadioSelect.checked=true;
}

function rowOverEffect(object) {
  if (object.className=='moduleRow') object.className='moduleRowOver';
}

function rowOutEffect(object) {
  if (object.className=='moduleRowOver') object.className='moduleRow';
}

function popupImageWindow(url) {
  window.open(url,'popupImageWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width=100,height=100,screenX=150,screenY=150,top=150,left=150')
}


// groupChange
function changeGroup(groupFormId){
  var groupForm=document.getElementById(groupFormId);
  if(groupForm){
    groupForm.submit();
  }
}

function updateShippingTime(callObj, products_id){
	var url=shopPath+"ajax_updateShippingTime.php?products_id="+products_id+"&options_values_id="+callObj.value;
  $("#pShippingTime").load(url);
}

function getNextConfigOption(configPath, callObj, pos, products_id){
  configFinishedFlag=false;
  $('#btn_add_cart').css({"display" : "none"});
  $('#btn_add_cart_trans').css({"display" : "inline"});
  clearConfigOptions(pos);
  var target=$('#config_option_'+pos);
  var dummy=$('#config_option_dummy_'+pos);
  if(callObj.value>=0){
    configPath=configPath+callObj.value+"-";
  	var url=shopPath+"ajax_getNextConfigOption.php?products_id="+products_id+"&configPath="+configPath;  	
    $.ajax({
      url: url,
      success: function(data) {
        dummy.css({"display" : "none"});
        target.css({"display" : "block"}).html(data);
      }
    });
  }
}

function clearConfigOptions(pos){
  for(var i=pos; i<=3; i++){
    var tmpTarget=$('#config_option_'+i);
    var tmpDummy=$('#config_option_dummy_'+i);
    if(tmpTarget && tmpDummy){
      tmpTarget.html("");
      tmpDummy.css({"display" : "block"});
    }
    else break;
  }
}

function configFinished(configPath, callObj, products_id){  
  if(callObj.value>=0){  
    configPath=configPath+callObj.value;
  	var url=shopPath+"ajax_updatePriceAndShippingTime.php?products_id="+products_id+"&configPath="+configPath;
    $.ajax({
      url: url,
      success: function(data) {
        updatePriceAndShipping(data);
      }
    });
  }
}

function updatePriceAndShipping(response){
  configFinishedFlag=true;
  $('#btn_add_cart_trans').css({"display" : "none"}); 
  $('#btn_add_cart').css({"display" : "inline"});
  var responseArray=response.split('###');
  if(responseArray.length > 0){  
    $('#pShippingTime').html(responseArray[0]);
    if(responseArray[1]) $('#p_price').html(responseArray[1]);
    if(responseArray[1]) $('pModelNr').html(responseArray[2]);
  }
  if(responseArray.length==2){
    $('#pShippingTime').html(responseArray[0]);
    $('#p_price').html(responseArray[1]);
  }
}

function checkConfigFinished(errorMessage){
  if(configFinishedFlag){
    return true;
  }
  else{
    alert(errorMessage);
    return false;
  }
}

//png stuff

function correctPNG() {
  var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, "");
  var doIt = rslt != null && Number(rslt[1]) <= 6;
  if(doIt){
    for (var i = 0; i < document.images.length; i++) {
      var img = document.images[i];
      var imgName = img.src.toUpperCase();
      if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
        var imgID = img.id ? "id='" + img.id + "' " : "";
        var imgClass = img.className ? "class='" + img.className + "' " : "";
        var imgTitle = img.title ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
        var imgStyle = "display:inline-block;" + img.style.cssText;
        if (img.align == "left") {
            imgStyle = "float:left;" + imgStyle;
        }
        if (img.align == "right") {
            imgStyle = "float:right;" + imgStyle;
        }
        if (img.parentElement.href) {
            imgStyle = "cursor:hand;" + imgStyle;
        }
        var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src='" + img.src + "', sizingMethod='crop');\">";
        img.outerHTML = strNewHTML;
        i = i - 1;
      }
    }
  }
}

function alphaBackgrounds() {
  var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, "");
  var doIt = rslt != null && Number(rslt[1]) <= 6;
  if(doIt){
    for (i = 0; i < document.all.length; i++) {
      var bg = document.all[i].currentStyle.backgroundImage;
      var el=document.all[i];
      if (doIt && bg) {
        if (bg.match(/\.png/i) != null && el.className != 'noFix') {
          var mypng = bg.substring(5, bg.length - 2);
          document.all[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + mypng + "', sizingMethod='scale')";
          document.all[i].style.background = "none";
        }
      }
    }
  }
}

if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent) {
  window.attachEvent("onload", alphaBackgrounds);
  window.attachEvent("onload", correctPNG);
}

//jquery 
$(window).load(function() {
  // specImage
  $(".specLink").fancybox({ 
		'transitionIn'	     : 'none',
		'transitionOut'      : 'none', 
    'titleShow'          : false,
  	'autoScale'          : false,
  	'hideOnContentClick' : true
  });
  // thumbs
  $(".imageThumb a").click(function(e){
    e.preventDefault();
    var xxl_href=$(this).attr("href").replace('/products/m/', '/products/l/');
    $('#imageLarge')
    .attr("href", xxl_href)
    .html('<img src="'+$(this).attr("href")+'" alt="" />');
  });
  // magViewer
  $('#imageLarge').click(function(e){
    e.preventDefault();
    var pathParts=$(this).attr("href").split('/');
    var imgToLoad=pathParts[pathParts.length-1];       
    if(DetectFlashVer(8, 0, 0)){
      //flash installed
      var viewerUrl="magLoader.swf?imgToLoad="+imgToLoad;
    	$.fancybox({
    		'transitionIn'	: 'none',
    		'transitionOut'	: 'none',
    		'padding'       : 0,
    		'href'          : viewerUrl,
    		'width'			    : 600,
    		'height'		    : 600,
    		'title'         : '',
    		'type'          : 'swf',
    		'autoScale'     : false
    	});
    }
    else{
      //no flash installed
      var viewerUrl=$(this).attr("href");
    	$.fancybox({
    		'transitionIn'	: 'none',
    		'transitionOut'	: 'none',
    		'href'          : viewerUrl,
    		'title'         : '',
    		'autoScale'     : false
    	});
    }
  });  
  // product listing image magnifier
  $(".pL_magnifier").hover(
    function(e){ 
      var imgSrc=shopPath+"images/products/m/"+$(this).attr("rel");
      var offsets=$(this).offset();
      var xPos=offsets.left-258+"px";  
      var yPos=offsets.top-258+"px";      
    	$('#imagePreview')
      .css({"top" : yPos, "left" : xPos, "display" : "block"})
      .html('<img src="'+imgSrc+'" alt="" />');
    }, 
    function(e){
      $('#imagePreview').css({"display" : "none"});
    }
  );
  // lightbox => fancybox 
  $('a[rel*=lightbox]').fancybox({
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
		'titleShow'	    : true,
		'titlePosition' : 'inside'
	});
  // productQuestion
  $("#productQuestion").click(function(e){
    e.preventDefault();
    var url="popup_content.php?coID=9998&products_id="+$(this).attr("rel");
    $.fancybox({
  		'transitionIn'	: 'none',
  		'transitionOut'	: 'none', 
  		'width'         : 530,
  		'height'        : 420,
      'type'          : 'iframe',
  		'href'          : url
  	});
  });
  // productBestprice
  $("#productBestprice, .bestprice").click(function(e){
    e.preventDefault();
    var url="popup_content.php?coID=9997&products_id="+$(this).attr("rel");
    $.fancybox({ 
  		'transitionIn'	: 'none',
  		'transitionOut'	: 'none', 
  		'width'         : 530,
  		'height'        : 350,
      'type'          : 'iframe',
  		'href'          : url
  	});
  });  
  // auto suggest
  var options_xml = {
		script: function (input) { return "ajax_autoSuggest.php?input="+input+"&testid="+document.getElementById('searchInput').value; },
		varname:"input",
  	timeout:3000,
  	maxresults:15,
  	delay:100,
  	cache:false
	};
	var as_xml = new bsn.AutoSuggest('searchInput', options_xml);         
});

function createFlvPlayer(target_id, player_id, flv, image, width, height){
  var flashvars={
    file: flv, 
    image: image
  };
  var params={
    allowfullscreen: 'true', 
    allowscriptaccess: 'always',
    wmode: 'transparent'
  };
  var attributes={
    id: player_id, 
    name: player_id
  };
  swfobject.embedSWF('player.swf', target_id, width, height, '9.0.124', false, flashvars, params, attributes);
};

function ivLoadImage(imageSrc){
  //just the image name is required
  var urlParts=imageSrc.split('/');
  var imageSrc=urlParts[urlParts.length-1];
  popupWindow(shopPath+'popupImage.php?image='+imageSrc);
}
function spLoadImage(imageSrc){
  //just the image name is required
  var urlParts=imageSrc.split('/');
  var imageSrc=urlParts[urlParts.length-1];
  popupWindow(shopPath+'popupSpecImage.php?image='+imageSrc);
}