var pageloadComplete=false;
var searchFieldCleaned=false;
var popUpWindow;
var popUpWindow360;
var popUpWindowVideo;
var configFinishedFlag=false;

function popUpContent(contentId){
  popUpWindow=window.open(shopPath +'popup_content.php?coID=' + contentId, 'popup', 'scrollbars=yes, resizable=yes, toolbar=0, width=600, height=600');
  popUpWindow.focus();
}

function show_360(path){
  popUpWindow360=window.open(shopPath +'viewer360.php?path=' + path, 'popup', 'scrollbars=no, resizable=no, toolbar=0, width=600, height=600');
  popUpWindow360.focus();
}

function show_video(model){
  popUpWindowVideo=window.open(shopPath +'viewerVideo.php?model=' + model, 'popup', 'scrollbars=no, resizable=no, toolbar=0, width=600, height=400');
  popUpWindowVideo.focus();
}

function cleanSearchField(callObj){
  if(!searchFieldCleaned){
    callObj.value='';
    searchFieldCleaned=true;
  }
}

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;
}
function popupWindow(url) {
  window.open(url,'popupWindow','scrollbars=yes,resizable=yes,toolbar=0,width=630,height=630,screenX=50,screenY=50,top=50,left=50')
} 

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();
  }
}
//img enlarge functions

function imgL(event, callObj, src){
  var callObj=$(callObj.id);
  var event=new Event(event);
	var container=$('imagePreview');
  
  var x_pos=callObj.getLeft()-258;
  var y_pos=callObj.getTop()-258;
	
  container.style.top=y_pos + "px";
  container.style.left=x_pos + "px";
  container.style.display="block";
  
  imgPath=shopPath+"images/products/m/" + src;
  
  container.innerHTML='<img src="' + imgPath + '" />';
}
function imgLClose(callObj){
  var container=$('imagePreview');
  container.style.display="none";
}

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

//mootools
window.addEvent('domready', function() {
  //image gallery
  imageGalleryAsssign();
  //headInfo Text
  var headInfos=$$('#headInfos a');
  headInfos.each(function(obj) {
    obj.addEvent('mouseenter', function(e){
      //stop the click event
      //e=new Event(e).stop();
      var infoObj=$(obj.id+"_text");
      if(infoObj) infoObj.setStyle('display', 'block');
    });
    obj.addEvent('mouseleave', function(e){
      //stop the click event
      e=new Event(e).stop();
      var infoObj=$(obj.id+"_text");
      if(infoObj) infoObj.setStyle('display', 'none');
    });
    //click
    obj.addEvent('click', function(e){
      //stop the click event
      e=new Event(e).stop();
    });
  });
  // specImage
  var specLinks=$$('.specLink');
  specLinks.each(function(obj) {
    //click
    obj.addEvent('click', function(e){
      //stop the click event
      e=new Event(e).stop();
      spLoadImage(obj.href);
    });  
  });
});

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

function imageGalleryAsssign(){
  //thumbs
  var thumbs=$$('.imageThumb a');
  thumbs.each(function(obj) {
    //click
    obj.addEvent('click', function(e){
      //stop the click event
      e=new Event(e).stop();
      //replace target href
      var xxl_href=obj.href.replace('/products/m/', '/products/l/');
      var dropTarget=$('imageLarge');
      dropTarget.href=xxl_href;
      //replace target img
      dropTarget.setHTML('<img src="'+obj.href+'" alt="" />');
    });
  });
  //dropTarget
  var obj=$('imageLarge');
  if(obj){
    obj.addEvent('click', function(e){
      e=new Event(e).stop();
      //var xxl_href=obj.href.replace('/products/m/', '/products/l/');
      varPathParts=obj.href.split('/');
      var imgToLoad=varPathParts[varPathParts.length-1];
      //popUpMagViewer(imgToLoad);
      imageViewerLoad(imgToLoad);
    });
  }
}

function imageViewerLoad(imgToLoad){
  //hide selects ie 6 problems
  var imageViewerHides=$$('select');
  imageViewerHides.each(function(obj) {
    obj.setStyles({visibility: 'hidden'});
  });
  var ivOverlay=new Element('div', {'id': 'ivOverlay'}).injectInside(document.body);
  var imageViewer=new Element('div', {'id': 'imageViewer'}).injectInside(document.body);
  var ivCenter=new Element('div', {'id': 'ivCenter'}).injectInside(imageViewer);
  var ivCenterBg=new Element('div', {'id': 'ivCenterBg'}).injectInside(ivCenter);
  var ivLoadTarget=new Element('div', {'id': 'ivLoadTarget'}).injectInside(ivCenter);
  var ivClose=new Element('div', {'id': 'ivClose'}).injectInside(ivCenter);
  ivClose.onclick=function(){ imageViewerClose(); };
  ivOverlay.setStyles({opacity: 0.8, display: 'block'});
  if(navigator.userAgent.indexOf('Firefox/2') < 0)  swfobject.embedSWF("magLoader.swf?imgToLoad="+imgToLoad, "ivLoadTarget", "600", "600", "8.0.0"); 
  ivLoadTarget.setStyles({backgroundImage: 'url(images/products/l/'+imgToLoad+')'});
	var topVal = window.getScrollTop() + (window.getHeight() / 15);
	imageViewer.setStyles({display: 'block',top: topVal});
  alphaBackgrounds();
}

function imageViewerClose(){
  $('imageViewer').remove();
  $('ivOverlay').remove();
  var imageViewerHides=$$('select');
  imageViewerHides.each(function(obj) {
    obj.setStyles({visibility: 'visible'});
  });
}

function popUpMagViewer(imgToLoad){
  newWin=void(window.open(shopPath +'popup_magviewer.php?imgToLoad=' + imgToLoad, 'popup', 'scrollbars=no, resizable=yes, toolbar=0, width=600, height=600'));
}

function createFlvPlayer(target_id, player_id, flv, image, width, height, autostart){
  var flashvars={
    file: flv, 
    image: image,
    autostart: autostart
  };
  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);
};

// auto suggest
window.addEvent('load', function() {
	var options_xml = {
		script: function (input) { return "ajax_autoSuggest.php?input="+input+"&testid="+document.getElementById('searchInput').value; },
		varname:"input"
	};
	var as_xml = new bsn.AutoSuggest('searchInput', options_xml);
});

function getNextConfigOption(configPath, callObj, pos, products_id){
  configFinishedFlag=false;
  $('btn_add_cart').style.display="none";
  $('btn_add_cart_trans').style.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;
  	new Ajax(url, {
  		method: 'get',
  		update: target,
  		onComplete: function() {
  			dummy.style.display="none";
  			target.style.display="block";
  		}
  	}).request();
  }
}

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.innerHTML='';
      tmpDummy.style.display="block";
    }
    else break;
  }
}

function configFinished(configPath, callObj, products_id){
  if(callObj.value>=0){  
    configPath=configPath+callObj.value;
  	var url=shopPath+"ajax_updateProductData.php?products_id="+products_id+"&configPath="+configPath;
  	new Ajax(url, {
  		method: 'get', 		
  		onComplete: function() {
  		  updateProductData(this.response.text, 'config');
  		}
  	}).request();
  }
  else{
    $('btn_add_cart').style.display="none";
    $('btn_add_cart_trans').style.display="inline";  
  }
}

function optionChanged(callObj, products_id){
  if(callObj.value>=0){  
  	var url=shopPath+"ajax_updateProductData.php?products_id="+products_id+"&options_values_id="+callObj.value;
  	new Ajax(url, {
  		method: 'get', 		
  		onComplete: function() {
  		  updateProductData(this.response.text, 'option');
  		}
  	}).request();
  }
}

function updateProductData(response, mode){
  if(mode=="config"){
    configFinishedFlag=true;
    $('btn_add_cart_trans').style.display="none";
    $('btn_add_cart').style.display="inline";  
  }
  var responseArray=response.split('###');
  if(responseArray.length > 0){  
    $('pShippingTime').innerHTML=responseArray[0];
    if(responseArray[1]) $('p_price').innerHTML=responseArray[1];
    if(responseArray[1]) $('pModelNr').innerHTML=responseArray[2];
  }
  /*
  if(responseArray.length==2){
    $('pShippingTime').innerHTML=responseArray[0];
    $('p_price').innerHTML=responseArray[1];
  }
  */
  if(responseArray.length >= 4){
    if(responseArray[3].length > 0){
      $('gallery_area').innerHTML=responseArray[3];
      imageGalleryAsssign();
    }
  }
  if(responseArray.length==5){
     $('bonus_points_needed').innerHTML=responseArray[4];    
  }
}



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