document.observe('dom:loaded', function(event) {

	// Uppdatera fraktkostnad live vid steg 2 i kassan när man anger postnummer
	if (document.forms['make_buy']) {
		var zipcode = document.forms['make_buy'].elements['zipcode'];
		if (zipcode!=null){
		zipcode.observe('keyup', function(event) {
		
			new Ajax.Request('/ajax_functions.php?action=make_cart_freight&postnr='+zipcode.value, {
				onComplete: function(reply) {
				
					var get = reply.responseText.evalJSON();
					
					$('freight').innerHTML = get["text"] + ' kr';
					
				}
				
			});
		
		});
		}
	}

});

//Ladda nya bilder
ajaxEngine.registerRequest( 'getPicture', '/ajax_picture.php' );

//Uppdater kundvagnen
ajaxEngine.registerRequest( 'updateCart', '/ajax_cart.php' );
				
//pageMain
ajaxEngine.registerRequest( 'getPageMain', '/ajax_page_main.php' );

//Mer info om produkten
ajaxEngine.registerRequest( 'getMoreInfo', '/ajax_moreinfo.php' );

//Post form
ajaxEngine.registerRequest( 'getPostForm', '/ajax_postform.php' );

function makulera_order(cart_id, other_user) {

	if (confirm ("Är du säker?")) {

		new Ajax.Request('/ajax_functions.php?action=makulera_order&cart_id='+cart_id+'&other_user='+other_user, {
			onComplete: function(reply) {
			
				var get = reply.responseText.evalJSON();
				
				if ( get["text"] == true )
					window.location = '/?fancyAlert=makulera_order';
				else
					fancyAlert('not_available');
				
			}
			
		});
		
	}

}

function changeOffer(id, name, parent) {

	$$('.offer_select').each(function(obj) {
	
		if (obj.id != parent)
			obj.selectedIndex = 0;
	
	});

	$('add_offer_name').innerHTML = name;
	$('add_offer').value = id;

}

function deleteOffer(offer_id) {

	if (confirm ("Är du säker?")) {
	
		$('delete_offer').value = offer_id;
		$('offers').request();
		$('offer_'+offer_id).setStyle({ display: "none" });
		
	}

}

function addOfferItem(id) {
	new Effect.ScrollTo('basket', 300, { queue : 'start' });
	
	$('offer_add2cart_'+id).request({
		onComplete: function(){ 
			setTimeout(function() {
				fancyAlert('add_to_cart');
				updateCarts();
			}, 1000);		
		}
	});

}

function changeOfferAmount(id, value) {

	$('amount_'+id).value = value;

}

function addComplementItem(id) {
	new Effect.ScrollTo('basket', 300, { queue : 'start' });
	
	$('complement_add2cart_'+id).request({
		onComplete: function(){ 
			setTimeout(function() {
				fancyAlert('add_to_cart');
				updateCarts();
			}, 1000);
		}
	});

}

function changeComplementAmount(id, value) {

	$('complement_amount_'+id).value = value;

}

function getFreight() {

	var postnr = $('postnr').value;
	var model = $('model').options[$('model').selectedIndex].value;

	new Ajax.Request('/ajax_functions.php?action=make_freight&postnr='+postnr+'&artnr='+model, {
		onComplete: function(reply) {
		
			var get = reply.responseText.evalJSON();
			zip_price = parseInt(get["text"]);
			
			if (zip_price < 1 ){
				$('fraktwrapper').innerHTML = "För att göra en beställning till din adress måste du kontakta oss.";
			} else {
				$('freightPrice').innerHTML = get["text"] + ' kr';
			}
			
		}
		
	});

}

function addToCart() {
	new Effect.ScrollTo('basket', 300, { queue : 'start' });
	
	$('add2cart').request({
		onComplete: function(){ 
			setTimeout(function() {
				fancyAlert('add_to_cart');
				updateCarts();
			}, 1000);
		}
	});

}

function updateCarts() {

	if ( $('cart') ) {
		new Ajax.Request('/clean.php?doc=item_cart', {
			method:  'get',
			onSuccess:  function(response){
				var html = response.responseText;
				$('cart').replace(html);
			}
		});
	}
	
	if ( $('basket') ) {
		new Ajax.Request('/clean.php?doc=page_rightbox&only_basket=true', {
			method:  'get',
			onSuccess:  function(response){
				var html = response.responseText;
				$('basket').replace(html);
				
				$$('tr.totalt').each(function(t) {
					new Effect.Highlight(t, { startcolor : '#DAEADD',  endcolor : '#ffffff' });
					//new Effect.Pulsate(t, { duration : 1, pulses : 3 });
				});
			}
		});
	}

}

function setPayment(payment_id) {

	new Ajax.Request('/ajax_functions.php?action=cart_payment&payment='+payment_id, {
		onComplete: function(reply) {
		
			var get = reply.responseText.evalJSON();
			//alert(get["text"]);
			
		}
		
	});

}

function deleteItem(item) {

	new Ajax.Request('/ajax_functions.php?action=cart_delete&item='+item, {
		onComplete: function(reply) {
		
			var get = reply.responseText.evalJSON();
			
			if ( get["text"] == true ) {
				//$('item_'+item).setStyle({ display: "none" });
				//$('cart_item_amount_'+item).value = 0;
				updateCarts();
			}
			
		}
		
	});

}

function updateKlarnaPrice() {

    var pclass = $("part_payment").value;

    var months = "3";

    switch(pclass) {

	case "1760":
	    months = "3";
	    break;

	case "1761":
	    months = "6";
	    break;

	case "1762":
	    months = "12";
	    break;

	case "1570":
	    months = "24";
	    break;
    }

    var text = "Du kommer att betala " + klarna_prices[pclass] + " kr";

    if(pclass == "-1") {

	text += " p&aring; en g&aring;ng."

    }
    else if(pclass == "373") {

	text += " vilket är 1/24 av summan.";
    }
    else {
	
	text += " varje m&aring;nad i " + months + " m&aring;nader.";
    }

    $("klarna_price_info_box").update(text);
}

function updateAmount(item, amount) {

	new Ajax.Request('/ajax_functions.php?action=cart_amount&item='+item+'&amount='+amount, {
		onComplete: function(reply) {
		
			var get = reply.responseText.evalJSON();
			
			if ( get["text"] == true ) {
				//updateSums(item, amount);
				updateCarts();

				window.location.reload();	
			}
			
		}
		
	});

}

function updateSums(item, amount) {
	
	// Get values
	var price = $('cart_item_price_'+item).value;
	var total = price*amount;
	var cart_total = total;
	
	// Update the hidden input value
	$('cart_item_amount_'+item).value = amount;
	$('cart_item_total_'+item).value = total;
	
	// Loop through all the other items in the cart
	$$('.cart_totals').each(function(obj) {
	
		if ( obj.id != 'cart_item_total_'+item )
			cart_total = parseInt(cart_total) + parseInt(obj.value);
		
	});
	
	// Format the sum
	cart_total = number_format(cart_total, "", "", " ");
	
	// Place in in every existing "total_sums"-class
	$$('.total_sums').each(function(obj) {
		
		obj.innerHTML = cart_total;
		
	});
	
	// Update small cart
	updateSmallCart();

}

function trPicture(product_id, picture_id) {
	ajaxEngine.registerAjaxElement( 'midPicture' );
	ajaxEngine.sendRequest( 'getPicture', 'prod=' + product_id, 'im=' + picture_id );
	return false;
}
function trCart(type, category, price, amount, id, properties) {
	if (!ajaxEngine.isRegisterAjaxElement( 'cartSum' ))
		ajaxEngine.registerAjaxElement( 'cartSum' );
	if (properties == ''){
		ajaxEngine.sendRequest( 'updateCart', 'session_id=' + session_id, 'type=' + type, 'state=add2cart', 'price=' + price, 'amount=' + amount, 'doc=product', 'id=' + id, 'category=' + category );
	}else{
		properties = properties.match(/[a-z0-9,;.:-_'+=() ]/gi);
		properties = properties.join('');
		//alert("ajaxEngine.sendRequest( 'updateCart', 'session_id=' + session_id, 'type=' + type, 'state=add2cart', 'price=' + price, 'amount=' + amount, 'doc=product', 'id=' + id, 'category=' + category, "+properties+" );");
		eval("ajaxEngine.sendRequest( 'updateCart', 'session_id=' + session_id, 'type=' + type, 'state=add2cart', 'price=' + price, 'amount=' + amount, 'doc=product', 'id=' + id, 'category=' + category, "+properties+" );");
	}
	//document.location.href = "/index.php?doc=cart&timestamp=" + id + "&session_id=" + session_id;
	//document.location.href = '/index.php?doc=showcart&product=' + id;
	alert('Din kundvagn har uppdaterats.');
	return false;
}
function trUpdateCart(args) {
	ajaxEngine.registerAjaxElement( 'cartSum' );
	ajaxEngine.registerAjaxElement( 'cartTotal' );
	ajaxEngine.registerAjaxElement( 'cartContent' );
	
	for (i=0;i<args.length;i++)
		args[i] = "'" + args[i] + "'";
	//alert(args);
	eval("ajaxEngine.sendRequest( 'updateCart', 'session_id=' + session_id, " + args.join(', ') + " );");
	return false;
}
function trProductMoreInfo(id, action, obj) {
	ajaxEngine.registerAjaxElement( 'productOthers' );
	ajaxEngine.registerAjaxElement( 'productFittings' );				
	ajaxEngine.registerAjaxElement( 'productReviews' );
	
	if (obj.innerHTML.indexOf('+&nbsp;&nbsp;') >= 0) {
		obj.innerHTML = obj.innerHTML.replace('+&nbsp;&nbsp;', '-&nbsp;&nbsp;&nbsp;');
		obj.style.color = '#997000';
		show = 1;
	} else {
		show = 0;
		obj.innerHTML = obj.innerHTML.replace('-&nbsp;&nbsp;&nbsp;', '+&nbsp;&nbsp;');
		obj.style.color = '';
	}
	ajaxEngine.sendRequest( 'getMoreInfo', 'id=' + id, 'action=' + action, 'show=' + show, 'session_id=' + session_id );
	return false;
}

function trProductEdit(id, action, obj, args) {
	ajaxEngine.registerAjaxElement( 'product_edit_' + id );
	
	if ( obj != null ) {
		if (action == "editproperties")
			obj2 = setObject2('product_edit_fittings_' + id);
		else
			obj2 = setObject2('product_edit_properties_' + id);
		
		obj2.innerHTML = obj2.innerHTML.replace('-&nbsp;&nbsp;&nbsp;', '+&nbsp;&nbsp;');
		obj2.style.color = '';
		
		if (obj.innerHTML.indexOf('+&nbsp;&nbsp;') >= 0) {
			obj.innerHTML = obj.innerHTML.replace('+&nbsp;&nbsp;', '-&nbsp;&nbsp;&nbsp;');
			obj.style.color = '#997000';
			show = 1;
		} else {
			show = 0;
			obj.innerHTML = obj.innerHTML.replace('-&nbsp;&nbsp;&nbsp;', '+&nbsp;&nbsp;');
			obj.style.color = '';
		}
	} else
		show = 1;
		
	for (i=0;i<args.length;i++)
		args[i] = "'" + args[i] + "'";
	
	if (args.length > 1) {
		for (i=0;i<args.length;i++) {
			if (args[i] == "'action=delete'") {
				if (!confirm('Vill du verkligen ta bort?'))
					return false;
			}
		}
	}
	
	eval("ajaxEngine.sendRequest( 'getPageMain', 'product=' + id, 'doc=' + action, 'session_id=' + session_id, 'show=' + show, " + args.join(', ') + " );");
	return false;
}

function trSearch( category, cat_name, keyword, obj) {
		
	/*as = document.getElementsByTagName('a');
	for (i=0;i<as.length;i++) {
		tmp = as.item(i);
		if (tmp.className.indexOf('menu2') == 0)
			tmp.style.color = '#4D4D4D';
	}
	if (obj)
		obj.style.color = "#997000";
	
	trPageMain(new Array('doc=search', 'type=1', 'doc=search', 'category=' + category, 'cat_name=' + cat_name, 'name=' + keyword));
	return false;*/
}

function trPageMain(args) {
	/*ajaxEngine.registerAjaxElement( 'pageMain' );
	
	dhtmlHistory.add(args.join(':'), args);
	
	for (i=0;i<args.length;i++)
		args[i] = "'" + args[i] + "'";
						
	eval("ajaxEngine.sendRequest( 'getPageMain', 'session_id=' + session_id, " + args.join(', ') + " );");
		
	return false;*/
}

var isIE = document.all?true:false;
var isNS = document.layers?true:false;
function onlyDigits(e) {
var _ret = true;
if (isIE) {
	if (window.event.keyCode < 46 || window.event.keyCode > 57) {
		window.event.keyCode = 0;
		_ret = false;
	}
}
if (isNS) {
	if (e.which < 46 || e.which > 57) {
		e.which = 0;
		_ret = false;
	}
}
return (_ret); 
}
if (isNS) document.captureEvents(Event.KEYPRESS);


function checkEnter(e){
	var characterCode
	
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	} else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}				
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		trSearch('','',document.forms['searchForm'].name.value, null);
		return false 
	} else{
		return true 
	}
}

function ajaxSubmit(form) {
	ajaxEngine.registerAjaxElement( form.divid.value );

	var obj = null;
	var product_id = 0;
	
	args = new Array();
	for (i=0;i<form.elements.length;i++) {
		if (form.elements.item(i).name != 'skicka') {
			args[i] = "'" + form.elements.item(i).name + '=' + form.elements.item(i).value + "'";
			if (form.elements.item(i).type == "text" && obj == null)
				obj = form.elements.item(i);
		}
		
		if (form.elements.item(i).name == 'product')
			product_id = form.elements.item(i).value;
	}
	
	eval("ajaxEngine.sendRequest( 'getPostForm', " + args.join(', ') + " );");

	if (obj)
		obj.focus();
	
	if (product_id > 0) {
		if ($('name_prop_' + product_id)) {
			$('name_prop_' + product_id).value = '';
			$('value_prop_' + product_id).value = '';
		}
	}

	return false;
}



//Vanlig update!
var xmlHttp, productId;

function createXMLHttpRequest() {
	if (window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		xmlHttp = new XMLHttpRequest();
	}
}

function refreshProductList(obj) {
	productId = obj.form.product.value;
	createXMLHttpRequest();
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.open("GET", "/ajax_page_main.php?doc=sql&category=" + obj.value, true);
	xmlHttp.send(null);	
}

function handleStateChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			updateProductList();
		}
	}
}

function updateProductList() {
	//var productList = setObject2("productList_" + productId);
	var productList = $('productList_' + productId);
	
	if (productList.childNodes.length > 0) {
		while(productList.childNodes.length > 0) {
			productList.removeChild(productList.childNodes[0]);
		}
	}
	
	var result = xmlHttp.responseXML.getElementsByTagName("product");
	var values = xmlHttp.responseXML.getElementsByTagName("id");
	var option = null;
	for (var i = 0; i < result.length; i++) {
		option = document.createElement("option");
		option.appendChild(document.createTextNode(result[i].firstChild.nodeValue));
		option.value = values[i].firstChild.nodeValue;
		productList.appendChild(option);
	}
}

function editChildProp(id) {
	$('child_name').value = $('child-name-' + id).innerHTML;
	
	if ($('child-price-' + id))
		$('child_value').value = $('child-price-' + id).innerHTML;
	
	if ($('child-art-' + id))
		$('art_code').value = $('child-art-' + id).innerHTML;
	
	$('child_action').value = 'editchild';
	$('edit_id').value = id;
	$('addchild_submit').value = 'Uppdatera';
	$('clean_child').disabled = '';
}

function cleanChildProp() {
	$('child_name').value = '';
	$('child_value').value = '';
	$('art_code').value = '';
	
	$('child_action').value = 'addchild';
	$('edit_id').value = '1';
	$('addchild_submit').value = 'Lägg till';
	$('clean_child').disabled = 'disabled';
}
