/*----------------------------------------------------------------------------------------------------------------------------*/



function locationChange(variable, value)
{
	var variables = getQueryVariables();
	var queryString = '?';
	var found = false;
	for (i = 0; i < variables.length; i++) {
		if ( variables[i][0] == variable ) {
			variables[i][1] = value;
			found = true;
		}
		if (i == 0) {
			queryString += variables[i][0] + '=' + variables[i][1];
		} else {
			queryString += '&' + variables[i][0] + '=' + variables[i][1];
		}
	}
	if (found == false) {
		if (variables.length > 0) {
			queryString = queryString + '&' + variable + '=' + value;
		} else {
			queryString = queryString + variable + '=' + value;
		}
	}
	window.location = queryString;
}

/* Get something from GET query */

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
}

function getQueryVariables() {
  var query = window.location.search.substring(1);
 var pairs = new Array();
  if (query != '') {
	  var vars = query.split("&");
	  for (var i=0; i < vars.length; i++) {
	    var pair = vars[i].split("=");
	    pairs[pairs.length] = pair;
	  }
  }
  return pairs;
}

function initContactType() {
	var val = getGETVar('contact_over');
	if (val != '') {
		document.getElementById('contact_over').value = val;
	}
}


/*----------------------------------------------------------------------------------------------------------------------------*/
/* Handle mouseover for images in topmenu */

function topMenuOver(oImg)
{
	var newSrc = oImg.src.replace('.gif','_act.gif');
	return(newSrc);
}

/*----------------------------------------------------------------------------------------------------------------------------*/
/* Handle mouseout for images in topmenu */

function topMenuOut(oImg)
{
	var newSrc = oImg.src.replace('_act.gif','.gif');
	return(newSrc);

}


/*----------------------------------------------------------------------------------------------------------------------------*/
/* Handle AJAX requests for newsletters */

function handleNewsletter(vlag,nbid)
{
	if(nbid != 'undefined')
	{
		/* Specific newsletter */
		var url = '/modules/newsletter/newsletter.php?action=newsletter&vlag='+vlag+'&nbid='+nbid;
	}
	else
	{
		/* Overview */
		var url = '/modules/newsletter/newsletter.php?action=overview&vlag='+vlag;

	}

	new Ajax.Updater('newslettercontent', url);
}

/*----------------------------------------------------------------------------------------------------------------------------*/
/* Handle AJAX requests for searches */

function handleSearch(vlag,query,start,skipbackcheck)
{

	if(query != '')
	{



	if(!skipbackcheck)
	{

		/* Check if user has pressed back button on browser, to make sure the correct AJAX call is made */
		var currentUrl = document.location.href;
		var currentUrlElements = currentUrl.split('#');
		if ((!isNaN(currentUrlElements[1])) && (!currentUrlElements[1].length == 0))
		{
			var start = currentUrlElements[1];
		}

	}


	/* Create URL */
	//var url = '/modules/search/search.php?query='+encodeURIComponent(query)+'&vlag='+vlag+'&start='+start;

	/* Request AJAX Update */
	//new Ajax.Updater('searchresults', url);

	//$("div.searchresults").load(url);

	$.ajax({
	   type: "GET",
	   url: "/modules/search/search.php",
	   data: "query="+encodeURIComponent(query)+"&vlag="+vlag+"&start="+start,
	   success: function(msg){
		 $("div#searchresults").append(msg);
	   }
	 });


	}

}

function getCookie(Name)
{
	var search = Name + "=";
	if (document.cookie.length > 0)
	{
		offset = document.cookie.indexOf(search);
		if (offset != -1)
		{
			offset += search.length;
			end = document.cookie.indexOf(";", offset);
			if (end == -1)
			end = document.cookie.length;
			return unescape(document.cookie.substring(offset, end));
		}
	}
}

function tjek()
{
	var t = new Date().getTime();

	if (document.inlogformulier.onthoud.checked == true)
	{
		var m = document.inlogformulier.email.value;
		var p = document.inlogformulier.password.value;

		var Verval = new Date();
		Verval.setMonth(Verval.getMonth()+6);

		document.cookie = "onthoudn="+m+"; expires=" + Verval.toGMTString();
		document.cookie = "onthoudp="+p+"; expires=" + Verval.toGMTString();
	}else{
		var Verval = new Date();
		Verval.setMonth(Verval.getMonth()-6);
		document.cookie = "onthoudn=; expires=" + Verval.toGMTString();
		document.cookie = "onthoudp=; expires=" + Verval.toGMTString();
	}

	return true;

}

function laden()
{
	var on = getCookie("onthoudn");
	var op = getCookie("onthoudp");

	if (op && on)
	{
		if(testIsValidObject(document.inlogformulier)){
			document.inlogformulier.emailLogin.value = on;
			document.inlogformulier.passwordLogin.value = op;
			document.inlogformulier.onthoud.checked = true;
		}
		if(testIsValidObject(document.inlogformulier_main)){
			document.inlogformulier_main.emailLogin.value = on;
			document.inlogformulier_main.passwordLogin.value = op;
		}

	}
	
	// foutmelding tonene in simplemodalbox
	 var fout = getGETVar("fout");

	 if (fout != '')
	 {
	 	 showLoginError('klantLoginFoutMeldingen');
	 }
}

function testIsValidObject(objToTest) {
	if (null == objToTest) {
		return false;
	}
	if ("undefined" == typeof(objToTest) ) {
		return false;
	}
	return true;

}

function getGETVar( name )
{
   name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
   var regexS = "[\\?&]"+name+"=([^&#]*)";
   var regex = new RegExp( regexS );
   var results = regex.exec( window.location.href );
   if( results == null )
                  return "";
   else    return results[1];
}

function switchSmallTabs(number)
{
	document.getElementById('liTab0').className = 'first';
	document.getElementById('divTab0').style.display = 'none';

	for (i = 1; i < 10; i++) {
		if (document.getElementById('liTab'+i) != undefined) {
			document.getElementById('liTab'+i).className = '';
		}
		if (document.getElementById('divTab'+i) != undefined) {
			document.getElementById('divTab'+i).style.display = 'none';
		}
	}
	if (number == 0) {
		document.getElementById('liTab0').className = 'first active';
	} else {
		document.getElementById('liTab'+number).className = 'active';
	}
	document.getElementById('divTab'+number).style.display = 'block';
}

function str_replace(search, replace, subject, count) {
	var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
	f = [].concat(search),
	r = [].concat(replace),
	s = subject,
	ra = r instanceof Array, sa = s instanceof Array;
	s = [].concat(s);
	if (count) {
		this.window[count] = 0;
	}

	for (i=0, sl=s.length; i < sl; i++) {
		if (s[i] === '') {
			continue;
		}
		for (j=0, fl=f.length; j < fl; j++) {
		temp = s[i]+'';
		repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
		s[i] = (temp).split(f[j]).join(repl);
		if (count && s[i] !== temp) {
			this.window[count] += (temp.length-s[i].length)/f[j].length;}
		}
	}
	return sa ? s : s[0];
}

function validEmail(emailStr){
	var filter=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(emailStr)) {
		return true;
	} else {
		return false;
	}
}

function validPhone(phoneStr){
	var filter=/^[0-9]{3}\-[0-9]{7}$/i
	if (filter.test(phoneStr)) {
		return true;
	} else {
		return false;
	}
}

function setHeaderOpacity()
{
	if ($("li.formOfferteHeader").length > 0)	{
		//first remove than add
		//$("li.formOfferteHeader").css("opacity","1.0");
		$("li.formOfferteHeader").css("opacity","0.6");
	}
}


var currentOfferteDivOpen = 'product';
function animateDivs(divPrefix)
{
	if (divPrefix != currentOfferteDivOpen) {
		$('#'+currentOfferteDivOpen+'Content').slideUp();
		$('#'+currentOfferteDivOpen+'Header > img').attr('src','/grafix/dropdown.gif');
		$('#'+currentOfferteDivOpen+'Header').attr('class','formOfferteHeader').css("opacity","0.6");
		currentOfferteDivOpen = divPrefix;
		//hack for ie7
		if (divPrefix == 'acc')	{

			var heightOr = $('#'+divPrefix+'Content').data("originalHeight");
			var visible = $('#'+divPrefix+'Content').is(":visible");
            if(!heightOr ){
                // get original height
                heightOr = $('#'+divPrefix+'Content').show().height();
                // update the height
                $('#'+divPrefix+'Content').data("originalHeight", heightOr);
                // if the element was hidden, hide it again
                if( !visible ) $('#'+divPrefix+'Content').hide();
            }

			//hack for footer ie
			//if (!$.browser.msie)	{
				//var defHeight = heightOr + 26;
			//}else	{
				var defHeight = heightOr;
			//}
			$('#'+divPrefix+'Content').css('height',0).show().animate({height: defHeight}, {duration: 500});
			//google
			pageTracker._trackPageview('/offerteTrechter/stap2.html');

		}else	{
			$('#'+divPrefix+'Content').slideDown();
		}

		if (divPrefix == 'data')	{
			//google
			pageTracker._trackPageview('/offerteTrechter/stap3.html');
			//delete the cookies from login
			var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, 4) == ('acc_') || cookie.substring(0, 6) == ('select')) {
                	var cookieName = cookie.split('=');
                    $.cookie(cookieName[0], null, { path: '/'});
                }
            }
            handleLoginDataSwitch();
            handleLandSelect();
            reselInfoPopup();
            handleLoginActions();
            autoCompleteHandler();            
		}

		if (divPrefix == 'product')	{
			pageTracker._trackPageview('/offerteTrechter/stap1.html');
		}


		$('#'+divPrefix+'Header > img').attr('src','/grafix/dropdown_active.gif');
		$('#'+divPrefix+'Header').attr('class','formOfferteHeaderActive').css("opacity","1.0");

	}
}

function handleLandSelect()
{
	$("select.countryHandlerEvent").change(function()	{
		var slItem = $("select.countryHandlerEvent option:selected").val();
		//alert(slItem);
		if (slItem == 'nw')	{
			//show the input field
			$("select.countryHandlerEvent").css("width","100px");
			$("div.specialInputCountryEvent input[type=text]").removeAttr("disabled").show();
			$("div.specialInputCountryEvent").show();
		}else	{
			//hide the input field
			$("div.specialInputCountryEvent input[type=text]").attr("disabled","disabled").hide();
			$("div.specialInputCountryEvent").hide();
			$("select.countryHandlerEvent").css("width","211px");
		}
	})

	$("select.countryHandler").change(function()	{
		var slItem = $("select.countryHandler option:selected").val();
		//alert(slItem);
		if (slItem == 'nw')	{
			//show the input field
			$("select.countryHandler").css("width","100px");
			$("div.specialInputCountry input[type=text]").removeAttr("disabled").show();
			$("div.specialInputCountry").show();
		}else	{
			//hide the input field
			$("div.specialInputCountry input[type=text]").attr("disabled","disabled").hide();
			$("div.specialInputCountry").hide();
			$("select.countryHandler").css("width","211px");
		}
	})
	
	$("select.countryHandlerConfirm").change(function()	{
		var slItem = $("select.countryHandlerConfirm option:selected").val();
		//alert(slItem);
		if (slItem == 'nw')	{
			//show the input field
			$("select.countryHandlerConfirm").css("width","100px");
			$("div.specialInputCountry input[type=text]").removeAttr("disabled").show();
			$("div.specialInputCountry").show();
		}else	{
			//hide the input field
			$("div.specialInputCountry input[type=text]").attr("disabled","disabled").hide();
			$("div.specialInputCountry").hide();
			$("select.countryHandlerConfirm").css("width","280px");
		}
	})
}

function countChecked(element) {
	var n = $(element+":checked").length;
    return n;
}

function handleLoginDataSwitch()
{
	$("div.offGegRight a.klantlogin").click(function()	{
		//fill the content with login box
		$("div.offGegRight table.klantform_table").hide();
		//show login box
		$("div.tempLogin").show();
		$(this).css({
			color: '#000000',
			cursor: 'default',
			"text-decoration": 'none'
		});
		//set the link for the klantdata
		$("div.offGegRight a.klantdata").css({
			color: '#00a8ff',
			cursor: 'pointer',
			"text-decoration": 'underline'
		});
		//show the kruis
		$("a.closeDealer").show();
	});

	$("div.offGegRight a.klantdata, a.closeDealer").click(function()	{
		//fill the content with login box
		$("div.tempLogin").hide();
		//show klantdata box
		$("div.offGegRight table.klantform_table").show();
		$("div.offGegRight a.klantdata").css({
			color: '#000000',
			cursor: 'default',
			"text-decoration": 'none'
		});
		//set the link for the klantlogin
		$("div.offGegRight a.klantlogin").css({
			color: '#00a8ff',
			cursor: 'pointer',
			"text-decoration": 'underline'
		});
		$("a.closeDealer").hide();
	});
}


function handleLoginDropDown()
{
		
	if ($("div#loginDropBox").length > 0)	{
	
		//check for open by default
		if( $.cookie( 'openLogin' ) ){
			$("div#loginDropBox").show();
		}
		
		$("a.loginRoll").click(function()	{
			$("div#loginDropBox").slideDown('slow');
			$.cookie('openLogin', '1', { path: '/', expires: 100 });
		})
		
		$("span.closeDrop").live("click",function()	{
			$('div#loginDropBox').slideUp('slow');
			$.cookie('openLogin', null, { path: '/'});
		})
	}
}

function handleLoginHeadTitle(data)
{
	if ($("div#loginDropBox").length > 0)	{
		if (data == '0')	{
			//niet ingelogd, set the correct span
			if ($("span.notLogin").hasClass("notView"))	{
				$("span.notLogin").removeClass("notView");
				$("span.isLogin").addClass("notView");
			}
			$("span.extraAddName").hide();
			
		}else	{
			
			if ($("span.isLogin").hasClass("notView"))	{
				$("span.isLogin").removeClass("notView");
				$("span.notLogin").addClass("notView");
			}
			//remove old names
			if ($("span.extraAddName").length > 0)	{
				$("span.extraAddName").remove();
			}
			$("span.isLogin").after('<span class="extraAddName">'+data+'</span>');
			$("span.extraAddName").show();
			
		}
	}
}

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

//functie voor het afhandelen van de select acties van een offerte
$(document).ready(function()	{

	//check offerte form function
	if ($("form#offerteForm").length > 0)	{
		handleConfirmForm();
	}
	
	//login dropdown
	handleLoginDropDown();

	function handleProductContact()
	{
		$("div#productContent input[type=checkbox].selectAction").click(function()	{
			//get the count
			var c = $("div#productContent input[type=checkbox].selectAction:checked").length;

			if (c == 1)	{
				//correct, goOn
				//show the aantal field
				var cVal = $(this).val();
				$("div#productContent input[type=text].input_offerte_smaller#art_"+cVal+", div#productContent span.offerteAantal#"+cVal+ ",div#productContent div.bg_input_offerte_smaller#bgh_"+cVal).show();
				if ($("div#productContent input[type=text].input_offerte_smaller#art_"+cVal).val() == '0')	{
					$("div#productContent input[type=text].input_offerte_smaller#art_"+cVal).val('1');
				}
				//fade the others
				$("div#productContent table.myProdTable").not("."+cVal+",#table_29").fadeTo(400,0.4);

				$("a.extraNavLeftLink").removeClass("extraNavLeftLinkDisabled");
			}else if (c == 0)	{
				//show all
				$("div#productContent input[type=text].input_offerte_smaller, div#productContent span.offerteAantal, div#productContent div.bg_input_offerte_smaller").hide();
				//reset the val
				$("div#productContent input[type=text].input_offerte_smaller").val('0');
				$("div#productContent table.myProdTable").not("#table_29").fadeTo(400,1.0);

				//remove the accosoires witch are selected
				$("div#accContent input[type=checkbox].selectActionAcc:checked").removeAttr("checked");
				$("div#accContent span.offerteAantal").hide();
				$("div#accContent div.bg_input_offerte_smaller").hide();
				$("div#accContent input[type=text].input_offerte_smaller").val('0').hide();
				$("div#accContent span#accC").html('');
				$("div#accContent input[type=hidden]").val('0').attr("disabled","disabled");

				$("a.extraNavLeftLink").addClass("extraNavLeftLinkDisabled");

			}else	{
				//more than 1
				//remove old ones
				$("div#productContent input[type=text].input_offerte_smaller, div#productContent span.offerteAantal, div#productContent div.bg_input_offerte_smaller").hide();
				$("div#productContent input[type=checkbox].selectAction:checked").removeAttr("checked");
				//reset the val
				$("div#productContent input[type=text].input_offerte_smaller").val('0');
				$("div#productContent table.myProdTable").not("#table_29").fadeTo(400,1.0);
				//set the new one
				var cVal = $(this).val();
				$("div#productContent input[value="+cVal+"].selectAction").attr("checked",true);
				$("div#productContent input[type=text].input_offerte_smaller#art_"+cVal+", div#productContent span.offerteAantal#"+cVal+",div#productContent div.bg_input_offerte_smaller#bgh_"+cVal).show();
				if ($("div#productContent input[type=text].input_offerte_smaller#art_"+cVal).val() == '0')	{
					$("div#productContent input[type=text].input_offerte_smaller#art_"+cVal).val('1');
				}
				$("div#productContent table.myProdTable").not("."+cVal+",#table_29").fadeTo(400,0.4);

				$("a.extraNavLeftLink").removeClass("extraNavLeftLinkDisabled");
			}
		})
		
		
		handleImagesGallery();
	}

	setHeaderOpacity();

	handleProductContact();

	$("div#productContent input[type=checkbox].selectActionGrp").click(function()	{

		var c = $("div#productContent input[type=checkbox].selectActionGrp:checked").length;

			if (c == 1)	{
				//correct, goOn
				//show the aantal field
				var sp = $(this).val().split('-');
				var cVal = sp[0];
				var pId = sp[1];
				var flag = sp[2];
				if (pId == '' || cVal == '' || pId == 'undefined' || cVal == 'undefined')
					return;

				//fade the others
				//$("div#productContent table#table_29").not("."+cVal).fadeTo(400,0.4);
				$("div#productContent table.myProdTable").not("."+cVal+",#table_25").fadeTo(400,0.4);

				//decide the request uri
				if ($("input.chReqInfo").length > 0)	{
					//change, get the change info
					var chInfo = $("input.chReqInfo").val().split("|");
					var oID = chInfo[0];
					var sAuth = chInfo[1];
					if (oID == '' || sAuth == '' || oID == 'undefined' || sAuth == 'undefined')
						return;
					var reqUri = "/javascript/ajaxRequests/getOffGroupProducts.php?oID="+oID+"&sAuth="+sAuth+"&gId="+cVal+"&pId="+pId+"&vlag="+flag;

				}else	{
					//normal
					var reqUri = "/javascript/ajaxRequests/getOffGroupProducts.php?gId="+cVal+"&pId="+pId+"&vlag="+flag;
				}

				//request voor onderliggende
				$("div.productOverview").load(reqUri," ",function()	{
					$("div.productOverview").slideDown('normal',function()	{
						$.scrollTo('div#jumpProduct',800);
						handleProductContact();
						//check for change
						if ($("input.chReqInfo").length > 0 && $("div#productContent input[type=checkbox].selectAction:checked").length > 0)	{
							$("a.extraNavLeftLink").removeClass("extraNavLeftLinkDisabled");
						}else	{
							$("a.extraNavLeftLink").addClass("extraNavLeftLinkDisabled");
						}

						//check for showing / hiding products
						if ($("div#productContent input[type=checkbox].selectAction:checked").length > 0)	{
							//trigger a click
							$("div#productContent input[type=checkbox].selectAction:checked").trigger("click").attr("checked",true);
						}


					});
				})


			}else if (c == 0)	{
				//show all
				//$("div#productContent table#table_29").fadeTo(400,1.0);
				$("div#productContent table.myProdTable").not("#table_25").fadeTo(400,1.0);
				$("div#productContent input[type=text].input_offerte_smaller").val('0');

				//remove childs
				$("div.productOverview").slideUp('normal');

				//remove the accosoires witch are selected
				$("div#accContent input[type=checkbox].selectActionAcc:checked").removeAttr("checked");
				$("div#accContent span.offerteAantal").hide();
				$("div#accContent div.bg_input_offerte_smaller").hide();
				$("div#accContent input[type=text].input_offerte_smaller").val('0').hide();
				$("div#accContent span#accC").html('');
				$("div#accContent input[type=hidden]").val('0').attr("disabled","disabled");

				$("a.extraNavLeftLink").addClass("extraNavLeftLinkDisabled");

			}else	{
				//more than 1
				//remove old ones
				$("div#productContent input[type=checkbox].selectActionGrp:checked").removeAttr("checked");
				//reset the val
				//$("div#productContent table#table_29").fadeTo(400,1.0);
				$("div#productContent table.myProdTable").not("#table_25").fadeTo(400,1.0);
				//set the new one
				var sp = $(this).val().split('-');
				var cVal = sp[0];
				var pId = sp[1];
				var flag = sp[2];
				if (pId == '' || cVal == '' || pId == 'undefined' || cVal == 'undefined')
					return;

				$("div#productContent input[value="+cVal+"-"+pId+"-"+flag+"].selectActionGrp").attr("checked",true);
				//$("div#productContent table#table_29").not("."+cVal).fadeTo(400,0.4);
				$("div#productContent table.myProdTable").not("."+cVal+",#table_25").fadeTo(400,0.4);

				//remove childs
				$("div.productOverview").slideUp('normal',function()	{

					//request voor onderliggende
					$("div.productOverview").load("/javascript/ajaxRequests/getOffGroupProducts.php?gId="+cVal+"&pId="+pId+"&vlag="+flag," ",function()	{
						$("div.productOverview").slideDown('normal',function()	{
							$.scrollTo('div#jumpProduct',800);
							handleProductContact();
							$("a.extraNavLeftLink").addClass("extraNavLeftLinkDisabled");
						});
					})

				});


			}

	})

	//check for showing the dropdown for groups
	if ($("div#productContent input[type=checkbox].selectActionGrp:checked").length > 0)	{
		//trigger a click
		$("div#productContent input[type=checkbox].selectActionGrp:checked").trigger("click").attr("checked",true);
	}
	//check for showing / hiding products
	if ($("div#productContent input[type=checkbox].selectAction:checked").length > 0)	{
		//trigger a click
		$("div#productContent input[type=checkbox].selectAction:checked").trigger("click").attr("checked",true);
	}

	//opvangen van accossoires
	$("div#accContent input[type=checkbox].selectActionAcc").click(function()	{

		var checked = this.checked;

		if (checked != false)	{
			var aVal = $(this).val();
			//type
			var aType = $(this).attr('id');

			//checked artikel
			var art = $("div#productContent input[type=checkbox].selectAction:checked").val();
			//get the input value
			var artCount = $("div#productContent input[type=text]#art_"+art).val();

			//show a line
			$("div#accContent span.offerteAantal#"+aVal).show();


			//2 options
			if (aType == 'ig')	{
				//Invoer gebruiker, show field
				$("div#accContent input[type=text]#acc_"+aVal+ ",div#accContent div.bg_input_offerte_smaller#bgh_"+aVal).show();
				$("div#accContent input[type=text]#acc_"+aVal).val('1');

			}else if (aType == 'aas')	{
				//afhankelijk aantal systemen
				$("div#accContent input[name*="+aVal+"][type=hidden]").val(artCount).removeAttr('disabled');
				$("div#accContent span.aasSpan_"+aVal).html(artCount);

			}else	{
				alert('Onbekende invoer');
			}

		}else	{

			var aVal = $(this).val();
			//type
			var aType = $(this).attr('id');

			$("div#accContent span.offerteAantal#"+aVal).hide();


			//2 options
			if (aType == 'ig')	{
				//Invoer gebruiker, show field
				$("div#accContent input[type=text]#acc_"+aVal+ ",div#accContent div.bg_input_offerte_smaller#bgh_"+aVal).hide();

			}else if (aType == 'aas')	{
				//afhankelijk aantal systemen
				$("div#accContent input[name*="+aVal+"][type=hidden]").val('0').attr("disabled","disabled");
				$("div#accContent span.aasSpan_"+aVal).html('');

			}else	{
				alert('Onbekende invoer');
			}

		}

	})


	/**
	* Cookies standaard opslaan zodra een veld wordt ingevuld.
	* Bij het uitchecken van de save_info checkbox, worden alle cookies verwijderd.
	**/

	//eerst controleren of de cookies gebruikt moeten worden, of dat de gegevens geladen moeten worden aan de hand van de inlog
	$.ajax({
		url: "/javascript/ajaxRequests/checkLogin.php",
		type: "GET",
		dataType: "html",
		//cache: false,
		success: function(data)	{
			if (data == '0')	{
				activCookie();			
			}else if (data != '1')	{
				activCookieLogin();
			}
			handleLoginHeadTitle(data);
		}
	});

	function activCookie()
	{
		//alleen bij offerte formulier, aan de hand van de parents
		var pars = jQuery.makeArray($("input#save_info").parents());
		var arrPar = [];

		$(pars).each(function(){
		    arrPar.push($(this).attr('id'));
		})

		if (jQuery.inArray('dataContent',arrPar) > 0)    {

			var selector = $("input[type=text],select,input[type=checkbox]#save_info,input[type=radio],textarea#remarks").not(".input_offerte_smaller");
			remember(selector);

			$("input[type=checkbox]#save_info").click(function()	{

				var checked = this.checked;

				if (checked == false)	{
					delCookie(selector);
				}
			})
		}
	}
	
	//remember only the event fields
	function activCookieLogin()
	{
		//alleen bij offerte formulier, aan de hand van de parents
		var pars = jQuery.makeArray($("input#save_event").parents());
		var arrPar = [];

		$(pars).each(function(){
		    arrPar.push($(this).attr('id'));
		})

		if (jQuery.inArray('dataContent',arrPar) > 0)    {

			var selector = $("input#datumEvenement,input#aantalDagen,input#plaatsEvenement,select#landEvenement,textarea#remarks");
			remember(selector);
			
		}
	}

	//load login box
	var curVlag = $("input[type=hidden][name=curVlag]").val();
	var curOff = $("input[type=hidden][name=curOff]").val();
	var url = "/modules/klanten/get_login_status.php?vlag="+curVlag+"&curOff="+curOff;
	var foutOff = getVar('foutOff');
	if (foutOff != '') {
		url=url+"&foutOff="+foutOff;
	}
	$("div.tempLogin").load(url,'',function()	{

		handleLoginActions();

		// foutmelding tonene in simplemodalbox
		 var foutOff = getVar("foutOff");

		 if (foutOff != '')
		 {
	 		 showLoginError('klantLoginFoutMeldingenOff');
		 }

	});

	//check for showing
	if ($("table#table_29").length != 0)	{
		//check if the cookie exists
		if ($.cookie('selectGroup'))	{
			var sp = $.cookie('selectGroup').split('-');
			var cVal = sp[0];
			var pId = sp[1];
			if (pId == '' || cVal == '' || pId == 'undefined' || cVal == 'undefined')
				return;

			//request voor onderliggende
			$("div.productOverview").load("/javascript/ajaxRequests/getOffGroupProducts.php?gId="+cVal+"&pId="+pId," ",function()	{
				$("div.productOverview").slideDown('normal',function()	{
					$.scrollTo('div#jumpProduct',800);
					handleProductContact();
					$("a.extraNavLeftLink").addClass("extraNavLeftLinkDisabled");
				});
			})

		}
	}

	//see what page must bee show
	var returnFromLogin = getVar('rfl');
	if (returnFromLogin != '' && returnFromLogin == 'true')	{
		//check if the cookie is made
		if ($.cookie('selectProduct'))	{
			animateDivs('data');
		}
	}
	checkLoginAndButton();

	handleImagesGallery();

})


function checkLoginAndButton()
{
	var returnFromLogin = getVar('rfl');
	if (returnFromLogin == '' || returnFromLogin == 'false')	{
		//set the next button to not activ
		$("a.extraNavLeftLink").addClass("extraNavLeftLinkDisabled");
	}
	//when changing, set active
	if ($("input.chReqInfo").length > 0)	{
		$("a.extraNavLeftLink").removeClass("extraNavLeftLinkDisabled");
	}
}

function handleImagesGallery()
{
	//handle the photo click, for showing the gallery
	$("#table_25 img.artAfb, #table_25 a.imgLink, #table_26 img.accAfbBig").click(function()	{
		var curArt = $(this).attr('name').split('_');

		//build the div
		var galDiv = $('<div id="galleryPopUp">&nbsp;</div>');
		$("body").append(galDiv);

		var element = document.getElementById('galleryPopUp');

		$("#galleryPopUp").load("/javascript/ajaxRequests/getGalleryPop.php?curStr="+curArt[0]+"&vlag="+curArt[1]).modal({

		containerCss:{backgroundColor:"#fff",height:600,padding:0,width:800},

		onOpen: function(dialog)
			{
			dialog.overlay.fadeIn('fast', function () {
				dialog.container.slideDown('normal', function () {
					dialog.data.fadeIn('normal');

					element.style.visibility = 'visible';


				});
			});
			},
		onClose: function(dialog)
			{
				dialog.overlay.fadeOut('fast', function () {
					dialog.container.fadeOut('fast', function () {
						dialog.data.fadeOut('fast', function () {

							$.modal.close(); // must call this!
							$('#galleryPopUp').remove(); // and this too!

						});
					});
				});
			}
		}).css({
			width: '900px',
			height: '700px'
		})

	});
}

function handleLoginActions()	{

	$("a#loginButtonOff, a.saveCook").click(function()	{
		//get the selected products and accosiores
		//check if the group tab exists
		if ($("table#table_29").length != 0)	{
			//groups exists
			var acGrp = $("input[type=checkbox].selectActionGrp:checked");
			$.cookie('selectGroup', $(acGrp).val(), { path: '/', expires: 1 });
		}		
		//the product
		var acPrd = $("input[type=checkbox].selectAction:checked");
		$.cookie('selectProduct', $(acPrd).val(), { path: '/', expires: 1 });
		//the product count
		var acPrdCount = $("input[type=text].input_offerte_smaller#art_"+$(acPrd).val());
		if ($(acPrdCount).val() > 0)	{
			$.cookie('selectProductCount', $(acPrdCount).val(), { path: '/', expires: 1 });
		}
		//accosoires
		var accSc = $("input[type=checkbox].selectActionAcc:checked");
		$(accSc).each(function()	{
			var cookName = "acc_"+$(this).val();
			$.cookie(cookName, $(this).val(), { path: '/', expires: 1 });
			//count
			var accScCount = $("input[name*=acc["+$(this).val()+"]]");
			if ($(accScCount).val() > 0)	{
				var cookCName = "acc_"+$(this).val()+"_count";
				$.cookie(cookCName, $(accScCount).val(), { path: '/', expires: 1 });
			}
		})


	})

	$("a#loginButtonOff").click(function()	{
		$("form#offerteLogin").submit();
	})

}

function getVar( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null ) {
		return "";
	} else {
		return results[1];
	}
}

function autoCompleteHandler()
{
	//check of there are autocomplete fields
	if ($("input.hasAutoComplete").length > 0)	{
		
		//oke, add the functions
		$("input.hasAutoComplete").autocomplete("/javascript/ajaxRequests/getCompleteValue.php", {
			width: 750,
			matchContains: true,
			//autoFill: true,
			scroll: false
		});

		$("input.hasAutoComplete").result(function(event, data, formatted) {
			if (data != undefined)	{
				$("input[name=suSelect].autoCompleteVal").val(data[1]);
			}
		});
		
		//handle the submit
		$("a.selectOfferte").unbind('click').click(function()	{
						
			//check the value
			var selectOff = $("input[type=hidden][name=suSelect]").val();
			if (selectOff != '' && selectOff != 'undefined')	{
				
				//save the data
				//get the selected products and accosiores
				//check if the group tab exists
				if ($("table#table_29").length != 0)	{
					//groups exists
					var acGrp = $("input[type=checkbox].selectActionGrp:checked");
					$.cookie('selectGroup', $(acGrp).val(), { path: '/', expires: 1 });
				}				
				//the product
				var acPrd = $("input[type=checkbox].selectAction:checked");
				$.cookie('selectProduct', $(acPrd).val(), { path: '/', expires: 1 });
				
				//the product count
				var acPrdCount = $("input[type=text].input_offerte_smaller#art_"+$(acPrd).val());
				if ($(acPrdCount).val() > 0)	{
					$.cookie('selectProductCount', $(acPrdCount).val(), { path: '/', expires: 1 });
				}
				//accosoires
				var accSc = $("input[type=checkbox].selectActionAcc:checked");
				$(accSc).each(function()	{
					var cookName = "acc_"+$(this).val();
					$.cookie(cookName, $(this).val(), { path: '/', expires: 1 });
					//count
					var accScCount = $("input[name*=acc["+$(this).val()+"]]");
					if ($(accScCount).val() > 0)	{
						var cookCName = "acc_"+$(this).val()+"_count";
						$.cookie(cookCName, $(accScCount).val(), { path: '/', expires: 1 });
					}
				})
				
				//check for a checked event info
				var showEvent = '0';
				if ($("input[name=showEvent]:checked").length == 1)	{
					showEvent = '1';
				}
				
				//make a request to set the data
				$.ajax({
					url: "/javascript/ajaxRequests/setSuOfferte.php",
					type: "GET",
					dataType: "html",
					data: "selectOff=" + selectOff,
					complete: function(XMLHttpRequest, textStatus) {
						var data = XMLHttpRequest.responseText;
						if (is_numeric(data))	{
							var loc = '/modules/offerteaanvraag/offerteAanvraag.php?type='+getVar('type')+'&vlag='+getVar('vlag')+'&rfl=true&productID='+getVar('productID')+'&sus='+data+'&se='+showEvent;
							setTimeout("window.location = '"+loc+"'",500);
						}else	{
							alert('Het selecteren van de offerte is mislukt');							
						}
					}
				});
				
			}else	{
				alert("Geen offerte geselecteerd");
			}
			
		});
	}
}


function showLoginError(elementName){

	var element = document.getElementById(elementName);

	$.modal($(element),{

    	minHeight:17,
		containerCss:{backgroundColor:"#fff",height:130,padding:0,width:322},

		onOpen: function(dialog)
		{
			dialog.overlay.fadeIn('fast', function () {
				dialog.container.slideDown('normal', function () {
					dialog.data.fadeIn('normal');

					element.style.visibility = 'visible';


				});
			});
		},
		onClose: function(dialog)
		{
			dialog.overlay.fadeOut('fast', function () {
				dialog.container.fadeOut('fast', function () {
					dialog.data.fadeOut('fast', function () {

						$.modal.close(); // must call this!
						$("#"+elementName).remove(); // and this too!

					});
				});
			});
		}

	});
}

//delete all the cookies
function delCookie(selector)
{
	 $(selector).each(function(){

    	var name = $(this).attr('name');
    	if( $.cookie( name ) ){
    		$.cookie(name, null, { path: '/'});
		}

	})
}

//cookies
function remember( selector ){
    $(selector).each(
    	function(){
    		//if this item has been cookied, restore it
    		var name = $(this).attr('name');

    		if( $.cookie( name ) ){
    			if (name == 'gender' && $(this).attr('value') == $.cookie(name))	{
					$(this).attr('checked','checked');
				}else if (name == 'gender' && $(this).attr('value') != $.cookie(name))	{
					//do nothing
    			}else if (name == 'save_info')	{
					$(this).attr('checked','checked');
    			}else	{
					$(this).val( $.cookie(name) );
    			}

    		}
    		//assign a change function to the item to cookie it
    		$(this).change(
    			function(){
    				if (name == 'save_info')	{
						var ch = this.checked;

						if (ch != false)	{
							$.cookie(name, $(this).val(), { path: '/', expires: 1065 });							
						}else	{
							$.cookie(name, null, { path: '/'});
						}						
    				}else	{    					
    					if (name == 'aantalDagen' || name == 'plaatsEvenement' || name == 'landEvenement' || name == 'datumEvenement' || name == 'remarks')	{
    						$.cookie(name, $(this).val(), { path: '/', expires: 14 });
						}else	{
    						$.cookie(name, $(this).val(), { path: '/', expires: 1065 });
						}
					}
    			}
    		);
    	}
    );
}



function checkProducts(message, message2)
{
	if ($("div#productContent").css("display") != 'none')	{
		var found = false;
		//var values = $('#table_25 tr td div > input[type=text]').not(':hidden');
		var values = $('table.checkTables tr td input[type=text]');		
		for ( i  = 0; i < values.length; i++) {
			var numeric = is_numeric(values[i].value);
			if (!numeric) {
				alert(message);
				return false;
			} else if (values[i].value > 0) {
				found = true;
				$('table.checkTables tr td div > input[type=text]').val(round(values[i].value));
				//check the accessoires
				$("input.selectActionAcc:checked").each(function()	{
					//check only aas acc
					var chVal = $(this).val();
					if ($("span.aasSpan_"+chVal).length > 0)	{
						//set the new values
						$("span.aasSpan_"+chVal).html(round(values[i].value));
						$("input[type=hidden][name=acc["+chVal+"]]").val(round(values[i].value));
					}
				})
			}
		}
		if (found) {
			animateDivs('acc');
			return true;
		} else {
			alert(message2);
			return false;
		}
	}else	{
		animateDivs('acc');
		return true;
	}
}

function checkAccessoires(message, message2)
{
	var found = false;
	var values = $('#table_26 tr td > input[type=text]');
	for ( i  = 0; i < values.length; i++) {
		var numeric = is_numeric(values[i].value);
		if (!numeric) {
			alert(message);
			return false;
		}else	{
			$('#table_26 tr td > input[type=text]').val(round(values[i].value));
		}
	}
	animateDivs('data');
	return true;
}


function handleConfirmForm()
{
	//check the clicks on a radio
	$("input[name=diffShipping]:radio").click(function()	{
		var rVal = $(this).val();
		if (rVal == 'ja')	{
			$("div#question1").slideDown('slow');
		}else if (rVal == 'nee')	{
			$("div#question1").slideUp('slow');
		}
	});

	//question 2
	$("input[name=extraBuildDays]:radio").click(function()	{
		var rVal = $(this).val();
		if (rVal == 'ja')	{
			$("div#question2").slideDown('slow');
		}else if (rVal == 'nee' || rVal == 'nb')	{
			$("div#question2").slideUp('slow');
		}
	});

	//question 3
	$("input[name=extraContactperson]:radio").click(function()	{
		var rVal = $(this).val();
		if (rVal == 'ja')	{
			$("div#question3").slideDown('slow');
		}else if (rVal == 'nee')	{
			$("div#question3").slideUp('slow');
		}
	});
}


function reselInfoPopup()
{

  if ($("img.reselInfo").length > 0)	{

	  var hideDelay = 500;
	  var currentID;
	  var hideTimer = null;

	  $('#personPopupContainer').remove();

	  // One instance that's reused to show info for the current person
	  var container = $('<div id="personPopupContainer">'
	      + '<table width="" border="0" cellspacing="0" cellpadding="0" align="center" class="personPopupPopup">'
	      + '<tr>'
	      + '   <td class="corner topLeft"></td>'
	      + '   <td class="top"></td>'
	      + '   <td class="corner topRight"></td>'
	      + '</tr>'
	      + '<tr>'
	      + '   <td class="left">&nbsp;</td>'
	      + '   <td><div id="personPopupContent"></div></td>'
	      + '   <td class="right">&nbsp;</td>'
	      + '</tr>'
	      + '<tr>'
	      + '   <td class="corner bottomLeft">&nbsp;</td>'
	      + '   <td class="bottom">&nbsp;</td>'
	      + '   <td class="corner bottomRight"></td>'
	      + '</tr>'
	      + '</table>'
	      + '</div>');

	  $('body').append(container);

	  var popupInfo = $("div.reselData").html();

	  $('img.reselInfo').live('mouseover', function()
	  {

	      if (hideTimer)
	          clearTimeout(hideTimer);

	      var pos = $(this).offset();
	      var width = $(this).width();
	      container.css({
	          left: (pos.left + width) + 'px',
	          top: pos.top - 5 + 'px'
	      });

	      $('#personPopupContent').html(popupInfo);


	      container.css('display', 'block');
	  });

	  $('img.reselInfo').live('mouseout', function()
	  {
	      if (hideTimer)
	          clearTimeout(hideTimer);
	      hideTimer = setTimeout(function()
	      {
	          container.css('display', 'none');
	      }, hideDelay);
	  });

	  // Allow mouse over of details without hiding details
	  $('#personPopupContainer').mouseover(function()
	  {
	      if (hideTimer)
	          clearTimeout(hideTimer);
	  });

	  // Hide after mouseout
	  $('#personPopupContainer').mouseout(function()
	  {
	      if (hideTimer)
	          clearTimeout(hideTimer);
	      hideTimer = setTimeout(function()
	      {
	          container.css('display', 'none');
	      }, hideDelay);
	  });
  }
}




function is_numeric (mixed_var) {
    // Returns true if value is a number or a numeric string
    if (mixed_var === '') {
        return false;
    }

    return !isNaN(mixed_var * 1);
}

function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities
    //
    // version: 909.322
    // discuss at: http://phpjs.org/functions/get_html_translation_table
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}

    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};

    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }

    return hash_map;
}


function round (val, precision, mode) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Onno Marsman
    // +      input by: Greenseed
    // +    revised by: T.Wild
    // +      input by: meo
    // %        note 1: Great work. Ideas for improvement:
    // %        note 1:  - code more compliant with developer guidelines
    // %        note 1:  - for implementing PHP constant arguments look at
    // %        note 1:  the pathinfo() function, it offers the greatest
    // %        note 1:  flexibility & compatibility possible
    // *     example 1: round(1241757, -3);
    // *     returns 1: 1242000
    // *     example 2: round(3.6);
    // *     returns 2: 4
    // *     example 3: round(2.835, 2);
    // *     returns 3: 2.84
    // *     example 4: round(1.1749999999999, 2);
    // *     returns 4: 1.17
    // *     example 5: round(1.17499999999999, 2);
    // *     returns 5: 1.18

    /* Declare Variables
     * retVal  - temporay holder of the value to be returned
     * V       - String representation of val

     * integer - Integer portion of val
     * decimal - decimal portion of val
     * decp    - characterindex of . [decimal point] inV
     * negative- was val a negative value?
     *
     * _round_half_oe - Rounding function for ROUND_HALF_ODD and ROUND_HALF_EVEN

     * _round_half_ud - Rounding function for ROUND_HALF_UP and ROUND_HALF_DOWN
     * _round_half    - Primary function for round half rounding modes
     */
    var retVal=0,v='',integer='',decimal='',decp=0,negative=false;
    var _round_half_oe = function (dtR,dtLa,even){
        if (even === true) {
            if (dtLa == 50) {
                if ((dtR % 2) === 1) {
                    if (dtLa >= 5) {
                        dtR+=1;
                    } else {
                        dtR-=1;
                    }
                }
            }else if (dtLa >= 5) {
                dtR+=1;
            }
        }else{
            if (dtLa == 5) {
                if ((dtR % 2) === 0) {
                    if (dtLa >= 5) {
                        dtR+=1;
                    }else{
                        dtR-=1;
                    }
                }
            }else if (dtLa >= 5) {
                dtR+=1;
            }
        }

        return dtR;
    };
    var _round_half_ud = function (dtR,dtLa,up) {
        if (up === true) {
            if (dtLa>=5) {
                dtR+=1;
            }
        }else{
            if (dtLa>5) {
                dtR+=1;
            }
        }
        return dtR;
    };
    var _round_half = function (val,decplaces,mode){
    /*Declare variables
         *V       - string representation of Val
         *Vlen    - The length of V - used only when rounding intgerers

         *VlenDif - The difference between the lengths of the original V
         *          and the V after being truncated
         *decp    - character in index of . [decimal place] in V
         *integer - Integr protion of Val
         *decimal - Decimal portion of Val
         *DigitToRound - The digit to round

         *DigitToLookAt- The digit to comapre when rounding
         *
         *round - A function to do the rounding
         */
        var v = val.toString(),vlen=0,vlenDif=0;
        var decp = v.indexOf('.');

        var digitToRound = 0,digitToLookAt = 0;
        var integer='',decimal='';
        var round = null,bool=false;
        switch (mode) {
            case 'up':
                bool = true;
                // Fall-through
            case 'down':
                round = _round_half_ud;
                break;
            case 'even':
                bool = true;
            case 'odd':
                round = _round_half_oe;
                break;
        }
        if (decplaces < 0){ //Int round
            vlen=v.length;

            decplaces = vlen + decplaces;
            digitToLookAt = Number(v.charAt(decplaces));
            digitToRound  = Number(v.charAt(decplaces-1));
            digitToRound  = round(digitToRound,digitToLookAt,bool);
            v = v.slice(0,decplaces-1);
            vlenDif = vlen-v.length-1;

            if (digitToRound == 10){
                v = String(Number(v)+1)+"0";
            }else{
                v+=digitToRound;
            }

            v = Number(v)*(Math.pow(10,vlenDif));
        }else if (decplaces > 0){
            integer=v.slice(0,decp);
            decimal=v.slice(decp+1);
            digitToLookAt = Number(decimal.charAt(decplaces));

            digitToRound  = Number(decimal.charAt(decplaces-1));
            digitToRound  = round(digitToRound,digitToLookAt,bool);
            decimal=decimal.slice(0,decplaces-1);
            if (digitToRound==10){
                v=Number(integer+'.'+decimal)+(1*(Math.pow(10,(0-decimal.length))));
            }else{
                v=Number(integer+'.'+decimal+digitToRound);
            }
        }else{
            integer=v.slice(0,decp);
            decimal=v.slice(decp+1);
            digitToLookAt = Number(decimal.charAt(decplaces));

            digitToRound  = Number(integer.charAt(integer.length-1));
            digitToRound  = round(digitToRound,digitToLookAt,bool);
            decimal='0';
            integer = integer.slice(0,integer.length-1);
            if (digitToRound==10){
                v=Number(integer)+1;
            }else{
                v=Number(integer+digitToRound);
            }
        }
        return v;
    };


    //precision optional - defaults 0
    if (typeof precision == 'undefined') {
        precision = 0;
    }
    //mode optional - defaults round half up
    if (typeof mode == 'undefined') {
        mode = 'PHP_ROUND_HALF_UP';
    }

    if (val < 0){ //Remember if val is negative
        negative = true;
    }else{
        negative = false;
    }

    v = Math.abs(val).toString(); //Take a string representation of val
    decp = v.indexOf('.');        //And locate the decimal point
    if ((decp == -1) && (precision >=0)){
   /* If there is no deciaml point and the precision is greater than 0
         * there is no need to round, return val
         */
        return val;
    }else{
        if (decp == -1){
            //There are no decimals so intger=V and decimal=0
            integer = v;
            decimal = '0';
        }else{
            //Otherwise we have to split the decimals from the integer
            integer = v.slice(0,decp);
            if (precision >= 0){
                //If the precision is greater than 0 then split the decimals from the integer
                //We truncate the decimals to a number of places equal to the precision requested+1
                decimal = v.substr(decp+1,precision+1);
            }else{
                //If the precision is less than 0 ignore the decimals - set to 0
                decimal = '0';
            }
        }
        if ((precision > 0) && (precision >= decimal.length)){
            /*If the precision requested is more decimal places than already exist
            * there is no need to round - return val
            */
            return val;
        }else if ((precision < 0) && (Math.abs(precision) >= integer.length)){
           /*If the precison is less than 0, and is greater than than the
             *number of digits in integer, return 0 - mimics PHP
             */
            return 0;
        }
        val = Number(integer+'.'+decimal); // After sanitizing recreate val
    }

    //Call approriate function based on passed mode, fall through for integer constants
    switch (mode){
        case 0:
        case 'PHP_ROUND_HALF_UP':
            retVal = _round_half(val,precision,'up');
            break;
        case 1:
        case 'PHP_ROUND_HALF_DOWN':
            retVal = _round_half(val, precision,'down');
            break;
        case 2:
        case 'PHP_ROUND_HALF_EVEN':
            retVal = _round_half(val,precision,'even');
            break;
        case 3:
        case 'PHP_ROUND_HALF_ODD':
            retVal = _round_half(val,precision,'odd');
            break;
    }
    if (negative){
        return 0-retVal;
    }else{
        return retVal;
    }
}


