/************************************************************************************************************
(C) www.dhtmlgoodies.com, March 2006

This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.

Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.

Version:
	1.0	Released	March. 3rd 2006

Thank you!

www.dhtmlgoodies.com
Alf Magne Kalleland

************************************************************************************************************/

function file_get_contents( url ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Legaev Andrey
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Mainly here for study purposes.
    // %        note 1: To avoid browser blocking issues's concider using jQuery's: $('#divId').load('http://url') instead.
    // *     example 1: file_get_contents('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'

    var req = null;
    try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
        try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
            try { req = new XMLHttpRequest(); } catch(e) {}
        }
    }
    if (req == null) throw new Error('XMLHttpRequest not supported');

    req.open("GET", url, false);
    req.send(null);

    return req.responseText;
}

var flyingSpeed = 15;
//var url_addProductToBasket = '/tinymce/js/addProduct.php';
//var url_removeProductFromBasket = '/tinymce/js/removeProduct.php';
var txt_totalPrice = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Product totaal: &euro; ';


var shopping_cart_div = false;
var flyingDiv = false;
var currentProductDiv = false;

var shopping_cart_x = false;
var shopping_cart_y = false;

var slide_xFactor = false;
var slide_yFactor = false;

var diffX = false;
var diffY = false;

var currentXPos = false;
var currentYPos = false;

var ajaxObjects = new Array();
var toonprijs = new Number();

function shoppingCart_getTopPos(inputObj)
{
  var returnValue = inputObj.offsetTop;
  while((inputObj = inputObj.offsetParent) != null){
  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
  }
  return returnValue;
}

function shoppingCart_getLeftPos(inputObj)
{
  var returnValue = inputObj.offsetLeft;
  while((inputObj = inputObj.offsetParent) != null){
  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
  }
  return returnValue;
}

function UpdatePriceonChange() {

var tempo = document.getElementById('product_id_0').value.split('_');
var postidtoAjax = tempo[0];

var str = '';
var elem = document.getElementById('formulier_0').elements;
for(var i = 0; i < elem.length; i++){
 j = elem[i].name.indexOf('opties');
 if (j >= 0) {
   k = elem[i].type.indexOf('radio');
   l = elem[i].type.indexOf('checkbox');
   m = elem[i].type.indexOf('text');


   if (k >= 0) {
      if(elem[i].checked){
        postidtoAjax += '_'+elem[i].value;
      }
    }
   else if (l >= 0) {
      if(elem[i].checked){
        postidtoAjax += '_'+elem[i].value;
      }
    }
   if (m >= 0) {
   }
   else  {
        postidtoAjax += '_'+elem[i].value;
   }
  }
}

document.getElementById('product_id_0').value = postidtoAjax;
}



// ####################################
// ########### addToBasket ############
// ####################################
function addToBasket(productId,nummer)
{

var str = '';
var formulier = 'formulier_'+nummer;
var elem = document.getElementById(formulier).elements;

	if(!shopping_cart_div)shopping_cart_div = document.getElementById('shopping_cart');
	if(!flyingDiv){
		flyingDiv = document.createElement('DIV');
		flyingDiv.style.position = 'absolute';
		document.body.appendChild(flyingDiv);
	}

	shopping_cart_x = shoppingCart_getLeftPos(shopping_cart_div);
	shopping_cart_y = shoppingCart_getTopPos(shopping_cart_div);

	currentProductDiv = document.getElementById('slidingProduct');

	currentXPos = shoppingCart_getLeftPos(currentProductDiv);
	currentYPos = shoppingCart_getTopPos(currentProductDiv);

	diffX = shopping_cart_x - currentXPos;
	diffY = shopping_cart_y - currentYPos;


	var shoppingContentCopy = currentProductDiv.cloneNode(true);
	shoppingContentCopy.id='';
	flyingDiv.innerHTML = '';
	flyingDiv.style.left = currentXPos + 'px';
	flyingDiv.style.top = currentYPos + 'px';
	flyingDiv.appendChild(shoppingContentCopy);
	flyingDiv.style.display='block';
	flyingDiv.style.width = currentProductDiv.offsetWidth + 'px';
	flyToBasket(productId, nummer);
}


function CurrencyFormatted(amount)
{
  var debug = 'amount: '+amount+'\n';
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += ',00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
debug += 's: ' + amount + '\n';
//alert(debug);
	return s;
}



function flyToBasket(productId, nummer)
{

	var maxDiff = Math.max(Math.abs(diffX),Math.abs(diffY));
	var moveX = (diffX / maxDiff) * flyingSpeed;;
	var moveY = (diffY / maxDiff) * flyingSpeed;

	currentXPos = currentXPos + moveX;
	currentYPos = currentYPos + moveY;

	flyingDiv.style.left = Math.round(currentXPos) + 'px';
	flyingDiv.style.top = Math.round(currentYPos) + 'px';


	if(moveX>0 && currentXPos > shopping_cart_x){
		flyingDiv.style.display='none';
	}
	if(moveX<0 && currentXPos < shopping_cart_x){
		flyingDiv.style.display='none';
	}

	if(flyingDiv.style.display=='block')setTimeout('flyToBasket("' + productId + '", "' + nummer + '")',10);;
}

function showAjaxBasketContent(ajaxIndex)
{
	// Getting a reference to the shopping cart items table
	var itemBox = document.getElementById('shopping_cart_items');

 	var productItems = ajaxObjects[ajaxIndex].response.split('|||');	// Breaking response from Ajax into tokens


//alert('in showAjaxBasketContent - productItems -> '+productItems[3]);



//alert('shopping_cart_items_product' + productItems[0]);
	if(document.getElementById('shopping_cart_items_product' + productItems[0])){	// A product with this id is allready in the basket - just add number items
        var row = document.getElementById('shopping_cart_items_product' + productItems[0]);
        for( var x = 0; x < row.childNodes.length; x++ ) {
          if( row.childNodes[x].id == 'winkelmandrow_aantal' ) {
            var aantal = row.childNodes[x];
            var huidigeaantal = Math.round(aantal.innerHTML*100)/100;
            var nieuwaantal = Math.round(productItems[1]*100)/100 + huidigeaantal;
            aantal.innerHTML = nieuwaantal;
          }
        }
	}else{	// Product isn't allready in the basket - add a new row
        var contentrow;
        contentrow = file_get_contents("/Templates/default/Modules/winkel/winkelmand_row.htm");
        contentrow = contentrow.replace(/{id}/g,productItems[0]);
        contentrow = contentrow.replace('{aantal}',productItems[1]);
        contentrow = contentrow.replace('{title}',productItems[2]);
        contentrow = contentrow.replace('{price}',productItems[3]);
//        contentrow = contentrow.replace('{price}',CurrencyFormatted(productItems[3]));
        var row = document.getElementById('shopping_cart_items');
        row.innerHTML += contentrow; // dit klopt denk ik niet.. appendchild gebruiken?
    }
	ajaxObjects[ajaxIndex] = false;
    	updateTotalPrice();
}

function updateTotalPrice()
{
  var debug = '\n';
var itemBox = document.getElementById('shopping_cart_items');
var newtotalprice = 0.00;
for( var x1 = 0; x1 < itemBox.childNodes.length; x1++ ) {
    if (itemBox.childNodes[x1].id){
    var productId = itemBox.childNodes[x1].id;
    var productRow = document.getElementById(productId);
    debug += 'productrows: ' + productRow.childNodes.length + '\n';
    for( var x = 0; x < productRow.childNodes.length; x++ ) {
    debug += 'id: ' + productRow.childNodes[x].id + '\n';
        if( productRow.childNodes[x].id == 'winkelmandrow_aantal' ) {
            var aantal = productRow.childNodes[x].innerHTML;
    debug += 'productrow aantal : ' + aantal+ '\n';
            var totalrowaantal = Math.round(aantal*100)/100;
    debug += 'productrow totalrowaantal : ' + totalrowaantal+ '\n';
        }
        if( productRow.childNodes[x].id == 'winkelmandrow_price' ) {
            var price = productRow.childNodes[x].innerHTML;
    debug += 'productrow price innerHTML : ' + price+ '\n';

            var price = price.replace(/&nbsp;€&nbsp;/g,'');
    debug += 'productrow price replace € : ' + price+ '\n';
//    if(price.length > 5){
//            var price = price.replace('.','');
    debug += 'productrow price replace . - ,: ' + price+ '\n';
//    }
//            var price = price.replace(',','.');
    debug += 'productrow price replace , - . : ' + price+ '\n';

            var totalrowprice = Math.round(price*100)/100;
    debug += 'productrow totalrowprice : ' + totalrowprice+ '\n';
        }
    }
    newtotalprice += totalrowaantal*totalrowprice;
    debug += 'productrow newtotalprice : ' + newtotalprice+ '\n';
    }
}
newtotalprice = Math.round(newtotalprice*100)/100;
debug += 'newtotalprice: ' + newtotalprice + '\n';
//newtotalprice = (newtotalprice/100);
//debug += 'newtotalprice: ' + newtotalprice + '\n';
//alert(debug);
//var displayprice = CurrencyFormatted(newtotalprice/100)
var displayprice = CurrencyFormatted(newtotalprice)
//var displayprice = displayprice.replace('.',',');
document.getElementById('shopping_cart_totalprice').innerHTML = displayprice;
}

function removeProductFromBasket(productId)
{
var ajaxIndex = ajaxObjects.length;
var productRow = document.getElementById('shopping_cart_items_product' + productId);

    for( var x = 0; x < productRow.childNodes.length; x++ ) {
        if( productRow.childNodes[x].id == 'winkelmandrow_aantal' ) {
            var aantal = productRow.childNodes[x].innerHTML;
            var totalprice = Math.round(aantal*100)/100;
            var totalPrice = totalprice - 1;
            productRow.childNodes[x].innerHTML = totalPrice;
            if ( totalPrice == '0' ) {
                var itemBox = document.getElementById('shopping_cart_items');
                itemBox.removeChild(productRow);
            }
        }
    }
    updateTotalPrice();
    ajaxRemoveProduct(productId);
}

function ajaxValidateRemovedProduct(ajaxIndex){
	if(ajaxObjects[ajaxIndex].response!='OK')alert('Error while removing product from the database');
}

function ajaxRemoveProduct(productId)
{
	var ajaxIndex = ajaxObjects.length;
	ajaxObjects[ajaxIndex] = new sack();
	ajaxObjects[ajaxIndex].requestFile = url_removeProductFromBasket;	// Saving product in this file
	ajaxObjects[ajaxIndex].setVar('productIdToRemove',productId);
	ajaxObjects[ajaxIndex].onCompletion = function(){ ajaxValidateRemovedProduct(ajaxIndex); };	// Specify function that will be executed after file has been found
	ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function
}

function ajaxAddProduct(productId, nummer)
{
	var ajaxIndex = ajaxObjects.length;
	ajaxObjects[ajaxIndex] = new sack();
	ajaxObjects[ajaxIndex].requestFile = url_addProductToBasket;	// Saving product in this file
	ajaxObjects[ajaxIndex].setVar('productId',productId);
	ajaxObjects[ajaxIndex].setVar('aantal',document.getElementById('aantal_'+nummer).value);
	ajaxObjects[ajaxIndex].setVar('omschrijving',document.getElementById('omschrijving_'+nummer).value);
//	ajaxObjects[ajaxIndex].setVar('prijs',document.getElementById('prijs_'+nummer).value);

var Opties = new Array();
var str = '';
var prijs = document.forms['formulier_'+nummer].elements['prijs'].value;
var toonprijs = new Number(prijs);
var elem = document.getElementById('formulier_'+nummer).elements;
for(var i = 0; i < elem.length; i++)
{
 j = elem[i].name.indexOf('opties');
 if (j >= 0) {
   k = elem[i].type.indexOf('radio');
   l = elem[i].type.indexOf('checkbox');
   if (k >= 0) {
      if(elem[i].checked){

        var temp = elem[i].value.split('_');
        if ( temp[1] > 0 ) {
        toonprijs = toonprijs +(temp[1] - prijs);
        }
	    ajaxObjects[ajaxIndex].setVar(''+elem[i].name+'',elem[i].value);
//        Opties[productId][elem[i].name] = elem[i].value;
      }
    }
   else if (l >= 0) {
      if(elem[i].checked){
        var temp = elem[i].value.split('_');
        if ( temp[1] > 0 ) {
        toonprijs = toonprijs +(temp[1] - prijs);
        }
	    ajaxObjects[ajaxIndex].setVar(''+elem[i].name+'',elem[i].value);

//        Opties[productId][elem[i].name] = elem[i].value;
      }
    }
   else  {
        var temp = elem[i].value.split('_');
        if ( temp[1] > 0 ) {
        toonprijs = toonprijs +(temp[1] - prijs);
        }
	    ajaxObjects[ajaxIndex].setVar(''+elem[i].name+'',elem[i].value);
//        Opties[productId][elem[i].name] = elem[i].value;

    }
  }
}

//	ajaxObjects[ajaxIndex].setVar('opties',Opties);
	ajaxObjects[ajaxIndex].setVar('prijs',document.getElementById('prijs_'+nummer).value);
	ajaxObjects[ajaxIndex].onCompletion = function(){ showAjaxBasketContent(ajaxIndex); };	// Specify function that will be executed after file has been found
	ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function
}


function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}