addLoadEvent(prepShowMoreProductInfo);
addLoadEvent(callFrontPageTableMarker);
addLoadEvent(setVings);
addLoadEvent(preFields);
addLoadEvent(setEditableTables);
addLoadEvent(checkInteressts);
addLoadEvent(checkForPopups);
addLoadEvent(weekPlan);
addLoadEvent(setWeightDirections);

var fastGuideCurNumLink;
function showFastMenu(objId, num)
{
	var curObj = document.getElementById('fastBox' + objId);
	var exitDiv = document.getElementById('exitDiv');
	var coverDiv = document.getElementById('coverDiv');
	var links = document.getElementById('jsFastGuideLinks').getElementsByTagName('a');
	var frontVideo = document.getElementById("frontVideo");
	
	if(frontVideo)frontVideo.style.visibility = "hidden";
	
	for(i=0;i<links.length;i++)
	{
		links[i].className = '';
	}
	
	links[num].className = 'hover';
	fastGuideCurNumLink = num;
	
	exitDiv.onmouseover = function()
	{
		exitDiv.style.display = "none";
		coverDiv.style.display = "none";
		curObj.style.display = "none";
		for(i=0;i<links.length;i++)
		{
			links[i].className = '';
		}
		if(frontVideo)frontVideo.style.visibility = "visible";
	}
	
	exitDiv.style.display = "block";
	coverDiv.style.display = "block";
	curObj.style.display = "block";
}


function activateHoverFunc(linkElm) {
	var submitDiv = linkElm.parentNode;
	
	var divs = submitDiv.getElementsByTagName('div');
	var yesNoSpans = divs[0];
	var yes = yesNoSpans.getElementsByTagName('span')[1];
	var no = yesNoSpans.getElementsByTagName('span')[2];
	var coverLine = divs[divs.length - 1]
	var coverinLine = divs[divs.length - 2]
	var inputs = submitDiv.getElementsByTagName('input');
	
	yes.onmousedown = function()
	{
		submitDiv.value = "true";
		saveDietComment(submitDiv);
		submitDiv.style.display = "none";
		submitDiv.parentNode.parentNode.className += " completed";
	}
	
	no.onclick = function()
	{
		
		submitDiv.className = "submitData hover active";
		submitDiv.onmouseout = function(){}
		submitDiv.onmouseover = function(){}
		coverinLine.onmouseover = function()
		{
			submitDiv.className = "submitData";
		}
		inputs[1].parentNode.onsubmit = function()
		{
			submitDiv.value = inputs[0].value;
			saveDietComment(submitDiv);
			var submitsParent = submitDiv.parentNode;
			var commentTag = document.createElement('p');
			commentTag.className = "comment";
			commentTag.innerHTML = submitDiv.value;
			submitsParent.appendChild(commentTag);
			submitDiv.style.display = "none";
			submitDiv.parentNode.parentNode.className += " completed";
			return false;
		}
		inputs[0].focus();
	}
	
	submitDiv.onmouseover = function()
	{
		submitDiv.className = "submitData hover";
	}
	
	submitDiv.onmouseout = function()
	{
		submitDiv.className = "submitData";
	}
}





function setWeightDirections() {
	var weightList = document.getElementById('weightList');
	if(!weightList)return false;
	
	var weightListFadeOut = document.getElementById('weightListFadeOut');
	var listElms = weightList.getElementsByTagName('li');
	var liBefore;
	var valueBefore;
	var count = listElms.length-1;
	
	if(listElms.length < 5)
		weightListFadeOut.style.display = "none";
	
	
	for(var i=listElms.length-1; i>=0; i--)
	{
		if(count<6)
		{
			var curLi = listElms[i];
			
			//find value (value is in a span)
			var curValue = parseFloat(curLi.getElementsByTagName('span')[0].innerHTML.replace(/,/,'.'));
			var directionImg = document.createElement('img');
			
			if(valueBefore < curValue)
				directionImg.src = "graphic/w_wrong.gif";
				
			if(valueBefore > curValue)
				directionImg.src = "graphic/w_right.gif";
				
			if(valueBefore == curValue || directionImg.src == "")
				directionImg.src = "graphic/w_lig.gif";
				
			curLi.appendChild(directionImg);
				
			valueBefore = curValue;
		}
		count--;
	}
}

function completedCorrect(answer, dag, uge)
{
	var notCompletedCorrect = document.getElementById('notCompletedCorrect');
	if(!answer) {
		window.location = 'make_note.php?uge=' + uge + '&dag=' + dag;
//		notCompletedCorrect.style.display = "block";
	}
	else
		notCompletedCorrect.style.display = "none";
}


function eatCompletedCorrect(answer)
{
	var notCompletedCorrect = document.getElementById('eatCorrectNo');
	if(!answer)
		notCompletedCorrect.style.display = "block";
	else
		notCompletedCorrect.style.display = "none";
}

function display(objName)
{
	document.getElementById(objName).style.display = "block";
}

function reviewTraining(obj)
{
	alert(obj);
	/*var curRow = obj;
	var trainingProgramTableWeek = document.getElementById('trainingProgramTableWeek');
	var evaluateDay = document.getElementById('evaluateDay');
	if(!trainingProgramTableWeek)return false;
	if(!curRow)return false;
	if(!evaluateDay)return false;
	var trs = trainingProgramTableWeek.getElementsByTagName('tr');
	
	var week = "none";
	if(obj.className.indexOf('week1') != -1) week = 1;
	if(obj.className.indexOf('week2') != -1) week = 2;
	if(obj.className.indexOf('week3') != -1) week = 3;
	if(obj.className.indexOf('week4') != -1) week = 4;
	if(obj.className.indexOf('week5') != -1) week = 5;
	if(obj.className.indexOf('week6') != -1) week = 6;
	if(obj.className.indexOf('week7') != -1) week = 7;
	week = "week" + week;
	
	for(var i=0;i<trs.length;i++)
	{
		var curTr = trs[i];
		if(curTr.className.indexOf('header') == -1 & curTr != curRow)
			curTr.style.display = "none";
		
		if(curTr.className.indexOf(week) == -1)
			curTr.style.display = "none";
	}
	evaluateDay.style.display = "block";*/
}

function weekPlan(weekNumber)
{
	var trainingProgramTableWeek = document.getElementById('trainingProgramTableWeek');
	if(!trainingProgramTableWeek)return false;
	var trs = trainingProgramTableWeek.getElementsByTagName('tr');
	var urlString = document.location + ""; 
	urlString = urlString.replace(/#/, "");
	var weekNr = "week" + urlString.split('?week=')[1]; if(weekNr) weekNr = weekNr.split('&')[0]; 
	var weekDay = "day" + urlString.split('&day=')[1];  
	if(weekDay=="dayundefined")weekDay=false;
	if(weekNr=="weekundefined")weekNr='weekall';
	var diet = false;
	if(trainingProgramTableWeek.className.indexOf('diet') != -1) diet = true;
	
	var daysVisible = 0;
	
	for(var i=0;i<trs.length;i++)
	{
		var curTr = trs[i];
		//curTr.title = "Klik her for at indtaste status";
		if(diet && curTr.className.indexOf('header') == -1)
			curTr.className += " dietClass";
			
		curTr.onclick = function()
		{
			if(this.className.indexOf('header') == -1 && diet==false)
			{
				/*location.href='/?uge='+weekNr+'&day='+weekDay; */
				/* reviewTraining(this); */
				this.style.background = "#eee";
			}
		}
		
		if(weekNr == 'weekall')
		{
			curTr.style.visibility = "visible";
		}
		else
		{
			
			if(curTr.className.indexOf(weekNr) == -1 & i!=0)
				curTr.style.display = "none";
			else
			{
				curTr.style.visibility = "visible";
			}
			
			
			if(weekDay != false)
			{
				if(curTr.className.indexOf(weekDay) == -1 & curTr.className.indexOf('header') == -1)
					curTr.style.display = "none";
				
				//if(curTr.className.indexOf('header') == -1)
				//	reviewTraining(curTr);
				
				if(curTr.className.indexOf('header') != -1 & i!=0)
				{
					var headerTd = curTr.getElementsByTagName('td')[0];
					var showAll = document.createElement('a');
					showAll.href = "#";
					showAll.innerHTML = "(Klik her for at se hele ugen)";
					showAll.onclick = function()
					{
						var urlLocation = document.location + "";
						document.location = urlLocation.split('&day')[0];
					}
					headerTd.appendChild(showAll);
				}
			}
		}
	}
	

	
}

function checkForPopups()
{
	var links = document.getElementsByTagName('a');
	for(var i=0;i<links.length;i++)
	{
		var curLink = links[i];
		if(curLink.target == "popupPic")
		{
			curLink.onclick = function()
			{
				popup(this.href)
				//this.href = "";
				return false;
			}
		}
	}
}

function popup(url)
{
	var popupContainer = document.createElement('div');
	var popupShade = document.createElement('div');
	var thePic = document.createElement('img');
	var clickShade = document.createElement('div');
	var frontVideo = document.getElementById('frontVideo');
	
	if(frontVideo)frontVideo.style.visibility = "hidden";
	
	thePic.src = url;
	
	popupContainer.className = "popupContainer";
	popupShade.className = "popupShade";
	popupShade.id = "popupShade";
	clickShade.className = "clickShade";
	popupShade.style.display = "block";
	
	
	popupContainer.appendChild(popupShade);
	popupShade.appendChild(thePic);
	
	document.body.appendChild(popupContainer);
	document.body.appendChild(clickShade);
	
	
	thePic.onload = function()
	{
		vMiddle(popupShade);
	}
	
	clickShade.onclick = function()
	{
		popupShade.style.display = "none";
		this.style.display = "none";
		if(frontVideo)frontVideo.style.visibility = "visible";
	}
	
	setTimeout("vMiddle(document.getElementById('popupShade'))",500);
	setTimeout("vMiddle(document.getElementById('popupShade'))",1000);
	setTimeout("vMiddle(document.getElementById('popupShade'))",1500);
	
	
}


function vMiddle(theObject){

	var currentObject = theObject;

	var locWinY = document.documentElement.scrollTop;
	var locWinX = document.documentElement.scrollLeft;
	
	var dimWinY;
	var dimWinX;
	
	var dimDocY = document.body.offsetHeight;
	var dimDocX = document.body.offsetWidth;
	
	if(window.innerHeight)
	{
		   dimWinY = window.innerHeight;
		   dimWinX = window.innerWidth;
	}
	else
	{
		   dimWinY = document.documentElement.clientHeight;
		   dimWinX = document.documentElement.clientWidth;
	}
	
	var locIframeY = (dimWinY / 2) + locWinY - (currentObject.offsetHeight / 2);
	var locIframeX = (dimWinX / 2) + locWinX - (currentObject.offsetWidth / 2);
	
	currentObject.style.top = parseInt(locIframeY.toString()) + 'px';
	currentObject.style.left = parseInt(locIframeX.toString()) + 'px';
	

}




function step1(option)
{
	var step1true = document.getElementById('step1true'); 
	var step1false = document.getElementById('step1false'); 
	if(option)
	{
		step1true.style.display = "block";
		step1false.style.display = "none";
	}
	else
	{
		step1true.style.display = "none";
		step1false.style.display = "block";
	}
}

function checkInteressts()
{
	var interest = document.getElementById('interest');
	if(!interest)return false;
	
	var urlString = document.location + "";
	var choice = 0;
	var emailField = document.getElementById("email");
	var nameField = document.getElementById("name");
	var tak = document.getElementById("tak");
	
	if(urlString.indexOf("c=1") != -1) choice = 1;
	if(urlString.indexOf("c=2") != -1) choice = 2;
	if(urlString.indexOf("c=3") != -1) choice = 3;
	if(urlString.indexOf("c=4") != -1) choice = 4;
	
	if(urlString.indexOf("email") != -1)
	{
		var emailAddress = urlString.split("email=")[1].split("&")[0];
		emailField.value = unescape(emailAddress);
		tak.style.display = "block";
		ifmRequest("saveemail.php?e=" + emailAddress);
	}
	
	if(choice==0)return false;
	
	var choices = interest.getElementsByTagName('option');
	choices[choice - 1].selected = true;
	
	nameField.focus();
	
}

function searching()
{
	var searchInput = document.getElementById('searchInput');
	document.location = "soegning.php?s=" + searchInput.value;// + " site:theessenz.com";
}

function setEditableTables()
{
	//setTable('trainingProgramTable');
	setTable('personalTrainingProgramTable');
}


function setTable(tableId)
{
	var trainingProgramTable = document.getElementById(tableId);
	if(!trainingProgramTable)return false;
	
	var trs = trainingProgramTable.getElementsByTagName('tr');
	
	for(var i=0;i<trs.length;i++)
	{
		var curTr = trs[i];
		curTr.style.cursor = "pointer";
		curTr.onclick = function()
		{
			if(this.edit) return false;
			for(var i=0;i<trs.length;i++)
			{
				trs[i].className = "";
				trs[i].edit = false;
			}
			
			this.className = "edit";
			this.edit = true;
			var inputs = this.getElementsByTagName('input');
			for(var i=0;i<inputs.length;i++)
			{
				var curInput = inputs[i];
				var curSpan = curInput.parentNode.getElementsByTagName('span')[0];
				curInput.value = curSpan.innerHTML;
				
				curInput.onchange = function()
				{
					var theSpan = this.parentNode.getElementsByTagName('span')[0];
					save(this);
					showSaved(theSpan.parentNode);
					theSpan.innerHTML = this.value;
					this.parentNode.parentNode.className = "";
					this.parentNode.parentNode.edit = false;
				}
			}
		}
		curTr.ondblclick = function()
		{
			this.className = "";
			this.edit = false;
		}
	}
}

function showSaved(obj)
{
	obj.cnOrig = obj.className
	obj.className += " saved";
	if(obj.id == "")
		obj.id = "ranObj" + parseInt(Math.random() * 1000000);
	setTimeout("document.getElementById('" + obj.id + "').className = '" + obj.cnOrig + "'",1000);
}







function saveDietComment(obj)
{
	var txtToSave;
	var saveUrl = "savedietcomment.php";
	
 /* txtToSave = escape(obj.value); */
	var txtToSave = escape(obj.value);
	saveUrl += "?" + obj.id + "=" + txtToSave;
	ifmRequest(saveUrl);
	showSaved(obj);
	shout(saveUrl);
}




function save(obj)
{
	var txtToSave;
	var saveUrl = "savetraining.php";
	
	txtToSave = escape(obj.value);
	
	saveUrl += "?" + obj.id + "=" + txtToSave;
	ifmRequest(saveUrl);
	showSaved(obj);
	shout(saveUrl);
}





function goalChange(id)
{
	var curGoalTxt = document.getElementById('goalTxt' + id);
	var txtArea = curGoalTxt.getElementsByTagName('textarea')[0];
	var pTag = curGoalTxt.getElementsByTagName('p')[0];
	
	txtArea.style.height = pTag.offsetHeight + "px";
	
	txtArea.innerHTML = pTag.innerHTML;
	curGoalTxt.className = "edit";
		
	txtArea.focus();
	
}


function submitForm() {
	var email = document.getElementById('email');
	var newsLetterBefore = document.getElementById('newsLetterBefore');
	var newsLetterAfter = document.getElementById('newsLetterAfter');
	var emailHere = document.getElementById('emailHere');
	
	//document.location = "tilmeld.html?email=" + email.value + "&c=4";
	
	//chech if name and afd is filled out
	var saveUrl = "gemmeurl.php";
	
	saveUrl += "?email=" + email.value;

	ifmRequest(saveUrl);
	
	emailHere.innerHTML = email.value;
	newsLetterBefore.style.display = "none";
	newsLetterAfter.style.display = "block";
}


function preFields()
{
	var allInputs = document.getElementsByTagName("input");
	for(var i=0; i<allInputs.length;i++)
	{
		var curInput = allInputs[i];
		curInput.startTxt = curInput.value;
		curInput.onfocus = function()
		{
			if(this.type != "text")return false;
			if(this.getAttribute("password") == "true")this.type = "password";
			if(this.value == this.startTxt)
			{
				this.style.color = "#000";
				this.value = "";	
			}
		}
		curInput.onblur = function()
		{
			if(this.value == "")
			{
				this.style.color = "#777";
				this.value = this.startTxt;	
				if(this.getAttribute("password") == "true")this.type = "text";
			}
		}
	}
}




function setVings()
{
	var productOverview = document.getElementById('productOverview');
	if(!productOverview) return false;
	var tds = productOverview.getElementsByTagName('td');
	
	for(var i=0;i<tds.length;i++)
	{
		var curTd = tds[i];
		
		if(curTd.innerHTML == "x")
		{
			curTd.innerHTML = "<img src='graphic/ving.gif' />";
		}
		
	}
}


function callFrontPageTableMarker()
{
	markSecTds('productOverview', false);
}

function markSecTds(objId, foldOut)
{
	var curTable = document.getElementById(objId);
	if(!curTable) return false;
	var trs = curTable.getElementsByTagName('tr');
	var trToGet = new Array();
	var marker = false;
	var classToLookFor = "hide";
	if(foldOut)classToLookFor = "none";
	
	for(var i=0;i<trs.length;i++)
	{
		var curTr = trs[i];
		if(curTr.className.indexOf(classToLookFor) == -1)
			trToGet[trToGet.length] = curTr;
		
		curTr.className = curTr.className.replace(/sec/, "");
		
		/*if(curTr.className.indexOf('hide') == 1)
			curTr.className = curTr.className.replace(/hide/, "noHide");
			
		if(curTr.className.indexOf('noHide') == 1)
			curTr.className = curTr.className.replace(/noHide/, "hide");
		*/
	}
	
	
	
	for(var i=0;i<trToGet.length;i++)
	{
		var curTr = trToGet[i];
		if(marker)
		{
			curTr.className += " sec";
			marker = false;
		}
		else
			marker = true;
	}
}

var prodSplitters = false;
function prepShowMoreProductInfo()
{
	var productOverview = document.getElementById('productOverview');
	var showMoreLink = document.getElementById('showMoreLink');
	var productsDiv = document.getElementById('productsDiv');
	if(!productOverview) return false;
	if(!showMoreLink) return false;
	if(!productsDiv) return false;
	
	//find splitters
	var tablesInProdDiv = productsDiv.getElementsByTagName('table');
	prodSplitters = new Array();
	for(var i=0;i<tablesInProdDiv.length;i++)
	{
		var curTable = tablesInProdDiv[i];
		if(curTable.className == "splitter")
		{
			prodSplitters[prodSplitters.length] = curTable;
			curTable.style.height = curTable.offsetHeight + 40 + "px";
		}
	}
	
	var closedHeight = productsDiv.offsetHeight;
	showMoreLink.status = "small";
	
	showMoreLink.onclick = function()
	{
		if(showMoreLink.status == "small")
		{
			showMoreLink.className = "showLessLink showMoreLink";
			productsDiv.style.height = closedHeight + "px";
			productsDiv.style.overflow = "hidden";
			productOverview.className = "large";
			grow(productsDiv, productOverview.offsetHeight + 15);
			this.innerHTML = "Minimer oversigten";
			showMoreLink.status = "large";
			markSecTds('productOverview', true);
		}
		else
		{
			showMoreLink.className = "showMoreLink";
			//productsDiv.style.height = closedHeight + "px";
			productsDiv.style.overflow = "hidden";
			//productOverview.className = "small";
			schrimp(productsDiv, closedHeight);
			this.innerHTML = "Se hele oversigten her";
			showMoreLink.status = "small";
		}
		
		return false;
	}
}

function grow(obj, endHeight)
{
	if(!prodSplitters) prodSplitters = false;
	moveObj = obj;
	if(!obj.style.height)
	{
		obj.style.height = obj.offsetHeight + "px";
		document.title = obj.offsetHeight;
	}
		
	if(obj.offsetHeight < endHeight - 10)
	{
		var difToAdd = parseInt(endHeight - obj.offsetHeight)/ 10; 
		difToAdd = parseInt(difToAdd);
		obj.style.height = parseInt(obj.style.height) + difToAdd + "px";
		if(prodSplitters)
		{
			for(var i=0;i<prodSplitters.length;i++)
			{
				var curSplitter = prodSplitters[i];
				curSplitter.style.height = (parseInt(curSplitter.style.height) + difToAdd) + "px";
			}
		}
		setTimeout("grow(moveObj," + endHeight + ")", 10);
	}
	else
	{
		markSecTds('productOverview', true);	
	}
}

function schrimp(obj, endHeight)
{
	moveObj = obj;
	if(obj.offsetHeight > endHeight + 10)
	{
		var difToRemove = parseInt(obj.offsetHeight - endHeight)/ 10; 
		obj.style.height = parseInt(obj.style.height) - parseInt(difToRemove) + "px";
		for(var i=0;i<prodSplitters.length;i++)
		{
			var curSplitter = prodSplitters[i];
			curSplitter.style.height = (parseInt(curSplitter.style.height) - difToRemove) + "px";
		}
		setTimeout("schrimp(moveObj," + endHeight + ")", 10);
	}
	else
	{
		markSecTds('productOverview', false);
		
		if(obj.className == "productsDiv")
		{
			var productOverview = document.getElementById('productOverview');
			productOverview.className = "small";
		}
			
	}
}


function shout(message) {
	document.title = message;	
}

function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}

function ifmRequest(url) {
	var ifm = document.createElement("iframe");
	ifm.src = url;
	ifm.className = "hiddenIframe";
	document.body.appendChild(ifm);	
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if(typeof window.onload != 'function')
	{
		window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			oldonload();
			func();
		}
	}
}


var date_seperator = '-';
var decimal_seperator = ',';
var thousand_seperator = '.';
	var K_Validate = {
		Version: '1.0.0',
		Load: function(){
			var children = document.getElementsByTagName('input');
			for (var i = 0; i < children.length; i++) {
				var classNames = children[i].className.split(' ');
					
					if (children[i].className.match(new RegExp("(^|\\s)validatenum(\\s|$)"))) {
						this.addInListener(children[i],'keypress',K_Validate.checkNum);
						
						if (children[i].className.match(new RegExp("(^|\\s)thousand(\\s|$)"))) {
							this.addInListener(children[i],'focus',K_Validate.normalFormat);
							this.addInListener(children[i],'blur',K_Validate.formatThousand);
						}
					
					}
					if (children[i].className.match(new RegExp("(^|\\s)validatedate(\\s|$)"))) {
							this.addInListener(children[i],'keypress',K_Validate.checkDate);
							this.addInListener(children[i],'blur',K_Validate.isDate);
							children[i].maxlength=10;
						}					
		
			}
		},
		addInListener : function (a,b,c){
			a["on"+b]=c
		},
		
		isNumeric: function(ch) {
			if (!(ch >= '0' && ch <= '9')) {
				return false;
			}
		return true;
		},
		
		elo : function (e){
			if (!e) var e = window.event;
			var eid = (window.event) ? e.srcElement : e.target;
			if(!eid) return false;
			return eid;
		},
	
		checkNum: function (e,not_dec,not_minus) {
			if(!e) e = window.event;
			if(window.event){
				keynum = e.keyCode
			}else if(e.which){
				keynum = e.which
			}	
			if (K_Validate.elo(e).className.match(new RegExp("(^|\\s)nominus(\\s|$)"))) not_minus = true;
			if (K_Validate.elo(e).className.match(new RegExp("(^|\\s)nodecimal(\\s|$)"))) not_dec = true;
			if (!not_minus) not_minus = false;
			if (!not_dec) not_dec = false;
			var obj = (window.event) ? e.srcElement: e.target;

			var keychar;
			if (keynum == null) return true;
			goods = '0123456789';
			decimal_used = (obj.value.indexOf(decimal_seperator) != -1) ? true:false;
			minus_used = (obj.value.indexOf('-') != -1) ? true:false;

			if(!not_dec && !decimal_used) goods = goods+decimal_seperator;
			keychar = String.fromCharCode(keynum);
			keychar = keychar.toLowerCase();
			goods = goods.toLowerCase();
			var curr_pos = K_Validate.insertAtCursor(obj);
			if(!not_minus && curr_pos<1 && !minus_used) goods = goods+'-';

			if (goods.indexOf(keychar) != -1)
				return true;

			if ( keynum==null || keynum==0 || keynum==8 || keynum==9 || keynum==13 || keynum==27 )
				return true;

			return false;
		},
		
		insertAtCursor : function (obj) {
			if (document.selection) {
			sel=document.selection;
				if(sel)
				{
					r2=sel.createRange();
					rng=obj.createTextRange();
					rng.setEndPoint("EndToStart", r2);
					i=rng.text.length;
				}
				return i;
			}else if (obj.selectionStart || obj.selectionStart == '0') {
				return obj.selectionStart;
			}
		},
		
		
		
		formatThousand : function (e) {
			if(!e) e = window.event;
			obj = K_Validate.elo(e);
			formattedNbr="";
			if (obj.value.match(new RegExp(/-/))){
				var minus=true;
				obj.value = obj.value.replace("-","");
			}
			var temp_val	=	obj.value.split(decimal_seperator);
			len = temp_val[0].length;
			for (i=len-1, k=1 ; i>=0; i = i-1,k++ )  {
				if (((k % 3)	== 0) && (k != len))
					formattedNbr = thousand_seperator + temp_val[0].charAt(i) + formattedNbr;
				else
					formattedNbr = temp_val[0].charAt(i) + formattedNbr;
			}
			formattedNbr = (minus)?'-'+formattedNbr:formattedNbr;
			if(temp_val[1]){
				obj.value = formattedNbr+decimal_seperator+temp_val[1];
			}else{
				obj.value = formattedNbr;
			}
		},

		normalFormat : function(e)	{
			if(!e) e = window.event;
			obj = K_Validate.elo(e);
			tempText= new String();
			text = obj.value;
			if (text=="") { 
				return false;
			}
			len = text.length;
			for(i=0; i < len; ++i) {
				ch = text.charAt(i);
				if ((ch >= '0' && ch <= '9') || ch==decimal_seperator || ch=='-') {
					tempText+=ch;
				}
			}
			obj.value=tempText;
			return true;
		},
		
		checkDate : function (e){
			if(!e) e = window.event;
			var obj = (window.event) ? e.srcElement: e.target;
			if(window.event) // IE
			{
				keynum = e.keyCode
			}else if(e.which) {
				keynum = e.which
			}
			goods = '0123456789';
			keychar = String.fromCharCode(keynum);
			keychar = keychar.toLowerCase();
			var curr_pos = K_Validate.insertAtCursor(obj);
			if (goods.indexOf(keychar) != -1){
				if(curr_pos==2 && obj.value.charAt(2)!=date_seperator && obj.value.length<3){
					obj.value = obj.value+date_seperator;
					curr_pos++;
				}
				if(curr_pos==5 && obj.value.charAt(4)!=date_seperator && obj.value.length<6){
					obj.value = obj.value+date_seperator;
					curr_pos++;
				}
			return true;

			}
			if(keychar==date_seperator && (curr_pos==5 || curr_pos==2))
				return true;

			if ( keynum==null || keynum==0 || keynum==8 || keynum==9 || keynum==13 || keynum==27 )
				return true;

			return false;
		},
		
		getDateFromFormat : function (val,format){
			val=val+"";
			format=format+"";
			var i_val=0;
			var i_format=0;
			var c="";
			var token="";
			var token2="";
			var x,y;
			var now=new Date();
			var year=now.getYear();
			var month=now.getMonth()+1;
			var date=1;
			var hh=now.getHours();
			var mm=now.getMinutes();
			var ss=now.getSeconds();
			var ampm="";
			while(i_format < format.length){
				c=format.charAt(i_format);
				token="";
				while((format.charAt(i_format)==c) &&(i_format < format.length)){
					token += format.charAt(i_format++);
				}
				if(token=="yyyy" || token=="yy" || token=="y"){
					if(token=="yyyy"){x=4;y=4;}
					if(token=="yy"){x=2;y=2;}
					if(token=="y"){x=2;y=4;}
					year=K_Validate._getInt(val,i_val,x,y);
					if(year==null){return 0;}
					i_val += year.length;
					if(year.length==2){
						if(year > 70){
							year=1900+(year-0);
						}else{
							year=2000+(year-0);
						}
					}
				}else if(token=="MMM"||token=="NNN"){
					month=0;
					for(var i=0;i<MONTH_NAMES.length;i++){
						var month_name=MONTH_NAMES[i];
						if(val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()){
							if(token=="MMM"||(token=="NNN"&&i>11)){
								month=i+1;
								if(month>12){month -= 12;}
								i_val += month_name.length;
								break;
							}
						}
					}
				
					if((month < 1)||(month>12)){return 0;}
				}else if(token=="EE"||token=="E"){
					for(var i=0;i<DAY_NAMES.length;i++){
						var day_name=DAY_NAMES[i];
						if(val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()){
							i_val += day_name.length;
							break;
						}
					}
				}else if(token=="MM"||token=="M"){
					month=K_Validate._getInt(val,i_val,token.length,2);
					if(month==null||(month<1)||(month>12)){return 0;}
					i_val+=month.length;
				}else if(token=="dd"||token=="d"){
					date=K_Validate._getInt(val,i_val,token.length,2);
					if(date==null||(date<1)||(date>31)){return 0;}
					i_val+=date.length;
				}else if(token=="hh"||token=="h"){
					hh=K_Validate._getInt(val,i_val,token.length,2);
					if(hh==null||(hh<1)||(hh>12)){return 0;}
					i_val+=hh.length;
				}else if(token=="HH"||token=="H"){
					hh=K_Validate._getInt(val,i_val,token.length,2);
					if(hh==null||(hh<0)||(hh>23)){return 0;}
					i_val+=hh.length;
				}else if(token=="KK"||token=="K"){
					hh=K_Validate._getInt(val,i_val,token.length,2);
					if(hh==null||(hh<0)||(hh>11)){return 0;}
					i_val+=hh.length;
				}else if(token=="kk"||token=="k"){
					hh=K_Validate._getInt(val,i_val,token.length,2);
					if(hh==null||(hh<1)||(hh>24)){return 0;}
					i_val+=hh.length;hh--;
				}else if(token=="mm"||token=="m"){
					mm=K_Validate._getInt(val,i_val,token.length,2);
					if(mm==null||(mm<0)||(mm>59)){return 0;}
					i_val+=mm.length;
				}else if(token=="ss"||token=="s"){
					ss=K_Validate._getInt(val,i_val,token.length,2);
					if(ss==null||(ss<0)||(ss>59)){return 0;}
					i_val+=ss.length;
				}else if(token=="a"){
					if(val.substring(i_val,i_val+2).toLowerCase()=="am"){
						ampm="AM";
					}else if(val.substring(i_val,i_val+2).toLowerCase()=="pm"){
						ampm="PM";
					}else{return 0;}
					i_val+=2;
				}else{
					if(val.substring(i_val,i_val+token.length)!=token){
						return 0;
					}else{
						i_val+=token.length;
					}
				}
			}
			if(i_val != val.length){return 0;}
			if(month==2){
				if( ((year%4==0)&&(year%100 != 0) ) ||(year%400==0) ){
					if(date > 29){return 0;}
				}else{
					if(date > 28){return 0;}
				}
			}
			if((month==4)||(month==6)||(month==9)||(month==11)){
				if(date > 30){return 0;}
			}
			if(hh<12 && ampm=="PM"){
				hh=hh-0+12;
			}else if(hh>11 && ampm=="AM"){
				hh-=12;
			}
			var newdate=new Date(year,month-1,date,hh,mm,ss);
			return newdate.getTime();
		},
		
		
	isDate : function (e){
		if(!e) e = window.event;
		obj = K_Validate.elo(e);
		var val = obj.value;
		var date=K_Validate.getDateFromFormat(val,"dd-MM-y");
		if(date==0){
			obj.style.color="#ff0000";
		}else{
			obj.style.color="#000000";
		}
	},
	
	
	_isInteger : function (val){
		var digits="1234567890";
		for(var i=0;i < val.length;i++){if(digits.indexOf(val.charAt(i))==-1){return false;}}return true;
	},



	_getInt : function (str,i,minlength,maxlength){
	for(var x=maxlength;x>=minlength;x--){
		var token=str.substring(i,i+x);
			if(token.length < minlength){
				return null;
				}
			if(K_Validate._isInteger(token)){
				return token;
				}
		}
	return null;
	}
	}
	
	
	
	
	function activateNewsLetter()
	{
		$("#newsletterBubble").fadeIn();
		$("#newsletterEmail").focus();
		
	}
	
	function submitEmail()
	{
		var email = document.getElementById('newsletterEmail').value;
		var saveUrl = "gemmeurl.php";
		
		saveUrl += "?email=" + email;
	
		ifmRequest(saveUrl);
		
		$("#newsletterBubble").fadeOut();
	}
	
	function addEmail()
	{
		var email = document.getElementById('rightSideEmail').value;
		var saveUrl = "gemmeurl.php";
		
		saveUrl += "?email=" + email;
	
		ifmRequest(saveUrl);
		
		$("#secEmailNewsletter").slideUp();
		$("#secEmailNewsletterAdded").slideDown();
		
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
