
// function used in search higlightning
function findAndReplace(searchText, replacement, searchNode) {

	if (!searchText || typeof replacement === 'undefined') {
	    return;
	}
	
	searchWords = searchText.split(" ");
	var i = 0;
	for(i = 0; i < searchWords.length; i++){
		highlightWord(searchWords[i],replacement,searchNode );
	}
}

function highlightWord(searchText,replacement ,searchNode){
	
		var regex = typeof searchText === 'string' ? new RegExp('(' + searchText+')', 'gi') : searchText,
		    childNodes = (searchNode || document.body).childNodes,
		    cnLength = childNodes.length,
		    excludes = 'html,head,style,title,meta,script,object,iframe';
		    
		while (cnLength--) {
		    var currentNode = childNodes[cnLength];
		    if (currentNode.nodeType === 1 &&
		        (excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
		        arguments.callee(searchText, replacement, currentNode);
		    }
		    if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
		        continue;
		    }
		    var parent = currentNode.parentNode,
		        frag = (function(){
		            var html = currentNode.data.replace(regex, "<span style=\"background-color: yellow;\">$1</span>"),
		                wrap = document.createElement('div'),
		                frag = document.createDocumentFragment();
		            wrap.innerHTML = html;
		            while (wrap.firstChild) {
		                frag.appendChild(wrap.firstChild);
		            }
		            return frag;
		        })();
		    parent.insertBefore(frag, currentNode);
		    parent.removeChild(currentNode);
		}
	}



// function to restrict characters in input field to digits. Used in credit card deposit, file /templates/html-forms/deposits/credit-cards-ajax.xsl
function restrictCharacters(obj, e) {
    
  regExpr = /[^0-9]/;
  
  if (!e) var e = window.event
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);

// allow extra keys like backspace = 8 and back arrow = 37 etc. but not alt togehter with ctrl
  if ((!e.ctrlKey || e.altKey) && code!=9 && code!=8 && code!=37 && code!=39 ) {
   if(character.search(regExpr) == -1) {
    }
    else {
        return false;
    }
  }
}

//the following to functions lets javascript communicate with the spotviewer component [AndSan]
function getContainer(swfName) {
  if (navigator.appName.indexOf("Microsoft") != -1) {
    return window[swfName];
  } else {
    return document[swfName];
  }
}
var spotloaderCallInterval;
var intCounter = 0;
function initSpotViewer() {
       spotloaderCallInterval = setInterval("callAS()",500);
}
function callAS() {
      intCounter++;
     if(getContainer('sotester').sendToActionScript() || intCounter > 10)
      clearInterval(spotloaderCallInterval);
}

//function to show tooltips [AndSan]
function showToolTip(e){
              var parentFound = false;
              
              if(document.attachEvent){  //ie
                var evTarget = e.srcElement;
                //climb upwards in node tree to find the a tag
                while(!parentFound) {
                  if(evTarget.tagName == 'A') {
                    parentFound = true;
                    var note = evTarget.getElementsByTagName('div')[0];
                  } else {
                    evTarget = evTarget.parentNode; 
                  }
                }
                //check if event target is inner element of tooltip link or link itself. If former, reference the parent element
                //var note = e.srcElement.src ? e.srcElement.parentNode.getElementsByTagName('div')[0] : e.srcElement.getElementsByTagName('div')[0];
                
              } else {//mozilla
                var evTarget = e.target;
                //climb upwards in node tree to find the a tag
                while(!parentFound) {
                  if(evTarget.tagName == 'A') {
                    parentFound = true;
                    var note = evTarget.getElementsByTagName('div')[0];
                  } else {
                    evTarget = evTarget.parentNode; 
                  }
                }
              }
                
                note.style.display = 'block';
                note.style.zIndex='3000';

                //calculate page measurements and pointer position (ie : mozilla)
                var winWidth = note.attachEvent ? document.body.offsetWidth : (window.innerWidth + window.pageXOffset);
                var winHeight = note.attachEvent ? (document.documentElement.clientHeight + document.documentElement.scrollTop) : (window.innerHeight + window.pageYOffset);
                var pointerPosX = note.attachEvent ? (e.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft) : e.pageX;
                var pointerPosY = note.attachEvent ? (e.clientY + document.documentElement.scrollTop - document.documentElement.clientTop) : e.pageY;
                
                //get tooltip width and height
                var tooltipWidth = note.offsetWidth;
                var tooltipHeight = note.offsetHeight;
                          
                //place tooltip div in relation to pointer based on links placement on side, ie. move tooltip up or to sides if viewing space is too small
                if((winHeight - pointerPosY) < tooltipHeight)
                  var heightOffset = tooltipHeight - (winHeight - pointerPosY);
                else
                  var heightOffset = -20;
                            
                if((winWidth - pointerPosX) < tooltipWidth)
                  var widthOffset = (tooltipWidth - (winWidth - pointerPosX)) +30;
                else
                  var widthOffset = -20;
                            
                note.style.left= pointerPosX - widthOffset +'px';
                note.style.top= pointerPosY - heightOffset +'px';
}

function hideToolTip(e){
              var parentFound = false;
              
              if(document.attachEvent) {  //ie
                var evTarget = e.srcElement;
                //climb upwards in node tree to find the a tag
                while(!parentFound) {
                  if(evTarget.tagName == 'A') {
                    parentFound = true;
                    var note = evTarget.getElementsByTagName('div')[0];
                  } else {
                    evTarget = evTarget.parentNode; 
                  }
                }
              } else { //mozilla
                var evTarget = e.target;
                 
                //climb upwards in node tree to find the a tag
                while(!parentFound) {
                  if(evTarget.tagName == 'A') {
                    parentFound = true;
                    var note = evTarget.getElementsByTagName('div')[0];
                  } else {
                    evTarget = evTarget.parentNode; 
                  }
                }
              }

                note.style.display = 'none';
}
            
function createTooltipListeners(obj) {
            //create additional listeners (move, out) on mouseover event for tooltip links
            if(obj.attachEvent) {
              obj.attachEvent('onmousemove',showToolTip);
              obj.attachEvent('onmouseout',hideToolTip);
            } else {
              obj.addEventListener('mousemove',showToolTip,false);
              obj.addEventListener('mouseout',hideToolTip,false);
            }
           
}

// function to show min deposit limit for different currencies in an drop down. Is used in real world bank deposit
		function showDepositMinLimit(selectElement){
			$('minAmountDiv').innerHTML = selectElement[selectElement.selectedIndex].id + ' ' + selectElement[selectElement.selectedIndex].value;
		}

    function calculateWithdrawal(value, fee, minFee, minValue){
//      alert(value);
      
      //the user has written an amount higer than the minimum
      if (value >= minValue ){
      
        // trim whitespaces
				value = value.replace(/^\s+|\s+$/g,"");
				
        valueUSD = value/10;
        valueUSD = valueUSD.toFixed(2);	// round to 2 decimals otherwise it goes havock (petjon 090714)
        amountUSDElement = document.getElementById('amountUSD');
        amountUSDElement.innerHTML = valueUSD;
        
        //for the form parameter
        amountUSDElement = document.getElementById('PEDCharge');
        valuePED = parseFloat(value);
		valuePED = valuePED.toFixed(2);	// ensure that we have a 2 decimal float posted
        amountUSDElement.value = valuePED;
        
        
        //for the form parameter
        amountFormParameter = document.getElementById('USDAmount');
        amountFormParameter.value = valueUSD;
        
        fee = fee * 0.01;
        feeUSD = fee * valueUSD;
        feeUSD = feeUSD.toFixed(2)
        minFeeUSD = minFee / 10;
        
        //if calculated fee less than minFee, use minFee 
        if(feeUSD > minFeeUSD){
          ;
        }
        else{
          feeUSD = minFeeUSD
        }
        
        feeElement = document.getElementById('fee');
        feeElement.innerHTML = '- ' + feeUSD;
        
        //for the form parameter
        feeUSDElement = document.getElementById('withdrawalFeeUSD');
        feeUSDElement.value= feeUSD;
        
        totalElement = document.getElementById('total');
        totalSumUSD = (valueUSD - feeUSD).toFixed(2);
        totalElement.innerHTML = totalSumUSD;
        
        //for the form parameter
        totalFormElement = document.getElementById('totalSum');
        totalFormElement.value= totalSumUSD;
        
        //for validation        
        document.getElementById('img_withdrawalAmount').src ='/img/check_valid.gif';
        
        //for validation to get the submit button enabled. We dont want to validate any field only the whole form(checks the check_valid.gif) thus 'dummy' parameter. tomeke
        validateForm(document.getElementById('withdrawalAmount'),'dummy', false);
      } 
      else{
        feeElement = document.getElementById('fee');
        feeElement.innerHTML = 0;
        
        totalElement = document.getElementById('total');
        totalElement.innerHTML = 0;
        
        totalFormElement = document.getElementById('totalSum');
        totalFormElement.value= 0;
        
        //for showing
        amountUSDElement = document.getElementById('amountUSD');
        amountUSDElement.innerHTML = 0;
      
        //for the form parameter
        amountFormParameter = document.getElementById('USDAmount');
        amountFormParameter.value = 0;
        
        //for the form parameter
        feeUSDElement = document.getElementById('withdrawalFeeUSD');
        feeUSDElement.value= 0;
        
        //for the form parameter
        amountUSDElement = document.getElementById('PEDCharge');
        amountUSDElement.value = 0;
        
        //for validation        
        document.getElementById('img_withdrawalAmount').src ='/img/check_unvalid.gif';
       
        //for validation to get the submit button disabled. We dont want to validate any field only the whole form(checks the check_valid.gif) thus 'dummy' parameter. tomeke
        validateForm(document.getElementById('withdrawalAmount'),'dummy', false); 
        
      }
    }
    
    function sumGoldCardOrder(){

			var totalCost = 0;

			transportElement = document.getElementsByName('transport');
  		for (i = 0; i < transportElement.length; i++){

				if(transportElement[i].checked){

					document.getElementById('transportName').innerHTML = transportElement[i].getAttribute('itemName');
					document.getElementById('transportCost').innerHTML = transportElement[i].getAttribute('itemCost');

	      	totalCost = Number(totalCost) + Number(transportElement[i].getAttribute('itemCost'));
      	}
      }

      productElement = document.getElementsByName('product');
  		for (i = 0; i < productElement.length; i++){
  		
				if(productElement[i].checked){
				
/*	      	var productParamsStr = productElement[i].getAttribute('itemName')
	      	var productParamsArray = productParamsStr.split(',')*/
/*	      	alert(array[0] + ' : ' + array[1]);*/
					
					document.getElementById('productName').innerHTML = productElement[i].getAttribute('itemName');
					document.getElementById('productCost').innerHTML = productElement[i].getAttribute('itemCost');
	      	
	      	totalCost = Number(totalCost) + Number(productElement[i].getAttribute('itemCost'));
      	}
      }
      document.getElementById('totalCost').innerHTML = totalCost;
		}


	/* javascript that handles onchange event on country select 
		 used in template insertCountrySelect in file /templates/parse-xml-response.xml
	*/
		function toggleRegion(countryID){
			//hide any open region selects,
			regionBoxes = document.getElementById('regionBoxes').childNodes;
			var i;
			for(i in regionBoxes){
				theTagType = regionBoxes[i].tagName;
				if(theTagType == 'DIV'){
					regionBoxes[i].style.display = "none";
				}
			}
			// if this country has a region select, display the div with the select
			regionBox = document.getElementById('region_' + countryID);
			if (regionBox != null){
				regionBox.style.display = 'block';
				$('resdRegion').value = $('resdRegion_' + countryID).value;
			}
			else{
				// set hidden input restRegion:s value to '' (new country - new regions, if any 
				theRegion = document.getElementById('resdRegion');
				theRegion.value = '';
			}
		}

		function dibsDepositAmountMinMax(currency){
			showID = document.getElementById('currencyMinMax' + currency);
			//hide any open currency values
			currencyBoxes = document.getElementById('depositCurrencyMinMax').childNodes;
			var i;
			for(i in currencyBoxes){
				theTagType = currencyBoxes[i].tagName;
				if(theTagType == 'SPAN'){
					currencyBoxes[i].style.display = "none";
				}
			}
			showID.style.display = 'inline';
		}
		
		function putRegionIntoForm(regionValue){
			theRegion = document.getElementById('resdRegion');
			theRegion.value = regionValue;
			// alert(theRegion +', ' + theRegion.value + ', ' + regionValue);
		}
		
		
  
    function showTip(objId,currField) {
        obj = document.getElementById(objId);
        obj.style.visibility = "visible";
        obj.style.display = "";
        currField.style.background = '#dbe6f4';
    }
    function hideTip(objId,currField) {
        obj = document.getElementById(objId);
        obj.style.visibility = "hidden";
        currField.style.background = '#ffffff';
    }

/*
    function evaluateInput(iconNr,field) {
      currImg = "icon"+iconNr;
      obj = document.getElementById(currImg);
      if(field.value != "") {
        obj.style.backgroundImage="url(icon_green.gif)";   
      } else {
        obj.style.backgroundImage="url(icon_grey.gif)";
      } 
    }
*/

/* ### Validate the whole form onload after user pressed back button in step three ### [AndSan] */
/* ###This method is currently very static and should be rewritten. Extra attributes could be put in the tags(input, select etc) that are to be validated.
    E.g <inpute type="text validate="notEmptyText"> or something like that. [tomeke] ###*/
function validateOnLoad(useCaptcha, formName) {
  var isOK = new Array();
  var readyToSubmit = true;
  var numInvalid = 0;
  var iconNr = 0;
  var onloadvalidate = true;
  if(!useCaptcha)
   useCaptcha = false;
   
  var formContent = document.getElementById(formName);
  for(i=0; i < formContent.length; i++) {
    if(formContent.elements[i].getAttribute('type') != 'hidden') { //dont include fields with type hidden
      if(formContent.elements[i].name == 'givenName' || formContent.elements[i].name == 'familyName' || formContent.elements[i].name == 'bankIBAN' || formContent.elements[i].name == 'bankBIC' || formContent.elements[i].name == 'resdAddress' || formContent.elements[i].name == 'resdPostalCode' || formContent.elements[i].name == 'resdCity')
        isOK.push(validateForm(formContent.elements[i],'name',useCaptcha));
      
      if(formContent.elements[i].name == 'birthYear' || formContent.elements[i].name == 'birthMonth' || formContent.elements[i].name == 'birthDay')
        isOK.push(validateForm(formContent.elements[i],'birth',useCaptcha));
      
      if(formContent.elements[i].name == 'gender')
        isOK.push(validateForm(formContent.elements[i],'gender',useCaptcha));
       
      if(formContent.elements[i].name == "confirmEmail" || formContent.elements[i].name == "email")
        isOK.push(validateForm(formContent.elements[i],'email',useCaptcha));

      if(formContent.elements[i].name == "eula" || formContent.elements[i].name == "guardian")
        isOK.push(validateForm(formContent.elements[i],'checkbox',useCaptcha));
            
      if(formContent.elements[i].name == "login")
        isOK.push(validateForm(formContent.elements[i],'login',useCaptcha));
    
      if(formContent.elements[i].name == "bankCountry" || formContent.elements[i].name == "resdCountry" )
        isOK.push(validateForm(formContent.elements[i],'select',useCaptcha));
      
    }
  }
  for(k=0; k < isOK.length; k++) {
    if(!isOK[k]) {
      readyToSubmit = false;
      numInvalid++;
    }
  }
  return readyToSubmit
}


/* ### Function for validating the input in account application form ### [AndSan] */
/* ### Note: When using validateForm there are some naming conventions and structures to remember:
1: All image tags for the validation icons must have an id with a "img_" prefix.
2: The above image tags must, in addition to the prefix, be named exactly as the input field name attribute they are coupled with.
For example: If the input field has the name "confirmPassword" the image id must be "img_confirmPassword". */
 
function validateForm(obj,field, useCaptcha) {
  var paramsArray = new Array();
  var regExpr;
  
  var imgValid = '/img/check_valid.gif';
  var imgInvalid = '/img/check_unvalid.gif';
  var imgError = '/img/check_error.gif';
  
  
  
  //if supplied fieldtype is an array
  if(field.constructor.toString().indexOf("Array") == -1) {
    var fieldType = field;
  } else {
    var fieldType = field[0];
    //add all supplied parameters to paramArray, these values can then be accessed in the different fieldType evaluations
    for(i=1; i < field.length; i++) {
      paramsArray.push(field[i]);
    }
  }

  if(paramsArray[0] == 'noImg'){
		var imgValid = '/img/check_blank.gif';
  	var imgInvalid = '/img/check_blank.gif';
  	//remove first element from params array (to allow multiple params)
  	paramsArray.shift();
	}
	   
  var validImgObj = new Array();
  
  if(!useCaptcha)
    useCaptcha = false;
    
  if(fieldType =='birth')
    imgId = 'img_'+obj.name.substring(0,5);
  else if(fieldType == 'expDate') {
    imgId = 'img_expDate';
  }
  else {
    imgId = 'img_'+obj.name;
  }
   
  //validate namefields
  if(fieldType == 'name') {
      var trimmedObj = obj.value.replace(/^\s+|\s+$/g,"");
      if(trimmedObj.length > 1) {
        document.getElementById(imgId).src =imgValid;
      } else {
        document.getElementById(imgId).src =imgError;
      }
  }
  if(fieldType == 'checkbox') {
    if(obj.checked)
      document.getElementById(imgId).src = imgValid;
    else
      document.getElementById(imgId).src = imgError;
  }
  if(fieldType == 'expDate') { //FIXME: Make generic
    var expMonth = obj.form.addCreditCardCardExpMonth.options[obj.form.addCreditCardCardExpMonth.selectedIndex].value;
    var expYear = obj.form.addCreditCardCardExpYear.options[obj.form.addCreditCardCardExpYear.selectedIndex].value;
    
    if(expMonth !='' && expYear !='')
      document.getElementById(imgId).src = imgValid;
    else
      document.getElementById(imgId).src = imgError;
  }

  if(fieldType == 'numDigits') {
    regExpr = /[^0-9]/;
    if(obj.value.search(regExpr) == -1) {
      if(obj.value.length >= paramsArray[0])
        document.getElementById(imgId).src = imgValid;
      else
        document.getElementById(imgId).src = imgInvalid;
    } else {
        document.getElementById(imgId).src = imgError;
    }
  }
  if(fieldType == 'email') {
    regExpr = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if(obj.value.search(regExpr)!= -1) {
      if(obj.name == 'confirmEmail') {//check that confirmEmail is same as Email
        if(obj.value == obj.form.email.value)
          document.getElementById(imgId).src =imgValid;
        else
          document.getElementById(imgId).src =imgError;
      } else
        document.getElementById(imgId).src =imgValid;
    } else {
      document.getElementById(imgId).src =imgError;
    }
  }
  if(fieldType == 'birth') {
    var suppYear = document.accountAppForm.birthYear.options[document.accountAppForm.birthYear.selectedIndex].value;
    var suppMonth = document.accountAppForm.birthMonth.options[document.accountAppForm.birthMonth.selectedIndex].value -1; //javascript uses 0-11
    var suppDate = document.accountAppForm.birthDay.options[document.accountAppForm.birthDay.selectedIndex].value;
    
    //if all dateparts has been supplied
    if(document.accountAppForm.birthYear.options[document.accountAppForm.birthYear.selectedIndex].value != '' && document.accountAppForm.birthMonth.options[document.accountAppForm.birthMonth.selectedIndex].value !='' && document.accountAppForm.birthDay.options[document.accountAppForm.birthDay.selectedIndex].value != '') {
      
      //convert supplied dateparts into a date object
      var suppliedDate = new Date(suppYear,suppMonth,suppDate);
      
      //compare created date object against each supplied part of date to check range validity (works on leap years)
      if((suppliedDate.getFullYear() == suppYear) && (suppliedDate.getMonth() == suppMonth) && (suppliedDate.getDate() == suppDate))
        document.getElementById(imgId).src=imgValid;
      else
        document.getElementById(imgId).src=imgError;
        
      if(calculateDateDiff(document.accountAppForm.birthYear.options[document.accountAppForm.birthYear.selectedIndex].value, document.accountAppForm.birthMonth.options[document.accountAppForm.birthMonth.selectedIndex].value, document.accountAppForm.birthDay.options[document.accountAppForm.birthDay.selectedIndex].value) < 18) {
        document.getElementById('guardian_perm').style.visibility = 'visible';
        document.getElementById('guardian_perm').style.display = 'block';
      } else {
        document.getElementById('guardian_perm').style.visibility = 'hidden';
        document.getElementById('guardian_perm').style.display = 'none';
      }
    } else
      document.getElementById(imgId).src=imgError;
  }
  
  if(fieldType == 'gender') {
    if(document.getElementById('male').checked || document.getElementById('female').checked)
      document.getElementById(imgId).src = imgValid;
    else
      document.getElementById(imgId).src = imgError;
  }
  
  if(fieldType == 'login') {
    regExpr = /[^a-zA-Z0-9]+/;
    if(obj.value.length >= 6 && obj.value.length <= 20){
      if(obj.value.search(regExpr) == -1) {
        document.getElementById(imgId).src =imgValid;
      }
      else{
        document.getElementById(imgId).src =imgError;
      }
    }  
    else{
      document.getElementById(imgId).src =imgError;
    }  
  }

  if(fieldType == 'password') {
    regExpr = /[^a-zA-Z0-9^!@#$%^&*?_~]+/;
    if(obj.value.length >= 6){
      if(obj.value.search(regExpr) == -1) {
        if(obj.name == 'confirmPassword') { //check that confirmPassword is same as password
          if(obj.value == obj.form.password.value)
            document.getElementById(imgId).src =imgValid;
          else
            document.getElementById(imgId).src =imgError;
        }
        else
          document.getElementById(imgId).src =imgValid;
      }
      else{
        document.getElementById(imgId).src =imgError;
      }
    }  
    else{
      document.getElementById(imgId).src =imgInvalid;
    }  
  }
  
  if(fieldType == 'select') {
    if(obj.value > 0){
      document.getElementById(imgId).src = imgValid;
    }
    else{
      document.getElementById(imgId).src = imgError;
    }  
  }
 
  //check all image icons inside application form to see if they are valid, then enable submit button
//  if(!parentObj) {
//alert(obj.form.name);    
    //loop through all img tags on page and extract those with the prefix 'img' in the id, ie validation icons
    var allImgObj = obj.form.getElementsByTagName('img');
    for(m=0; m < allImgObj.length; m++) {
      if(allImgObj[m].id.substring(0,3) == 'img' && allImgObj[m].id != 'img_capString') //FIXME: should be more generic
        validImgObj.push(allImgObj[m]);
    }
    var numValid = 0;

    for(j=0; j < validImgObj.length; j++) {
      //only validate objects if they have visibility set to visible 
      if(validImgObj[j].src.substring((validImgObj[j].src.lastIndexOf('/')+1)) == 'check_valid.gif' || validImgObj[j].parentNode.style.visibility == 'hidden')
        numValid++;
    }
    
//    alert(obj.getAttribute('type'));
//    alert(useCaptcha);
//  This check is for forms that dont have submit button disabled
    if(obj.form.getAttribute('disableSubmit')){
      //only check captcha length if useCaptcha is true
      if(useCaptcha) {
        if(validateCaptcha(numValid, validImgObj, obj.form.capString.value.length))
          obj.form.submit.disabled = false;
        else
          obj.form.submit.disabled = true;
      } else {
        if(numValid == validImgObj.length)
          obj.form.submit.disabled = false;
        else
          obj.form.submit.disabled = true;
      }
    } else {
      if(numValid == validImgObj.length) {
          return true;
      } else
          return false;
    }
//  }

};

/* ### Compares the captcha session against the submitted value and returns true if they match, otherwise false [AndSan] ### */
function validateCaptcha(numValid, validImgObj, length) {
  // if checked fields match number of valid image tags and captcha input field contains right number of characters
  if(numValid == validImgObj.length && length > 2)
    return true;
  else
    return false;
};

/* ### Calculate difference between supplied date and todays date [AndSan] ### */
function calculateDateDiff(year, month, day) {
    //substract one from month since month is 0-11 in javascript
    month--;
    
    var startDate = new Date(year, month, day);
    var today = new Date();
    
    var age = today.getFullYear() - startDate.getFullYear();
    
    //if startdate month is higher than todays month, compare dates to see if startdate has occured yet this year
    if(startDate.getMonth() > today.getMonth()) {
      age--;
    } else if(startDate.getMonth() == today.getMonth()) {
      if(startDate.getDate() > today.getDate())
        age--;
    }
    //return number of years
    return age;
};

/* ### Check the confirm form in last step of account creation for active email or login input fields. If any of these exist, replace hidden input fields with their values [AndSan] ### */
function validateConfirmForm(currForm) {
  if(document.confirmForm.email) {
    currForm.email.value = document.confirmForm.email.value;
  }
  if(document.confirmForm.login) {
    currForm.login.value = document.confirmForm.login.value;
  }
  if(document.confirmForm.userCampaignCode) {
    currForm.userCampaignCode.value = document.confirmForm.userCampaignCode.value;
  }
}

/* ### Function for ajax loading of screenshot images, used by img-gallery.xsl ### */
function screenShotLoader(path){
	new Ajax.Request('/media/screenshots/ajaxparts.html?__toolbar=0&sel-image=' + path, 
		{method: 'get', 
			onSuccess: function(transport){
				img = $('img-gall-selected-image');	//img-gall-selected-image-img
				ttext = $('img-gall-selected-titleText');
				prevnext = $('img-gallery-prev-next');
				Element.remove(ttext);
				new Effect.Shrink('img-gall-selected-image-img', {duration: 0.5,afterFinish:
					function dodisplay(){
						// only img left, replace it with new img, text + next/prev data
						Element.replace(img, transport.responseText);
						img.style.display = 'none'; // needed for appear effect
						Effect.multiple([img, ttext], Effect.Appear);
					}
				})
			}
		}
	)
}

function changeScreenGallery(path){
	new Effect.Fade('img-gall', {to:0.01, duration:0.3
		, afterFinish: 
			function loadNewGallery(){
				new Ajax.Updater('img-gall', '/media/screenshots/ajaxparts.html?showFolder=' + path, {
					onComplete:
						function bahab(){
							Effect.Appear('img-gall', {duration:0.3});
						}
					}
				)
			}
		}
	)
}

function overlay(path){

	el = $("overlay");
	el_img = $("overlay-img");
	//alert(el_img.style.visibility);
	if (el.style.visibility != 'visible'){
		el.style.visibility = 'visible';
		el_img.style.visibility = 'visible';
		//	load this image with ajax to use roxens img transformation
		if (path){
			new Ajax.Updater(el_img, '/media/screenshots/ajaxparts.html?loadFullSizeImg=' + path, {method:'get', onComplete:
				function displayfullsize(){
					Effect.multiple([el, el_img], Effect.Appear);
				}
			})
		}
	}
	else{
		Effect.multiple([el, el_img], Effect.Fade, {afterFinish: 
				function(){
					el.style.visibility = 'hidden'; 
					el_img.style.visibility = 'hidden';
				}
			}
		);
	}
	//el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
	//el_img.style.visibility = (el_img.style.visibility == "visible") ? "hidden" : "visible";
}
/* This is probably not in use /tomeke
function attach(popup_url,  caseId) {
  window.open(popup_url + "?__toolbar=0&__noframe=1&case=" + caseId , "attach",
	      "toolbar=no,scrollbars=no,resizable=no,menubar=no,width=400,height=300");
}*/

// Call this with link to message text and parsing template 
// E.g display_agreement('/messages/legal/real-world-items/index.xml?__noframe=1&amp;__xsl=/templates/page-comp-plain-output.xsl')
function display_agreement(link) {
    Modalbox.show(link, {title: '&nbsp; ',
        overlayOpacity:.7, 
        width: 950, 
        height: 700, 
        xafterHide: redirectBack }); // afterhide disabled with an x
}

function display_EULA() {
    Modalbox.show('/messages/legal/eula/index.xml?__noframe=1', {title: 'Entropia Universe End User License Agreement',
        overlayOpacity:.7, 
        width: 950, 
        height: 700, 
        xafterHide: redirectBack }); // afterhide disabled with an x
}

function flvPlayer(file,vtitle,w,h) {
    Modalbox.show('/swf/flv-player.xml?vidObj='+file, {title: vtitle,
        overlayOpacity:.9, 
        width: w, 
        height: h, 
        xafterHide: redirectBack }); // afterhide disabled with an x
}
function alterTextField(id){
    // used for /tip.xsl
    field = document.getElementById(id);
    field.value = '';
    field.style.color = '#333;';
}


function tip_friend(popup_url, path) {

    Modalbox.show('/tip.xml?__noframe=1&pagePath='+path, {title: '&nbsp;',
        overlayOpacity:.20, 
        width: 380, 
        height: 420, 
        xafterHide: redirectBack }); // afterhide disabled with an x
}


//tip_friend moved from popup window to modalbox, old code:
 /* window.open(popup_url + "?__toolbar=0&__noframe=1&path=" + path, "",
	      "toolbar=no,scrollbars=no,resizable=no,menubar=no,width=300,height=450");*/
	    

var login_action = false;

function redirectBack() {
  var from = $('from').value;
  try{
    var up = $('up').value;
  }
  catch(err){
    var up = "";
  }
  // handle the notorious empty from value ;(
  if (from == ''){
  	from = "/";
  }
  
  

  var login_page = $('login-page').value;
  var logout_page = $('logout-page').value;

//  if (from != login_page && from != logout_page && login_action) {
  if (from != login_page && from != logout_page) {
    window.location = from + "?__noframe=1";
  }
  else{
    window.location = "/?__noframe=1";
  }
  
  if(up.length > 0 && !login_action){
    window.location = up + "?__noframe=1";
  }
    
}

function modalbox_login(title) {
  Modalbox.show($('login'), {
    title: title, width: 300, height: 270, afterHide: redirectBack }); 
}


function login(ajax_auth_url, fail) {  
  
  var username = $('username').value;
  var password = $('password').value;

  var url = ajax_auth_url + "?__noframe=1" +
    "&login-type=std";
  $('login-fail').hide();

  function onSuccess(response) {
    if (response.responseText.search("<status>OK</status>") != -1){
      login_action = true;
      redirectBack();
    }
    else if (response.responseText.search("<status>network_failure</status>") != -1){
      $('login-fail-network').show();
      return false; 
    } 
    else{
    	$('login-fail').innerHTML = response.responseText;
      $('login-fail').show();
    }
  }
  
  function onFailure(response) {
    $('login-fail-network').show();
    return false;
  }

  new Ajax.Request(url, 
  { method: "post", parameters: {username: username, password: password}, onSuccess:  onSuccess, onFailure: onFailure });
return false; 
}


function login_gold(ajax_auth_url) {
  var code = $('code').value;
  var url = ajax_auth_url + "?__noframe=1&login-type=gold";
  login_action = true;

  function onSuccess(response) {
//    alert(response.responseText);
    if (response.responseText.search("<status>OK</status>") != -1){
      redirectBack();
    }
    else{
      $('login-fail').show();
    }
  }
  
  function onFailure(response) {
    $('login-fail-network').show();
  }

  new Ajax.Request(url, 
  { method: "post", parameters: {code: code}, onSuccess: onSuccess, onFailure: onFailure });
  
  return false; 
}



	// makes a blinddown, also changes click behaviour so that open boxes fold again
		function toggle_pagepart_blind(url){
			thisbox = $(url + '-content');
			if (thisbox.style.display == 'none'){
				Effect.BlindDown(url + '-content', { duration: 0.3, afterFinish:$(thisbox).style.height='auto' })
			}
			else{
				Effect.BlindUp(url + '-content', { duration: 0.3 })
			}
		}
		