/***********************************************
* PURPOSE:
* return true if a file name has a valid 
* extension, false otherwise.
***********************************************/
function checkExt(filename){

var filelength = parseInt(filename.length) - 4;
var fileext    = filename.substring(filelength,filelength + 4);

// Check file extenstion
if (fileext.toLowerCase() != ".png")
   {
   if(filename.length > 0)
       alert(filename+" was not a .png format image.");
   else
      alert("You must upload images with a .png extension.");
   return false;
   }

return true;
}

/***********************************************
* PURPOSE:
* Hide a sprite box.
***********************************************/
function hide_box(box){
box.style.display = "none";
}

/***********************************************
* PURPOSE:
* Show a sprite box.
***********************************************/
function show_box(box){
box.style.display = "block";
}

/***********************************************
* PURPOSE:
* Check a custom creature being created for 
* correct values.
***********************************************/
function validate_custom_creature(current_credit){

var breed_name   = document.getElementById('breed_name');
var description  = document.getElementById('description');
var agree        = document.getElementById('agreement');
var bonus_points = document.getElementById('bonus_point');

var base_cost    = document.getElementById('base_cost');
var quality_cost = document.getElementById('quality_cost');
var artist_cost  = document.getElementById('artist_charge');
var skill_cost   = document.getElementById('skill_charge');
var sprite_redu  = document.getElementById('sprite_reduction');

var artist_total = document.order_form.artist_group.length;
var total        = parseInt(base_cost.value) + parseInt(quality_cost.value) + parseInt(artist_cost.value) + parseInt(skill_cost.value) - parseInt(sprite_redu.value);

if(bonus_points.value != 0)
  {
  alert('You must distribute all 100 stat bonus points.');
  return false;
  }
if(breed_name.value.length > 15 || breed_name.value.length < 3)
  {
  alert('Breed names must be between 3 and 15 characters in length.');
  return false;
  }

//Check skills
for(var count = 1; count <= 5; ++count)
   {
   if(document.getElementById('skill_' + count).value == '0')
     {
     var descrip = document.getElementById('c_skill_' + count).value;

     if(descrip.length > 500 || descrip.length < 10)
       {
       alert("Custom skill "+ count + "'s descriptions must be between 10 and 500 characters.");
       return false;
       }
     }
   }

if(total > current_credit)
  {
  alert('You do not have enough Credit for this order. Please decrease the growth quality, choose a different image source, or acquire more credit.');
  return false;
  }

for(count = 0; count < artist_total; ++count)
   {
   if(document.order_form.artist_group[count].checked)
             var artist = document.order_form.artist_group[count].value;
   }

if(agree.checked == false)
  {
  alert("You must agree to the contract before submitting a custom character for creation.");
  return false;
  }

//Handles sub forms within the hidden divs
switch(artist)
      {
      case 'premade':
                var color_id = document.getElementById("color_sprite_set").value;
                var breed_id = document.getElementById("premade_sprite_set").value;

                if(color_id == 'custom')
                     {
                     var color_description = document.getElementById('color_description');

                     if(color_description.value == "Describe color preference here.")
                       {
                       alert('Please describe the custom colors you want this sprite to have.');
                       return false;
                       }
                     if(color_description.value.length < 20 
                     || color_description.value.length > 2050)
                       {
                       alert('The description of the colors you want for a premade sprite must be between 20 and 2050 characters in length.');
                       return false;
                       }

                     document.getElementById("color_description").value = color_description.value;
                     }
                break;
      case 'me':
                var order_form  = document.getElementById("order_form");
                var files       = order_form ["userfile[]"];

                for(i = 0; i < 12; ++i)
                   if(! checkExt(files[i].value))
                      return false;

                break;
      default:
                var sprite_description = document.getElementById("sprite_description");

                if(sprite_description.value.length < 20 || sprite_description.value.length > 10000)
                  {
                  alert('Custom art directions must be between 20 and 10000 characters in length.');
                  return false;
                  }
                break;
      }

if(description.value.length > 500 || description.value.length < 10)
  {
  alert('Your description of this breed must be between 10 and 500 characters in length.');
  return false;
  }

document.getElementById("order_form").submit();
}

/***********************************************
* PURPOSE:
* Alter artist fee.
***********************************************/
function artist_fee_reduction(sprite_max){

var sprite_redu  = document.getElementById('sprite_reduction');
var total        = document.getElementById('sprite_total');
var art_charge   = document.getElementById('artist_charge');
var reduction;

if(total.value == sprite_max)
    reduction = 0;
else
    {
    
    var percent = parseFloat(((1 / sprite_max * 100) * parseInt(total.value)) / 100);

    var charge  = parseInt(art_charge.value);

    reduction =   charge - Math.round(charge * percent);
    }

sprite_redu.value = reduction;
}

/***********************************************
* PURPOSE:
* Display custom selection for user.
***********************************************/
function custom_skill_check(cost){

var custom;
var selector;
var charge = 0;
var hold     = document.getElementById('skill_charge');

for(var level = 1; level <= 5; ++level)
   {
   selector = document.getElementById('skill_' + level);
   custom   = document.getElementById('c_skill_' + level + '_div');

   if(selector.value == '0')
     {
     custom.style.display = "block";
     charge += cost;
     }
   else
     {
     custom.style.display = "none";
     }
   }

hold.value = charge;
}

/***********************************************
* PURPOSE:
* Change which sprite the user sees.
***********************************************/
function change_sprite_preview(select_id, color_id, stand_id, port_id){

var breed_selection = document.getElementById(select_id); 
var color_selection = document.getElementById(color_id); 

var standing_sprite = document.getElementById(stand_id);
var portrait_sprite = document.getElementById(port_id);

var color = color_selection.value;
var breed = breed_selection.value;

var description = document.getElementById('color_description');
var explanation = document.getElementById('color_explanation');
var color_char  = document.getElementById('char_counter');
var hold        = document.getElementById('artist_charge');

switch(color_selection.value)
      {
      case 'custom':
                    color = 1;
                    description.style.display  = "table-cell";
                    explanation.style.display  = "table-cell";
                    color_char.style.display   = "table-cell";
                    explanation.innerHTML      = "Please describe the colors you want this creature to have below.";
                    hold.value                 = 500;
                    break;
      case 'l_mod':
                    color = 1;
                    description.style.display  = "table-cell";
                    explanation.style.display  = "table-cell";
                    color_char.style.display   = "table-cell";
                    explanation.innerHTML      = "Light modifications include small things, such as tail removal, horn removal, color changes, and altered skill effects. Please describe yours below.";
                    hold.value                 = 1250;
                    break;
      case 'h_mod':
                    color = 1;
                    description.style.display  = "table-cell";
                    explanation.style.display  = "table-cell";
                    color_char.style.display   = "table-cell";
                    explanation.innerHTML      = "Heavy modifications include large things, like complex clothing and weapon changes along with light modifications. Please describe yours below.";
                    hold.value                 = 2500;
                    break;
      default:
                    description.style.display  = "none";
                    explanation.style.display  = "none";
                    color_char.style.display   = "none";
                    hold.value                 = 50;
      }


standing_sprite.src = "../images/sprites/l/" + breed + "/stand/0"    + color + ".png";
portrait_sprite.src = "../images/sprites/l/" + breed + "/portrait/0" + color + ".png";
}

/***********************************************
* PURPOSE:
* Set how much the cost is.
***********************************************/
function set_cost(type, amount, name){

switch(type)
      {
      case 'quality': var hold    = document.getElementById('quality_cost');
                      var quality = document.getElementById('quality');

                      switch(quality.value)
                            {
                            case '1': amount = 0;
                                     break;
                            case '2': amount = 200;
                                     break;
                            case '3': amount = 400;
                                     break;
                            case '4': amount = 600;
                                     break;
                            case '5': amount = 1000;
                                     break;
                            }
                      break;
      case 'artist':  var hold         = document.getElementById('artist_charge');
                      var premade_box  = document.getElementById('premade_sprites');
                      var create_box   = document.getElementById('create_sprites');
                      var custom_box   = document.getElementById('custom_sprites');
                      var reduction    = document.getElementById('sprite_reduction');
                      var sprite_count = document.getElementById('sprite_total');

                      sprite_count.options[8].selected = true;

                      reduction.value = 0;
 
                      switch(name)
                            {
                            case 'me': 
                                       hide_box(custom_box);
                                       hide_box(premade_box);
                                       show_box(custom_box);
                                       break;
                            case 'premade': 
                                       hide_box(create_box);
                                       hide_box(custom_box);
                                       show_box(premade_box);
                                       break;
                            default:
                                       hide_box(premade_box);
                                       hide_box(custom_box);
                                       show_box(create_box);
                                       break;
                            }
                      break;
      }

hold.value = amount;
}

/***********************************************
* PURPOSE:
* Raise or lower a stats value during 
* creature creation.
***********************************************/
function element_change(direction, element_id, max){

var temp_element  = document.getElementById(element_id);

switch(element_id)
      {
      case  'dark':
                   opposing = 'light';
                   break;
      case 'light':
                   opposing = 'dark';
                   break;
      case 'earth':
                   opposing = 'wind';
                   break;
      case  'wind':
                   opposing = 'earth';
                   break;
      case  'fire':
                   opposing = 'water';
                   break;
      case 'water':
                   opposing = 'fire';
                   break;
      }

var temp_opp_element = document.getElementById(opposing); 

var this_element  = parseFloat(temp_element.value);
var that_element  = parseFloat(temp_opp_element.value);

if(direction == 'up')
  {
  if(this_element  >= max)
             return false;
  else
    {
    var fin_that = that_element   - .05;
    var fin_this = this_element   + .05;
    }
  }
else
  {
  if(this_element  <= -max)
             return false;
  else
    {
    var fin_that = that_element   + .05;
    var fin_this = this_element   - .05;
    }
  }

temp_opp_element.value = fin_that.toFixed(2);
temp_element.value     = fin_this.toFixed(2);
}

function wht_change(direction){

var atk_bonus = document.getElementById("atk_bonus");
var cur_wht   = document.getElementById("wht");

var bonus = parseFloat(atk_bonus.value);
var wht  =  parseInt(cur_wht.value);

switch(direction)
      {
      case "up":
                  if(wht < 150)
                    {
                    wht += 5;
                    bonus = ((wht - 100) /  300);
                    atk_bonus.value = Math.round(bonus.toFixed(2) * 100);
                    cur_wht.value = wht;
                    }
                  break;
      case "down":
                  if(wht > 100)
                    {
                    wht -= 5;
                    bonus = ((wht - 100) /  300);
                    atk_bonus.value = Math.round(bonus.toFixed(2) * 100);
                    cur_wht.value = wht;
                    }
                  break;
      }
}

/***********************************************
* PURPOSE:
* Raise or lower a stats value during 
* creature creation.
***********************************************/
function stat_change(direction, stat_id, max){

var temp_stat  = document.getElementById(stat_id);
var temp_bonus = document.getElementById('bonus_point'); 

var stat  = parseInt(temp_stat.value);
var bonus = parseInt(temp_bonus.value);

if(stat_id == 'spirit')
  {
  var opposing_stat = document.getElementById('health');
  var opp_stat = parseInt(opposing_stat.value);

  switch(direction)
        {
        case 'up':   if(stat >= max || opp_stat <= 20)
                                                return false
                     temp_stat.value = stat         + 20;
                     opposing_stat.value = opp_stat - 20;
                     break;
        case 'down': if(stat <= 20 || opp_stat >= max)
                                              return false
                     temp_stat.value = stat         - 20;
                     opposing_stat.value = opp_stat + 20;
                     break;
        }
  }
else
if(stat_id == 'health')
  {
  var opposing_stat = document.getElementById('spirit');
  var opp_stat = parseInt(opposing_stat.value);

  switch(direction)
        {
        case 'up':   if(stat >= max || opp_stat <= 20)
                                                return false
                     temp_stat.value = stat         + 20;
                     opposing_stat.value = opp_stat - 20;
                     break;
        case 'down': if(stat <= 20 || opp_stat >= max)
                                              return false
                     temp_stat.value = stat         - 20;
                     opposing_stat.value = opp_stat + 20;
                     break;
        }
  }
else
 if(direction == 'up')
  {
  if(bonus < 10)
             return false;
  else
    {
    temp_bonus.value = bonus - 10;
    temp_stat.value  = stat + 10;
    }
  }
else
  {
  if(stat <= 60)
             return false;
  else
    {
    temp_bonus.value  = bonus + 10;
    temp_stat.value   = stat - 10;
    }
  }
}

/***********************************************
* PURPOSE:
* Removes white spaces at the beginning and 
* end of a string.
*
* Source:
* http://www.delphifaq.com/faq/f1031.shtml
***********************************************/
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

/***********************************************
* PURPOSE:
* attach a challenge to user's password and 
* forward it to the server.
*
***********************************************/
function login(){

var loginform = document.getElementById("loginform");

if (loginform.username.value == "") 
         {
         alert("Please enter your user name.");
         return false;
         }
if (loginform.password.value == "") 
         {
         alert("Please enter your password.");
         return false;
         }

loginform.username.value = loginform.username.value.trim();
loginform.password.value = loginform.password.value.trim();

var submitForm = document.getElementById("submitform");

submitForm.username.value = loginform.username.value;

submitForm.response.value = hex_md5(loginform.challenge.value+loginform.password.value);

if(loginform.hold.checked)
      submitForm.remember.value = 1;
else
      submitForm.remember.value = 0;

submitForm.submit();
}

/**************************************
* PURPOSE:                                          
* Read a specific mail a user selected.          
* Dynamic Version by: Nannette Thacker      
* http://www.shiningstar.net -->        
* Original by :  Ronnie T. Moore -->   
* Web Site:  The JavaScript Source -->       
* Use one function for multiple text    
* areas on a page -->                                     
* Limit the number of characters per    
* textarea -->                          
***************************************/
function textcounter(field, cntfield, maxlimit) {

if (field.value.length > maxlimit) // if too long...trim it!
                    field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
        cntfield.value = maxlimit - field.value.length;
}

/**************************************************
* Validate donation information being sent.  
***************************************************/
function check_donation(){

alert("Donation rewards aren't possible yet, I'm sorry.");

return false;
}

/**********************************
* Judges strength of user's password   
* and uses images to display results.      
***********************************/
var commonPasswords = new Array('password', 'pass', '1234', '1246'); 
var numbers = "0123456789"; 
var lowercase = "abcdefghijklmnopqrstuvwxyz"; 
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
var punctuation = "!.@$£#*()%~<>{}[]"; 
 
function checkpassword(password) { 
 
    var combinations = 0; 
 
    if (contains(password, numbers) > 0) { 
        combinations += 10; 
    } 
 
    if (contains(password, lowercase) > 0) { 
        combinations += 26; 
    } 
 
    if (contains(password, uppercase) > 0) { 
        combinations += 26; 
    } 
 
    if (contains(password, punctuation) > 0) { 
        combinations += punctuation.length; 
    } 
 
    // work out the total combinations 
    var totalCombinations = Math.pow(combinations, password.length); 
 
    // if the password is a common password, then everthing changes... 
    if (isCommonPassword(password)) { 
        totalCombinations = 75000 // about the size of the dictionary 
    } 
 
    // work out how long it would take to crack this (@ 200 attempts per second) 
    var timeInSeconds = (totalCombinations / 200) / 2; 
 
    // this is how many days? (there are 86,400 seconds in a day. 
    var timeInDays = timeInSeconds / 86400 
 
    // how long we want it to last 
    var lifetime = 365; 
 
    // how close is the time to the projected time? 
    var percentage = timeInDays / lifetime; 
 
    var friendlyPercentage = cap(Math.round(percentage * 100), 100); 
    if (totalCombinations != 75000 && friendlyPercentage < (password.length * 5)) { 
        friendlyPercentage += password.length * 5; 
    } 
 
    var progressbar = document.getElementById("progressbar"); 
    progressbar.style.width = friendlyPercentage + "%"; 
 
    if (percentage > 1) { 
        // strong password 
        progressbar.style.backgroundImage = "url(/images/strong.png)"; 
        return; 
    } 
 
    if (percentage > 0.5) { 
        // reasonable password 
        progressbar.style.backgroundImage = "url(/images/medium.png)";
        return; 
    } 
 
    if (percentage > 0.10) { 
        // weak password 
        progressbar.style.backgroundImage = "url(/images/weak.png)"; 
        return; 
    } 
 
    // useless password! 
    if (percentage <= 0.10) { 
        // weak password 
        progressbar.style.backgroundImage = "url(/images/weak.png)"; 
        return; 
    } 
 
 
} 
 
function cap(number, max) { 
    if (number > max) { 
        return max; 
    } else { 
        return number; 
    } 
} 
 
function isCommonPassword(password) { 
 
    for (i = 0; i < commonPasswords.length; i++) { 
        var commonPassword = commonPasswords[i]; 
        if (password == commonPassword) { 
            return true; 
        } 
    } 
 
    return false; 
 
} 
 
function contains(password, validChars) { 
 
    count = 0; 
 
    for (i = 0; i < password.length; i++) { 
        var char = password.charAt(i); 
        if (validChars.indexOf(char) > -1) { 
            count++; 
        } 
    } 
 
    return count; 
} 

/****************************************************
 * DHTML email validation script. Courtesy of                       
* SmartWebby.com (http://www.smartwebby.com/dhtml/)    
 ****************************************************/
function email_check(str) {

		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);

		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}

/**********************************************************
* Checks if the user submitted any special characters 
* during registration.                      
**********************************************************/
function check_for_bad_character(string_to_check){

var string_length = string_to_check.value.length;

for(count = 0; count < string_length; ++count)
   {
   switch(string_to_check.value.charAt(count))
         {
         case '!': 
         case "$":
         case '%':
         case '^':
         case '*':
         case '(':
         case ')':
         case '>':
         case '<':
         case '+':
         case '~':
         case ':':
         case "'":
         case '"':
         case ';':
         case ':':
         case ',':
         case '|':
         case '}':
         case '#':
         case '&':
         case '=':
                  return false;
         default:  
         }
   }

return true;
}

/**********************************************************
* Checks if data being submitted by user is valid.                           
**********************************************************/
function validate_registration(){

var register_form = document.getElementById("register_form");

var output = document.getElementById('output');

with(register_form) 
              {

                if (username.value == "") {
                    output.innerHTML = "Please enter your user name.";
                    return false;
                }
                if (username.value.length < 3) {
                    output.innerHTML = "Your user name needs to be at least 3 characters long.";
                    return false;
                }

                if(! check_for_bad_character(username)) {
                    output.innerHTML = "Your user name cannot contain any special characters.";
                    return false;  
                }

                if (username.value.length > 12) {
                    output.innerHTML = "Your user name is too long.";
                    return false;
                }

                if (password_1.value == "") {
                    output.innerHTML = "Please enter your password.";
                    return false;
                }
                if (password_2.value == "") {
                    output.innerHTML = "Please enter both passwords.";
                    return false;
                }
                if (password_2.value != password_1.value) {
                    output.innerHTML = "Passwords do not match.";
                    return false;
                }
                if (password_1.value.length > 30) {
                    output.innerHTML = "That password is too long.";
                    return false;
                }
                if (password_1.value.length < 6) {
                    output.innerHTML = "Your password needs to be at least 6 characters long.";
                    return false;
                }

                if(! check_for_bad_character(password_1)) {
                    output.innerHTML = "Your password cannot contain any special characters.";
                    return false;  
                }

                if (email.value == "") {
                    output.innerHTML = "Please enter your email address.";
                    return false;
                }
                if (email.value.length < 5) {
                    output.innerHTML = "Please enter a valid email address.";
                    return false;
                }
                if (email.value.length > 50) {
                    output.innerHTML = "That email address is too long.";
                    return false;
                }

                if(! email_check(email.value))
                  {
                  output.innerHTML = "The email seems to be in an incorrect format.";
                  return false;
                  }

                if(! check_for_bad_character(email)) {
                    output.innerHTML = "Your email address cannot contain any special characters, if this is a mistake by the validation system, please contact Ignis.";
                    return false;  
                }

               if(! check_for_bad_character(email)) {
                    output.innerHTML = "Your email address cannot contain any special characters, if this is a mistake by the validation system, please contact Ignis.";
                    return false;  
                }

               if (agreement.checked == false) {
                    output.innerHTML =  "You must check the Terms & Conditions box to register.";
                    return false;
               }
       }
                register_form.submit();
}
