var _debug = false;
var _a_timeout = null;
var _key_timeout = 800;

var numexp = /^[\d]+$/;
var emailexp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
var phoneexp = /^([\d\(\)\+\-\/ ]+)$/;

$(document).ready(function(){

	
	if(document.getElementById('product_summary')){
		var msie6 = $.browser == 'msie' && $.browser.version < 7;
		  
		if (!msie6) {
			
			var top = $('#product_summary').offset().top - parseFloat($('#product_summary').css('margin-top').replace(/auto/, 0));
			
			$(window).scroll(function(event){
				var y = $(this).scrollTop();		

				if(y >= top){
					$('#product_summary').addClass('fixed');
				}else{
					$('#product_summary').removeClass('fixed');
				}
			});
		}  
	}

	$(".tooltip").simpletooltip();

	$(".box_deselect").hover(function(){
		$(this).animate({opacity:1},100);
	},function(){
		$(this).animate({opacity:0.8},100);
	});	

	$(".cartRemoveItem").live("click",function(){		
		var id = $(this).attr('rel');		
		removeFromCart(id);
	});

	$(".img_popup").click(function(){
		var vars = $(this).attr('rel');
		var alt = $(this).attr('alt');
		vars = vars.split("|");
		var url = typeof(vars[0]) != "undefined" ? vars[0] : false;
		var w = typeof(vars[1]) != "undefined" ? parseInt(vars[1]) : false;
		var h = typeof(vars[2]) != "undefined" ? parseInt(vars[2]) : false;
		
		if(url === false) return false;
		var d = document.createElement("div");
		d.id = "dialog-preview";
		d.title = alt ? alt : "Förhandsgranskning";
		var p = document.createElement("p");
		var img = new Image();
		p.appendChild(img);
		d.appendChild(p);
			
		$(img).load(function(){
			if(w === false){
				if(typeof(this.width) != "undefined"){
					w = this.width;
				}
			}
			if(h === false){
				if(typeof(this.height) != "undefined"){
					h = this.height;
				}
			}			
			document.body.appendChild(d);
			$("#dialog-preview").dialog("close");

			$(d).dialog({
				resizable: false,
				modal:true,
				width:(w ? w+30 : null),
				height:(h ? h+60 : null)
			});
		}).attr('src',url);
		;
	});
	
	
	
});

function HexToRGB(hex){ 
	return [HexToR(hex),HexToG(hex),HexToB(hex)];
}

function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}


function RGBToHex(rgb) {
	var hex = [
		rgb.r.toString(16),
		rgb.g.toString(16),
		rgb.b.toString(16)
	];
	
	$.each(hex, function (nr, val) {
		if (val.length == 1) {
			hex[nr] = '0' + val;
		}
	});
	return hex.join('');
}

function unique_id(){
	var newDate = new Date;
	return newDate.getTime();
}

function clearOrder(data,whenDone){
	
	if(_debug) $("#debug").append("<li>clearSession ["+decodeURIComponent($.param(data,true))+"]</li>");	
	$.ajax({
		url:doc_www+"inc/ajax/order_clear.php",
		data:data,
		success:function(o){

			if(typeof(whenDone) == "function"){
				whenDone(o);
			}
			
		},error:function(o){
		
		}
	});
}
function setOrder(data,whenDone){
	
	if(_debug) $("#debug").append("<li>setSession ["+decodeURIComponent($.param(data,true))+"]</li>");	
	
	$.ajax({
		url:doc_www+"inc/ajax/order_set.php",
		data:data,
		success:function(o){
			if(typeof(whenDone) == "function") whenDone(o);
		},error:function(o){
		
		}
	});
}

function updateOrder(vals,data,whenDone){
	
	if(_debug) $("#debug").append("<li>updateSession ["+decodeURIComponent($.param(vals,true))+"]</li>");	
	
	var posts = {};
	$.each(vals,function(i,v){
		posts[i] = v;
		
	});
	$.each(data,function(i,v){
		posts[i] = v;
	});
	
	
	$.ajax({
		url:doc_www+"inc/ajax/order_save.php",
		data:posts,
		success:function(o){
			if(typeof(whenDone) == "function"){				
				whenDone(o);
			}
			
		},error:function(o){
		
		}
	});
}



function clearCart(data,whenDone){
	
	if(_debug) $("#debug").append("<li>clearSession ["+decodeURIComponent($.param(data,true))+"]</li>");	
	
	$.ajax({
		url:doc_www+"inc/ajax/cart_clear.php",
		data:data,
		success:function(o){
			
			if(typeof(whenDone) == "function"){
				whenDone(o);
			}
			
		},error:function(o){
		
		}
	});
}
function setCart(data,whenDone){
	
	if(_debug) $("#debug").append("<li>setSession ["+decodeURIComponent($.param(data,true))+"]</li>");	
	
	$.ajax({
		url:doc_www+"inc/ajax/cart_set.php",
		data:data,
		success:function(o){
			if(typeof(whenDone) == "function") whenDone(o);
		},error:function(o){
		
		}
	});
}

function updateCart(data,whenDone){
	
	if(_debug) $("#debug").append("<li>updateSession ["+decodeURIComponent($.param(data,true))+"]</li>");	
	
	$.ajax({
		url:doc_www+"inc/ajax/cart_save.php",
		data:data,
		success:function(o){
			if(typeof(whenDone) == "function"){				
				whenDone(o);
			}
			
		},error:function(o){
		
		}
	});
}






function updatePrice(posts,whenDone){
	
	if(_debug) $("#debug").append("<li>updatePrice ["+decodeURIComponent($.param(posts,true))+"]</li>");	
	
	$.ajax({
		url:doc_www+"inc/ajax/get_price.php",
		data:posts,
		success:function(o){
			if(typeof(whenDone) == "function") whenDone(o);
		},error:function(o){
		
		}
	});
}


function getTotalPrice(whenDone){
	
	$.ajax({
		url:doc_www+"inc/ajax/get_total_price.php",
		data:null,
		success:function(o){
			if(typeof(whenDone) == "function") whenDone(o);
		},error:function(o){
		
		}
	});
}


function removeFromCart(id,when_done){
	if(_debug) $("#debug").append("<li>removeFromCart ["+id+"]</li>");	
	
	$.ajax({
		url:doc_www+'inc/ajax/cart_remove_item.php',
		type:'POST',
		dataType:'json',
		data:{
			id:id
		},
		success:function(resp){
			if(typeof(resp) != "object" || typeof(resp.status) == "undefined" || resp.status == 0){

			}else{
			
				$("#cart_items option[value="+id+"]").remove();
				
				if($("#cart_items option").length == 0){
					$("#shopping_cart .cartTotal").fadeOut();
					$("#cart_total_price").html(resp.total_price);
					$("#cart_items").prepend("<option value=\"0\">Varukorgen är tom</option>").remove();
				}else{
					$("#cart_total_price").html(resp.total_price);
				}				
			}
			if(typeof(when_done) == "function") when_done(resp);
		},
		error:function(o,textStatus, errorThrown){
			alert("ERR: "+o.responseText+" || "+textStatus+" || "+errorThrown);
		}
	});

}


function transf(from,to,className,whenDone){
	
	if(!className) className = "ui-effects-transfer";
	
	$(from).effect("transfer", { className:className,to: to}, 800, function() {
		if(typeof(whenDone) == "function") whenDone();
		/*
		if(conf.shake){
			$("#shopping_cart").effect("shake", { times: 1, direction: "up", distance: 5 }, 100, function() {
			
			});
		}
		*/
		
	});	
}



function addToCart(conf){
	if(_debug) $("#debug").append("<li>addToCart ["+decodeURIComponent($.param(conf,true))+"]</li>");	
	var defaults = {
		category:null,
		id:null,
		transfer: '.send_to_cart',
		transfer_to:'#cart_items',
		speed:1000,
		shake:true,
		when_done : null
	};
	var conf = $.extend({},defaults,conf);
	
	$.scrollTo({ top: 0, left: 0 }, 500);
	
	$(conf.transfer).effect("transfer", { to: conf.transfer_to}, conf.speed, function() {
		$.ajax({
			url:doc_www+'inc/ajax/cart_add_item.php',
			type:'POST',
			dataType:'json',
			data:conf,
			success:function(resp){
				if(typeof(resp) != "object" || typeof(resp.status) == "undefined" || resp.status == 0){

				}else{
					var cartItem = $(resp.html).appendTo("#cart_items");
					$("#cart_items option[value=0]").remove();
					$("#cart_items option[selected]").removeAttr('selected');
					$("#cart_items option[value="+resp.id+"]").attr('selected','selected');
					
					$("#cart_total_price").html(resp.total_price);
					$(".cartTotal").fadeIn();
				}
				if(typeof(conf.when_done) == "function") conf.when_done(resp);
			},
			error:function(o,textStatus, errorThrown){
				
				alert("ERR: "+o.responseText+" || "+textStatus+" || "+errorThrown);
			}
		});


		if(conf.shake){
			$("#shopping_cart").effect("shake", { times: 1, direction: "up", distance: 5 }, 100, function() {
			
			});
		}
		
	});	
}



function rand(minVal,maxVal,floatVal){
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function inspect(t){
	
	var txt = "";
	var textarray = false;
	var count=0;
	for(var i in t){
		txt += i+" = "+t[i]+"\n";
		count++;
		if(count > 20){
			if(textarray === false){textarray = [];}
			textarray.push(txt);
			count=0;
			txt = "";
		}
	}
	if(textarray){
		for(var i in textarray){
			alert(textarray[i]);
		}
	}else{
		alert(txt);
	}
	
}
