var amount = 0;
var pid = 0;
var depot = 0;
var regPic = 0;
var personalPic = 0;
var b = '';
var firstTime = true;

$(document).ready(function(){
	
    $.each($.browser, function(i, val) {
		if (i=='safari' && val==true){b='safari';}
		if (i=='opera' && val==true){b='opera';}
		if (i=='msie' && val==true){b='msie';}
		if (i=='mozilla' && val==true){b='mozilla';}
	});
	/*
	if (b != "msie") {
		// FLIR instantiation
		FLIR.init({
			path: root + "/lib/facelift/"
		}, new FLIRStyle({
			mode: 'wrap',
			resizeBox: 'true'
		}));
		FLIR.auto(['h1', 'h2', 'h3']);
	}
	*/
	
	/*
	 * Set Navigation
	 */
	$("#btn_"+ctrl).addClass('selected');
	
	/*
	 * Ajax functions
	 */
	$("#btn_address_search").click(function(){
		searchAddresses(1);
	});
	
	$("#btn_subscribe").click(function(){
		// reset error
		pageTracker._trackPageview('/'+language+'/registration_newsletter');
		$("form#subscribeForm input").removeClass("error");
		$.ajax({
			type:"POST",
			url:root+"/"+language+"/win/subscribe",
			data:$("form#subscribeForm").serialize(),
			dataType:"json",
			success:subscribeSuccess,
			error:postError
		});
	});
	
	$("#btn_intention").click(function(){
		// reset error
		//pageTracker._trackPageview('/'+language+'/send_intention');
		$("form#intentionForm input").removeClass("error");
		$("form#intentionForm textarea").removeClass("error");
		$.ajax({
			type:"POST",
			url:root+"/"+language+"/voornemen/sendintention",
			data:$("form#intentionForm").serialize(),
			dataType:"json",
			success:sendIntentionSuccess,
			error:postError
		});
	});
	
	$("#btn_question").click(function(){
		// reset error
		pageTracker._trackPageview('/'+language+'/personalization_question');
		$("form#personalizationForm input").removeClass("error");
		$.ajax({
			type:"POST",
			url:root+"/"+language+"/personalization/question",
			data:$("form#personalizationForm").serialize(),
			dataType:"json",
			success:personalizationSuccess,
			error:postError
		});
	});
	
	$("#btn_login").click(function(){
		// reset error
		$("form#loginForm input").removeClass("error");
		$.ajax({
			type:"POST",
			url:root+"/"+language+"/user/login",
			data:$("form#loginForm").serialize(),
			dataType:"json",
			success:loginSuccess,
			error:postError
		});
	});
	
	$("#btn_change").click(function(){
		// reset error
		$("#result_change").hide();
		$("form#changeForm input").removeClass("error");
		$.ajax({
			type:"POST",
			url:root+"/"+language+"/user/ajax_update",
			data:$("form#changeForm").serialize(),
			dataType:"json",
			success:changeSuccess,
			error:postError
		});
	});
	
	$("#btn_add").click(function(){
		$.ajax({
			type:"POST",
			url:root+"/"+language+"/user/add_cart",
			data:$("form#addcartForm").serialize(),
			dataType:"json",
			success:addSuccess,
			error:postError
		});
	});
	
	// Loader functions
	$("#loading").ajaxStart(function(){
		$(this).show();
		$("#error").hide();
		$("#error").html("");
		$(".formWrapper").hide();
	});
	
	$("#loading").ajaxComplete(function(){
		$(this).hide();
		$(".formWrapper").show();
	});
	
	/*
	 * Set search parameters for the address database
	 */
	if (typeof params != "undefined") {
		$.each(params, function(k, v){
			switch (k) {
				case "type":
					$("#type_item_" + v).attr("selected", "selected");
					break;
				case "province":
					$("#province_item_" + v).attr("selected", "selected");
					break;
				case "searchfield":
					$("#sel_field option[value='" + v + "']").attr("selected", "selected");
					break;
				case "searchterm":
					$("#searchterm").val(v);
					break;
			}
		});
	}
	
	/*
	 * Set selected subnavigation item
	 */
	if (typeof subpage != "undefined") {
		$("#subnav_"+subpage).addClass('selected');
	}
	
	/*
	 * Add to cart - buttons
	 */
	$(".btn_reg").click(function(){
		pid = $(this).attr("id").replace("btn_addReg_", "");
		formName = "add_purchase_"+pid;
		amount = $("form#"+formName+" input#amount_reg").val();
		addProduct(formName, amount);
	});
	
	$(".btn_depot").click(function(){
		pid = $(this).attr("id").replace("btn_addDepot_", "");
		formName = "add_depot_"+pid;
		addProduct(formName, amount);
	});
	
	/*
	 * Remove from cart - buttons
	 */
	$(".btn_reg_remove").click(function(){
		id = $(this).attr("id");
		removeProduct(id, "reg");
	});
	
	$(".btn_depot_remove").click(function(){
		id = $(this).attr("id");
		removeProduct(id, "depot");
	});
	
	/*
	 * Send cart
	 */
	$("input[name='delivery_method']").change(function(){
		if($(this).val() == "self"){
			$("#order_date_self").fadeIn();
		}else{
			$("#order_date_self").fadeOut("fast");
		}
	});
	
	$("#btn_order").click(function(){
		$.ajax({
			type:"POST",
			url:root+"/"+language+"/user/add_order",
			data:$("form#orderForm").serialize(),
			dataType:"json",
			success:orderSuccess,
			error:postError
		});
	});
	
	/*
	 * Product img buttons
	 */
	$(".btn_close").click(function(){
		handleImg(0, "null");
	});
	
	$(".btn_zoom").click(function(){
		id = $(this).attr("id").replace("zoom_", "");
		handleImg(id, "large");
	});
	
	$(".btn_personal").click(function(){
		id = $(this).attr("id").replace("personal_", "");
		handleImg(id, "personal_large");
	});
	
	function handleImg(id, type){
		if(regPic != 0){
			$("#large_"+regPic).fadeOut("fast", function(){showImg(id, type);});
		}
		if(personalPic != 0){
			$("#personal_large_"+personalPic).fadeOut("fast", function(){showImg(id, type);});
		}
		if(regPic == 0 && personalPic == 0){
			//$("#product_block_"+id).css("background-color", "#fc0");
			//$("#product_block_"+id).css("z-index", "300");
			$("#"+type+"_"+id).fadeIn("def", function(){
				if (type == "large") {
					regPic = id;
				}else{
					personalPic = id;
				}
			});
		}
	}
	
	function showImg(id, type){
		/*
		$("#product_block_"+personalPic).css("background-color", "#c00");
		$("#product_block_"+regPic).css("background-color", "#660");
		$("#product_block_"+id).css("background-color", "#fc0");
		
		
		$("#product_block_"+personalPic).css("z-index", "100"+personalPic);
		$("#product_block_"+regPic).css("z-index", "200"+regPic);
		$("#product_block_"+id).css("z-index", "300");
		*/
		if (type == "personal_large") {
			$("#" + type + "_" + id).fadeIn("def", function(){
				personalPic = id;
				regPic = 0;
			});
		}
		else if (type == "large") {
			$("#" + type + "_" + id).fadeIn("def", function(){	
				regPic = id;
				personalPic = 0;
			});
		}
	}
	
	/*
	 * Font resizing
	 */
	var originalFontSize = $('body').css('font-size');
	
    $(".resetFont").click(function(){
    	$('body').css('font-size', originalFontSize);
  	});
	
	// Increase Font Size
	$(".increaseFont").click(function(){
		var currentFontSize = $('body').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		var newFontSize = String(currentFontSizeNum*1.2) + "px";
		$('body').css('font-size', newFontSize);
		return false;
	});
	// Decrease Font Size
	$(".decreaseFont").click(function(){
		var currentFontSize = $('body').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		var newFontSize = String(currentFontSizeNum*0.8) + "px";
		$('body').css('font-size', newFontSize);
		return false;
	});	
});

function addProduct(formName, amount){	
	amount = $("form#"+formName+" input#amount").val();
	code = $("form#"+formName+" input#code").val();
	if(amount != "" && amount > 0){
		unitPrice = $("form#"+formName+" input#price").val();
		percentage = $("form#"+formName+" input#discount").val();
		percentage = (percentage != "") ? percentage : 0;
		if(amount >= $("form#"+formName+" input#discount_amount").val()){
			discountPrice = ((percentage/100) * unitPrice)*amount;
		}else{
			discountPrice = 0;
		}
		total = (unitPrice * amount) - discountPrice;
		
		urlString = $("form#"+formName).serialize()+"&id="+pid+"&name="+$("#title_"+pid).html()+"&discountPrice="+discountPrice+"&total="+total;
		url = root+"/"+language+"/products/product_add/"+urlString;
		
		Shadowbox.open({
	        player:     'iframe',
	        content:	url,
	        height:     230,
	        width:      320
	    }); 
	}else{
		alert("Sorry, u moet een getal groter dan 0 ingeven");
	}
}

function removeProduct(id, type){
	$.ajax({
		type:"GET",
		url:root+"/"+language+"/user/remove_cart/"+type+"/"+id,
		dataType:"json",
		success:removeSuccess,
		error:postError
	});
}

function searchAddresses(page){
	$.ajax({
		type: "POST",
		url: root+"/"+language+"/addresses/ajax",
		data: {"type":$("#sel_type").val(), "province":$("#sel_province").val(), "searchfield":$("#sel_field").val(), "searchterm":$("#searchterm").val(), "page":page},
		success:searchSuccess,
		error:postError
	});
}


function subscribeSuccess(data){
	if(data.result == 1){
		$("#win_subscription_form").html(data.msg);
	}else{
		$.each(data.error, function(e){
			$("#error").append(data.error[e]+"<br />");
		});
		$("#error").show();
		$.each(data.fields, function(e){
			$("input#"+e).addClass("error");
		});
	}
}

function sendIntentionSuccess(data){
	if(data.result == 1){
		$("#intention_form").html(data.msg);
		$("p.intro").hide();
	}else{
		$.each(data.error, function(e){
			$("#error").append(data.error[e]+"<br />");
		});
		$("#error").show();
		$.each(data.fields, function(e){
			$("input#"+e).addClass("error");
			$("textarea#"+e).addClass("error");
		});
	}
}

function personalizationSuccess(data){
	if(data.result == 1){
		$("#personalization_form").html(data.msg);
	}else{
		$.each(data.error, function(e){
			$("#error").append(data.error[e]+"<br />");
		});
		$("#error").show();
		$.each(data.fields, function(e){
			$("input#"+e).addClass("error");
		});
	}
}

function searchSuccess(data){
	$("#result_addresses").html(data);
}

function loginSuccess(data){
	if(data.result == 1){
		window.location.href = data.location;
	}else{
		$.each(data.error, function(e){
			$("#error").append(data.error[e]+"<br />");
		});
		$("#error").show();
		$("input#passw").addClass("error");
	}
}

function changeSuccess(data){
	if(data.result == 1){
		$("#result_change").html(data.msg);
		$("#result_change").show("fast");
	}else{
		if (data.error != "") {
			$.each(data.error, function(e){
				$("#error").append(data.error[e] + "<br />");
			});
		}
		$("#error").show();
		if(data.fields != ""){
		$.each(data.fields, function(e){
			$("input[name='"+e+"']").addClass("error");
		});
		}
		if (data.delivery_fields != "") {
			$.each(data.delivery_fields, function(e){
				$("input[name='delivery_" + e + "']").addClass("error");
			});
		}
		alert("Opgelet er is een fout opgetreden.");
	}
}

function addSuccess(data){
	if(data.result == 1){
		$(".formWrapper").html(data.msg);
		setTimeout(parent.Shadowbox.close, 1000);
	}else{
		$.each(data.error, function(e){
			$("#error").append(data.error[e]+"<br />");
		});
		$("#error").show();
	}
}

function orderSuccess(data){
	if(data.result == 1){
		$("#result_order").html(data.msg);
		$("#result_order").show("fast");
		$("#cart_address").html("");
		$("#tbl_wrap").hide();
	}else{
		$.each(data.error, function(e){
			$("#error").append(data.error[e]+"<br />");
		});
		$("#error").show();
		$.each(data.fields, function(e){
			$("input[name='"+e+"']").addClass("error");
		});
	}
}

function removeSuccess(data){
	if(data.result == 1){
		if(data.count == 0){
			$("div#"+data.part+"_block").hide();
		}else{
			$("."+data.part+" #row_"+data.pid).hide();
			$("#"+data.part+"_total_excl").html(data.total_excl);
			$("#"+data.part+"_tax").html(data.total_tax);
			$("#"+data.part+"_total_incl").html(data.total_incl);
			$("#"+data.part+"_extra").html(data.total_extra);
		}
	}
}

function postError(data){
	alert(data);
}



function resizeHeader(size){
	/*
	if (firstTime == true) {
		firstTime = false;
	}
	else {
	*/
		var h = "658px";
		var t = 1300;
		if (size == "small") {
			h = "280px";
			t = 800;
		}
		$("#flashwrapper").animate({
			"height": h
		}, t);
	//}
}

function setSubcategories(id){
	var temp = Object();
	output = "<ul class='short_tree_list'>";
	if(id > 0){
		$("#item"+id+" ul li").each(function(){
			output += "<li>";
			$(this).find("ul").remove();
			output += $(this).html();
			output += "</li>";
		});
		$("#subcat").html(output);
	}else if(id == 0){
		$("#category_list li.item_level0").each(function(){
			output += "<li>";
			output += $(this).html();
			output += "</li>";
		});
		$("#subcat").html(output);
	}
}

function resetElements(){
	$("input.amount_input").val("");
}

