
//re-fetches the captcha template from /templates/rxml-defines 
function regenerateCaptcha(targetArea,fieldToClear) {
  new Ajax.Updater({success: targetArea}, '/captcha.xml?__xsl=/templates/page-comp-plain-output.xsl&__toolbar=0', { method: 'get'});
  if(fieldToClear != undefined)
    fieldToClear.value = '';
}
function checkUsername(login,capString,target) {
var url = '/account-application/account-details/check-username.xml?login=' + login + '&capString=' + capString + '&__toolbar=0';

  new Ajax.Request(url, {
  method: 'get',
  onSuccess: function(transport) {
  var trimmedString = transport.responseText.replace(/^\s+|\s+$/g,"");

   document.getElementById('status-text').style.display = 'none';
     if(trimmedString == 'used') {
        document.getElementById(target).src = '/img/check_error.gif';
        document.getElementById('status-text').innerHTML = ' Already in use';
        document.getElementById('status-text').style.display = 'inline';
     } else if(trimmedString == 'available')  {
        document.getElementById(target).src = '/img/check_valid.gif';
     } else
        document.getElementById(target).src = '/img/check_unvalid.gif';
  },
  onFailure: function(transport) {
      document.getElementById('status-text').innerHTML = ' Error';
      document.getElementById(target).src = '/img/check_unvalid.gif';
  }
  });
}
// function to test that the entered amount is higer than the minimum in bank deposit
function testBankMinAmount(){

  var bankAmount = $('bankDepositAmount').value;
  
  var selectElement = $('bankDepositCurrency');
  var minValue = selectElement[selectElement.selectedIndex].id 

  $('minAmountText').style.border = '';
  
//  alert('bankAmount: ' + bankAmount + ' minValue: ' + minValue);
  if(Number(bankAmount) < Number(minValue)){
    var bankAmountInput = $('bankDepositAmount');
    bankAmountInput.focus();
    
    $('minAmountText').style.border = '1px solid red';
    return false;
  }
}

// function that tests that the PED certificate code is exactly 20 characters long
function testCertificateCode(){
  pedCertificateCode = $('pedCertificateCode');
  
  if(pedCertificateCode.value.length < 20){
    pedCertificateCode.focus();
    return false;
  }
}

// function to test that the ukash voucher number is exactly 19 digits long
function testUkashInput(){
  var ukashCode = $('ukashCode');
  
  if(ukashCode.value.length != 19){
  
    var ukashCodeImg = $('img_ukashCode');
    ukashCodeImg.src = '/img/check_error.gif';
    
    ukashCode.focus();
  
    return false;
  }
  
  var ukashAmount = $('ukashAmount');
  
  if(!(ukashAmount.value > 0)){
    ukashAmount.focus();
    return false;
  }
}

// function to restrict characters in input field to digits. Used in credit card deposit, file /templates/html-forms/deposits/credit-cards-ajax.xsl and other places
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;
    }
  }
}

//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){
		  
//		this is to turn off red border if too low amount was selected in bank deposit
		  if($('minAmountText') != null){
        $('minAmountText').style.border = '';
      }
		  
			$('minAmountDiv').innerHTML = selectElement[selectElement.selectedIndex].id + ' ' + selectElement[selectElement.selectedIndex].value;
		}

    function calculateWithdrawal(value, fee, minFee, minValue, balance){
//      alert(value);
      
      //the user has written an amount higer than the minimum
      if (value >= minValue && value <= balance){
      
        // 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;
      document.getElementById('totalCostHidden').value = 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";
				}
			}
			*/
			//above breaks in IE, hardcoded replacement below
			$('region_124').style.display = 'none';
			$('region_840').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)";
      } 
    }
*/

/*special behavior to select preselected option on revalidate of accountAppForm (because region and country options currently are hardcoded)*/
function preselectOption(country, region) {
         //alert(country);
         var selCountry = document.getElementById('resdCountry');
         var index = 0;
         //get selected index using option value
         for(i=0; i < selCountry.options.length; i++) {
            if(selCountry.options[i].value == country)
              index = i;
         }
          selCountry.options[index].selected = true;
           
        //validate regions if country is USA or Canada
        if(country == 124 || country == 840) {
                var selRegion = document.getElementById('resdRegion_'+country);

                index = 0;
                //get selected index using option value
                for(i=0; i < selRegion.options.length; i++) {
                    if(selRegion.options[i].value == region)
                    index = i;
                }
                selRegion.options[index].selected = true;
                
                //show region div and set hidden regionId field value
                var regionDiv = 'region_'+country;
                document.getElementById(regionDiv).style.display='block';
                document.getElementById('resdRegion').value = region;
        }   
          
}
/* ### 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, source) {
  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") {
        if(source == 'onload')
          isOK.push(validateForm(formContent.elements[i],'login_onvalidation',useCaptcha));
        else
          isOK.push(validateForm(formContent.elements[i],'login',useCaptcha, source));
      }
      if(formContent.elements[i].name == "bankCountry" || formContent.elements[i].name == "resdCountry" || formContent.elements[i].name == "resdRegion_124" || formContent.elements[i].name == "resdRegion_840")
        isOK.push(validateForm(formContent.elements[i],'select',useCaptcha));
      
    }
  }
  for(k=0; k < isOK.length; k++) {
    if(!isOK[k]) {
      readyToSubmit = false;
      numInvalid++;
    }
  }
  
  if(document.getElementById('validateErrorMsg') && source != 'onload') {
    if(!readyToSubmit)
      document.getElementById('validateErrorMsg').style.display ='block';
    else
      document.getElementById('validateErrorMsg').style.display ='none';
  }

  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, source) {
  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 || field == undefined) {
    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 > 0 ) {
        document.getElementById(imgId).src =imgValid;
      } else {
        document.getElementById(imgId).src =imgError;
      }
  }
  
  if(fieldType == 'strLength') {
      var trimmedObj = obj.value.replace(/^\s+|\s+$/g,'');

      if(trimmedObj.length >= paramsArray[0] && trimmedObj.length <= paramsArray[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 == 'numLength') {
    regExpr = /[^0-9]/;
    if(obj.value.search(regExpr) == -1) {
      if(obj.value.length >= paramsArray[0] && obj.value.length <= paramsArray[1])
        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(source !='button')
      document.getElementById(imgId).src =imgInvalid;
    
    if(obj.value.length >= 6 && obj.value.length <= 20){
      if(obj.value.search(regExpr) == -1) {
          document.getElementById('btnAvailability').style.display ='inline';
          //alert(document.getElementById(imgId).src.substring((document.getElementById(imgId).src.lastIndexOf('/') +1)));
          if(document.getElementById('btnAvailability').style.display =='none' || document.getElementById(imgId).src.substring((document.getElementById(imgId).src.lastIndexOf('/') +1)) != 'check_valid.gif')
            document.getElementById(imgId).src =imgInvalid;
            
          if(source != undefined && document.getElementById('btnAvailability').style.display != 'none' && document.getElementById(imgId).src.substring((document.getElementById(imgId).src.lastIndexOf('/') +1)) == 'check_unvalid.gif')
            document.getElementById(imgId).src =imgError;
      }
      else{
        document.getElementById(imgId).src =imgError;
        document.getElementById('btnAvailability').style.display ='none';
      }
    }  
    else{
      document.getElementById('btnAvailability').style.display ='none';
        
    } 

  }
  if(fieldType == 'login_onvalidation') {
    if(obj.value.length < 6)
      document.getElementById(imgId).src =imgError;
    else
      document.getElementById(imgId).src =imgValid;
    
  }
  
  if(fieldType == 'password') {
    //match all chars
    regExpr = /[^\s\S]+/;
    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.selectedIndex > 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' || validImgObj[j].parentNode.style.display == 'none')
        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 {
    //alert(numValid +'-'+validImgObj.length +': '+validImgObj[(validImgObj.length -1)].id);
      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) {  
  
  $('login_loader').style.display = 'inline';
  
  var username = $('username').value;
  var password = $('password').value;

  var url = ajax_auth_url + "?__noframe=1" + "&login-type=std";
  $('login-fail').hide();
  
  if(username.length < 1 || password.length < 1){
    $('login-fail').show();
    return false;
  }
  

  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();
      $('login_loader').style.display = 'none';
      return false; 
    } 
    else{
    	$('login_loader').style.display = 'none';
    	$('login-fail').innerHTML = response.responseText;
      $('login-fail').show();
    }
  }
  
  function onFailure(response) {
  	$('login_loader').style.display = 'none';
    $('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;
  $('login-fail').hide();
  
  if(code.length < 6 || !IsNumeric(code)){
    $('login-fail').show();
    return false;
  }

  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; 
}

function IsNumeric(sText){

  var ValidChars = "0123456789";
  var IsNumber=true;
  var Char;
 
  for (i = 0; i < sText.length && IsNumber == true; i++){ 
    Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1){
        IsNumber = false;
      }
  }
  return IsNumber;
}

function IsCharacters(sText){

  for( var i=0; i < sText.length; i++) {
  
  sText.charAt(i).charCodeAt(0)
  
    if (!(sText.charAt(i)>="a" && sText.charAt(i)<="z"||sText.charAt(i)>="A" && sText.charAt(i)<="Z")){
      return false;
    }
  }
  return true;
}


	// 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 })
			}
		}

function checkFieldNotEmpty(elementID, elementName) {
  if($(elementID).value.length > 0) {
    return true;
  } else {
    $('img_'+elementName).src = '/img/check_error.gif';
    $(elementID).focus();
    return false;
  }
}

function checkCreditCardAmountAndCVV() {
  if($('idAmount').value.length>0 && $('idCode').value.length>0) {
    return true;
  } else {
    if($('idAmount').value.length==0) { $('idAmount').style.border = '1px solid #ff0000'; }
    if($('idCode').value.length==0) { $('idCode').style.border = '1px solid #ff0000'; }
    return false;
  }
}	

function checkEmailDNS(email) {
$('emailDnsMessage').hide();
if(email.length < 5) { return false; }
var url = '/account-application/account-details/check-email-dns.xml?email=' + email + '&__toolbar=0&__xsl=/templates/page-comp-plain-output.xsl';

  new Ajax.Request(url, {
  method: 'post',
  onSuccess: function(transport) {
  var trimmedString = transport.responseText.replace(/^\s+|\s+$/g,"");
    if(trimmedString == "OK") {
      $('emailDnsMessage').hide();
    } else {
      //Show ? image if dns check fails but js check is valid
      if($('img_email').src.indexOf('/img/check_valid.gif') > 0) {  $('img_email').src = '/img/check_unknown.png';}
      $('emailDnsMessage').show();
      $('enteredMail').innerHTML = email.substring( email.indexOf('@')+1 );
      Effect.Pulsate('emailDnsMessageImg', {pulses:2, duration:1.0});
    }
    
  },
  onFailure: function(transport) {
      //Something happend in request, do not show error message
      $('emailDnsMessage').hide();
  }
  });

}	