/*
 Copyright: Futurice
*/

	// Array that holds all divs (Training).
    var other = new Array();
    var otherplace = 0;
    var unitTypes = new Array();
	var portions = new Array();

    /*
    Clear input-field

    */
    function clearInput(name) {
    	var obj = dojo.byId(name);
    	obj.value = '';
    }
    /*
     Hide or close div.
    */
    function showHide(name) {
		var element = dijit.byId(name);
		closeOther(name);

		try{

			if (closed(name)) {
				element.domNode.style.display = "block";
			} else {
				element.domNode.style.display = "none";
			}
		}catch (e){ }
    }

    /*
     Hide or show div.
    */
    function toggleDiv(id) {
		var element = document.getElementById(id);
		if (element != null)
		{
			if (element.style.display == "none") {
				element.style.display = "block";
			} else {
				element.style.display = "none";
			}
		}
    }

    function toggleSpan(id) {
		var element = document.getElementById(id);
		if (element.style.display == "none") {
			element.style.display = "inline";
		} else {
			element.style.display = "none";
		}
    }

	/*
	Toggle style.
	*/
	function toggleClass(obj) {
		var el = document.getElementById(obj);

		if (el != null)
		{
			if ( el.className != 'trainingHeader open' ) {
				el.className = 'trainingHeader open';
			}
			else {
				el.className = 'trainingHeader';
			}
		}
	}


    /*
     Close all divs.
    */
    function closeOther(current) {
		for (i=0;i<other.length;i++) {
		  var text = other[i];
		  if (text != current) {
		  	dijit.byId(text).domNode.style.display = "none";
		  }
		}
	}

	/*
	 Test if div is closed.
	 Returns true if closed, else false;
	*/
	function closed(divName){

	  try{

		  if(dijit.byId(divName).domNode.style.display == "none") {
		  	return true;
		  } else {
		  	return false;
		  }

	  }catch (e){ return false; }
    }

	 /*
	  Get data from server and update div. Use dojo.byId
	 */

	function getxhr(action, divName, scriptTillEND) {

		if (action.indexOf('?') == -1)
		{
			action = action + '?' + new Date().getTime();
		}
		else
		{
			action = action + '&' + new Date().getTime();
		}

		dojo.xhrGet( {

			url: ""+action,
			handleAs: "text",
			timeout:10000,
			load: function (response,ioArgs) {

				if (scriptTillEND != null && scriptTillEND == true)
                {
                  	var index = response.indexOf('SCRIPTEND');
                  	if (index != -1)
	                {
	                  	var script = response.substring(0, index);
	                  	response = response.substring(index + 'SCRIPTEND'.length);

	                  	try{eval(script);}catch (e){}
                  	}
                }

				try{
					eval(response);
				}catch (e){}

			  if (divName != '') {
				var obj = dojo.byId(divName);

	            obj.innerHTML = response;
	            dojo.parser.parse(obj);
	          }
			},
			error:function(response,ioArgs){
		         console.error("HTTP status code: ", ioArgs.xhr.status);
		         return response;
			}
		  }
		);
	  }

	function deleteEntry(action, divNameToRemove)
	{
		var ok = confirm("Oletko varma, että haluat poistaa?");
		if (ok != true) return;

		if (action.indexOf('?') == -1)
		{
			action = action + '?' + new Date().getTime();
		}
		else
		{
			action = action + '&' + new Date().getTime();
		}

		dojo.xhrGet( {

			url: ""+action,
			handleAs: "text",
			timeout:10000,
			load: function (response,ioArgs) {

				try{
					eval(response);
				}catch (e){}

			  if (divNameToRemove != '') {
				var obj = document.getElementById(divNameToRemove);
				obj.parentNode.removeChild(obj);
	          }
			},
			error:function(response,ioArgs){
		         console.error("HTTP status code: ", ioArgs.xhr.status);
		         return response;
			}
		  }
		);
	}

	/*
	 Get data from server and update div. User dijit.byId
	*/
	function getDijitXhr(action, divName, divToToggleAfterLoad, scriptAtFirstLine, scriptTillEND) {

		if (action.indexOf('?') == -1)
		{
			action = action + '?' + new Date().getTime();
		}
		else
		{
			action = action + '&' + new Date().getTime();
		}

		dojo.xhrGet( {
		url: ""+action,
		handleAs: "text",
		timeout:10000,
		load: function (response,ioArgs) {

				if (scriptAtFirstLine != null && scriptAtFirstLine == true)
                {
                  	var index = response.indexOf('\n');
                  	var script = response.substring(0, index);
                  	response = response.substring(index + 1);
                  	try{eval(script);}catch (e){}
                }

                if (scriptTillEND != null && scriptTillEND == true)
                {
                  	var index = response.indexOf('SCRIPTEND');
                  	if (index != -1)
	                {
	                  	var script = response.substring(0, index);
	                  	response = response.substring(index + 'SCRIPTEND'.length);

	                  	try{eval(script);}catch (e){}
                  	}
                }

                try{
					eval(response);
				}catch (e){}

				if(divName != '') {
		            var obj = dijit.byId(divName);
		            obj.setContent(response);
	            }
	            if (divToToggleAfterLoad != null && divToToggleAfterLoad != '')
	            	toggleDiv(divToToggleAfterLoad);
		},
		error:function(response,ioArgs){
	         console.error("HTTP status code: ", ioArgs.xhr.status);
	         return response;
		}});}


	/*
	 Post data to server and update div with response.
	 option: dojo.xhrGet(kw);  //Servlet get with doGet
	 Uses dojo.byId-function

	*/
	function postxhr(action, divName, formName) {
		var kw = {
		        url: ""+action,
				handleAs:"text",
		        load: function(response){

		        try{
					eval(response);
				}catch (e){}

	              if (divName != '') {
		            dojo.byId(divName).innerHTML = response;
                  }
		        },
				error:function(response,ioArgs){
		          console.error("HTTP status code: ", ioArgs.xhr.status);
		          return response;
		         },
		        timeout: 10000,
		        form: formName
		        };
			dojo.xhrPost(kw);  //Servlet get with doPost
	 }

	 function postxhrAndUpdateUser(action, divName, formName) {
		var kw = {
		        url: ""+action,
				handleAs:"text",
		        load: function(response){

		          try{
					eval(response);
				  }catch (e){}

	              if (divName != '') {
		            dojo.byId(divName).innerHTML = response;
                  }
                  updateUser();
				  window.location = 'mypage.action';
		        },
				error:function(response,ioArgs){
		          console.error("HTTP status code: ", ioArgs.xhr.status);
		          return response;
		         },
		        timeout: 10000,
		        form: formName
		        };
			dojo.xhrPost(kw);  //Servlet get with doPost
	 }

	 function updateUser()
	 {
	 	getDijitXhr('getinformation.action', '', '', true);
	 }


	/*
	  This function has same functionality as postxhr, but it uses dijit.byId. This function is mainly used
	  in personal training -page when users adds his own entry.
	  action = url
	  divName = What form will be updated
	  formName = Send this form with data.
	  javascriptAtFirstLine = hack to execute script at the firs line of response
	*/
		function postDijitXhr(action, divName, formName, scriptAtFirstLine, responseIsScript, scriptTillEND) {
		var kw = {
		        url: ""+action,
				handleAs:"text",
		        load: function(response){

		        if (responseIsScript != null && responseIsScript == true)
                {
                	try{eval(response);}catch (e){}
                	return;
                }


		          if (scriptAtFirstLine != null && scriptAtFirstLine == true)
                  {
                  	var index = response.indexOf('\n');
                  	var script = response.substring(0, index);
                  	response = response.substring(index + 1);

                  	try{eval(script);}catch (e){}
                  }

                  if (scriptTillEND != null && scriptTillEND == true)
	                {
	                  	var index = response.indexOf('SCRIPTEND');
	                  	if (index != -1)
	                  	{
	                  		var script = response.substring(0, index);
	                  		response = response.substring(index + 'SCRIPTEND'.length);

	                  		try{eval(script);}catch (e){}
	                  	}
	                }

                  try{
					eval(response);
				  }catch (e){}

	              if (divName != '') {
		            var obj = dojo.byId(divName);
		            obj.innerHTML = response;
		            dojo.parser.parse(obj);
                  }
		        },
				error:function(response,ioArgs){
		          console.error("HTTP status code: ", ioArgs.xhr.status);
		          return response;
		         },
		        timeout: 10000,
		        form: formName
		        };
			dojo.xhrPost(kw);  //Servlet get with doPost
	 }

	 /*
	  Method loads data from server when div is closed. If div is open, don't load anything.(I a case where user
	  closes open div).
	 */
	 function getTestXhr(action, divName, scriptAtFirstLine) {

	 	/*
	 	if(closed(divName)) {
	 		getxhr(action, divName);
	 	}
	 	*/

	 	//refresh always the div -ssaa
	 	getxhr(action, divName, scriptAtFirstLine);
	 }

	/**
	  Javascript validation for input-fields that can only accept numbers.

	*/
	function number(e)
	{
		var keynum;
		var keychar;
		var numcheck;

		if(window.event) // IE
        {
		  keynum = e.keyCode;
		}
		else if(e.which) // Netscape/Firefox/Opera
		{
		  keynum = e.which;
		}

		var evt = e || window.event;
		keyCode = evt.keyCode;
		if (keyCode == 8 || keyCode == 9 || keyCode == 46 || keynum == 44)
		{
			//allow backspace, tab and del
			return true;
		}

		if (keynum == undefined || keynum == 8 || keynum == 9 || keynum == 46 || keynum == 44)
		{
			//allow backspace, tab and del
			return true;
		}

		keychar = String.fromCharCode(keynum);

		return !isNaN(keychar);
	}

	/**
	 Modify program text: Julkinen / Yksityinen
	*/
	function modifytext(objName, text){
		var obj = dojo.byId(objName);
		obj.innerHTML = text;
	}

	/**
		Opens selected video in the video div
	*/
	function openVideo(articleid, videoid)
	{
		getxhr('videoArticle.action?main=' + articleid, 'videoArticle');
		loadVideo(videoid);
	}

	/**
		Opens selected video list in the videolist div
	*/
	function openVideoList(videolistid)
	{
		getxhr('videolist.action?right=' + videolistid, 'videolist');
	}

	/*
	  change elements class: Used in exercise marking.
	*/

	function changeState(element, elemId) {
		if (element.className == 'exercisetrue') {
			element.className = 'exercisefalse';
			getxhr('changeexercise.action?id='+elemId+'&visibility=false', '');
		} else {
			element.className = 'exercisetrue';
			getxhr('changeexercise.action?id='+elemId+'&visibility=true', '');
		}
	}

	/**
		confirmation message to delete avatar
	*/
	function confirmDeleteAvatar(userid, message)
	{
		var ok = confirm(message);
		if (ok== true)
		{
		    window.location="deleteUserAvatar.action?entity.id=" + userid;
		}
		else
		{
			return false;
		}
	}

	/**
		confirmation message to delete avatar
	*/
	function confirmDeleteProgram(programid, message)
	{
		var ok = confirm(message);
		if (ok== true)
		{
		    window.location="deleteProgram.action?deleteid=" + programid;
		}
		else
		{
			return;
		}
	}

	/**
		Selects/deselects all the checkboxes in the form
	*/
	function selectAll(selected) {
	    var checkboxCount = 0;
	    for(f=0;f<document.forms.length;f++)
	    for(i=0;i<document.forms[f].elements.length;i++) {
	        if(document.forms[f].elements[i].type=='checkbox') {

		        if (selected)
		        {
		        	document.forms[f].elements[i].checked='checked';
		        }
		        else
		        {
		        	document.forms[f].elements[i].checked='';
		        }
	        }
	    }
	    return;
	}

	/**
		opens the url in a popup
	*/
	function openInPopup(url, w, h)
	{
		if (w == null) w = 700;
		if (h == null) h = 700;

	    newwindow = window.open(url,'Elixir','height=' + h + ',width=' + w + ',scrollbars=1,resizable=1');
		if (window.focus) { newwindow.focus() }
	}

	function buyTime()
	{
		toggleDiv('persondiv');
		toggleDiv('buytimediv');
	}

	function showLink(id)
	{
		dijit.showTooltip('<div style = "padding : 5px">Linkki liikuntap&#xE4;iv&#xE4;kirjaan:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
		'<a href = "javascript:dijit.hideTooltip(dojo.byId(\'linktothis\'))">Sulje</a><br/>' +
		'<input size = "50" type = "text" value = "http://www.elixir.fi/showPublicProgram.action?programInstanceID=' + id + '"></input></div>', dojo.byId('linktothis'))
	}

	function continueRegistration(type) {
		if (type != 'friend' && !document.getElementById('accept').checked) {
			document.getElementById('accepterror').style.display = "block";
			return false;
		}
			
		return true;
	}

	function closeRegister()
	{
		try {
			dijit.byId('campaignRegisterDialog').hide();
		} catch (e) {}
		try {
			dijit.byId('registerDialog').hide();
		} catch (e) {}
	}

	function updateExerciseTitle(id, content)
	{
		document.getElementById('title_' + id).innerHTML = content;
	}

	function openRegister(preselectedIndex)
	{
		if(dijit.byId('registerDialog').isLoaded)
		{
			document.getElementsByName('subscriptionTypeId')[preselectedIndex - 1].checked = 'true';
		}

		dijit.byId('registerDialog').href = 'registerUserForm.action?selected=' + preselectedIndex;
		dijit.byId('registerDialog').show();
	}

function validatePerformanceEntry(randomid) {
	if (dojo.byId('entity.exerciseInstance.description_' + randomid).value.length < 1) {
		alert("Syötä otsikko");
		return false;
	}

	if (dojo.byId('entity.trainingDistance_' + randomid).value.length < 1) {
		alert("Syötä harjoitusmatka");
		return false;
	}

	if (dojo.byId('entity.trainingTime_' + randomid).value.length < 1) {
		alert("Syötä harjoitusaika");
		return false;
	}

	if (dojo.byId('entity.hbMin_' + randomid).value.length < 1) {
		alert("Syötä min");
		return false;
	}

	if (dojo.byId('entity.hbAvg_' + randomid).value.length < 1) {
		alert("Syötä keskiarvo");
		return false;
	}

	if (dojo.byId('entity.hbMax_' + randomid).value.length < 1) {
		alert("Syötä max");
		return false;
	}

	if (dojo.byId('entity.kCalories_' + randomid).value.length < 1) {
		alert("Syötä Kcal");
		return false;
	}

	return true;
}

function sendCode() {
	len = document.registerNewUser.subscriptionTypeId.length;

    if (dojo.byId('discountCode').value != "") {
	    for (i = 0; i <len; i++) {
	        document.registerNewUser.subscriptionTypeId[i].checked = false;
	    }
        postxhr('registerListSubscriptionTypes.action?discountCode=' + dojo.byId('discountCode').value, 'subscriptionTypes', '')
        document.getElementById('subscriptionTypes').style.visibility = 'visible';
    } else {
        document.getElementById('subscriptionTypes').style.visibility = 'hidden';

    }
}
// Quick fix.
function sendCodeMoreTime() {
    len = document.buytimeExpired.subscriptionTypeId.length;

    // hack
    if (dojo.byId('discountCode').value != "") {
	    for (i = 0; i <len; i++) {
	        document.buytimeExpired.subscriptionTypeId[i].checked = false;
	    }
        postxhr('registerListSubscriptionTypes.action?discountCode=' + dojo.byId('discountCode').value, 'subscriptionTypes', '')
        document.getElementById('subscriptionTypes').style.visibility = 'visible';
    } else {
    	document.getElementById('subscriptionTypes').style.visibility = 'hidden';

    }
}
function showUserAgreement()
{
	toggleDiv('campaignRegisterDiv');
	toggleDiv('registerDiv');
	toggleDiv('userAgreement');
}

/**
 * Used in listForumMessages.tag
 */
function forumNoticeForAnonymous() {
	alert('Täällä Elixir-yhteisön jäsenet vaihtavat ajatuksia liikunnasta, eri lajeista sekä muista hyvinvointiin '
		+ 'liittyvistä aiheista. Liittymällä jäseneksi pääset osallistumaan keskusteluun ja saat myös käyttöösi '
		+ 'kaiken Elixir.fi-palvelun sisällön!');
}

function changeTab(tabGroup, tabNr) {
	if (tabNr == 1) {
		dojo.query('#' + tabGroup + '_contentHolder2').style('display', 'none');
		dojo.query('#' + tabGroup + '_tab2').removeClass('selectedTab');
		dojo.query('#' + tabGroup + '_contentHolder3').style('display', 'none');
		dojo.query('#' + tabGroup + '_tab3').removeClass('selectedTab');
		dojo.query('#' + tabGroup + '_contentHolder1').style('display', 'block');
		dojo.query('#' + tabGroup + '_tab1').addClass('selectedTab');
	}
	else if (tabNr == 2) {
		dojo.query('#' + tabGroup + '_contentHolder2').style('display', 'block');
		dojo.query('#' + tabGroup + '_tab2').addClass('selectedTab');
		dojo.query('#' + tabGroup + '_contentHolder1').style('display', 'none');
		dojo.query('#' + tabGroup + '_tab1').removeClass('selectedTab');
		dojo.query('#' + tabGroup + '_contentHolder3').style('display', 'none');
		dojo.query('#' + tabGroup + '_tab3').removeClass('selectedTab');
	}	else {
		dojo.query('#' + tabGroup + '_contentHolder1').style('display', 'none');
		dojo.query('#' + tabGroup + '_tab1').removeClass('selectedTab');
		dojo.query('#' + tabGroup + '_contentHolder2').style('display', 'none');
		dojo.query('#' + tabGroup + '_tab2').removeClass('selectedTab');
		dojo.query('#' + tabGroup + '_contentHolder3').style('display', 'block');
		dojo.query('#' + tabGroup + '_tab3').addClass('selectedTab');
	}
}

function acceptTerms() {
	if (! dojo.byId('acceptTermsCheckbox').checked) {
		alert("Et voi käyttää palvelua ennen käyttöehtojen hyväksymistä");
		return false;
	}
}

function fixDialog(id) {
	dialog = dijit.byId(id);
	// alert(dialog);

	dialog._position = function() {
		// summary: position modal dialog in center of screen

		if (dojo.hasClass(dojo.body(),"dojoMove")) { return; }
		var viewport = dijit.getViewport();
		var mb = dojo.marginBox(this.domNode);

		var style = this.domNode.style;
		style.left = "100px";
		//style.left = Math.floor((viewport.l + (viewport.w - mb.w)/2)) + "px";

		var topTemp = Math.floor((viewport.t + (viewport.h - mb.h)/2));
		if (topTemp < 150) {
			topTemp = 150;
		}

		style.top = topTemp + "px";
	}

	dialog.origShow = dialog.show;
	dialog.show = function() {
		this.origShow();

		if (this._scrollConnected) {
			this._scrollConnected = false;
		}

		//alert(this._modalconnects);
		dojo.forEach(this._modalconnects, dojo.disconnect);
		this._modalconnects = [];

		this.domNode.style.top = '100px';
	}
}
