function go_to_top() {

    // go to the top of the window
    window.location = "#" + "top"
}

function go_to_tool() {

    // go to the start of the actual tool
    window.location = "#" + "tool_start"
}


function waitPreloadPage() { //DOM

	// PreLoad Wait - Script 
	// This script and more from http://www.rainbow.arch.scriptmania.com 

	if (document.getElementById){
		document.getElementById('prepage').style.visibility='hidden';
	}
	else{
		if (document.layers){ //NS4
			document.prepage.visibility = 'hidden';
		}
		else { //IE4
			document.all.prepage.style.visibility = 'hidden';
		}
	}
}

function calc()	{

		var x,y

		for(x=0;x<300000;x++) {
			y += (x * y) / (y - x);			
		}
}

function get_prefix(input,upto_char) {

	// Returns the first characters of a string up to the specified character. 

	return eval("input.substring(0,input.indexOf('" + upto_char + "'))")
}

function convert_special_chars(input) {

	// Go through the text area and convert and carriage returns to <BR> and any double-quotes to "'".
	
	var output = ""
	
	for (var i = 0; i < input.length; i++) {
		if ((input.charCodeAt(i) == 13) && (input.charCodeAt(i + 1) == 10)) {
			i++
			output += "<BR>"
		} 
		else if (input.charCodeAt(i) == 34){
			output += "'"
		}
		else {
			output += input.charAt(i)
 		}
	}
	
	return output
}

function check_if_empty(tutor_form) {
    
    // Loop through all the form elements
    for (var counter = 0; counter < tutor_form.length; counter++) {
    	
    	// Is this a visible text field?
        if ((tutor_form[counter].type == "text" || 
        	 tutor_form[counter].type == "textarea" || 
        	 tutor_form[counter].type == "password") &&
        	(tutor_form.elements[counter].name != "other_business_category" && 
        	 tutor_form.elements[counter].name != "other_business_concern")) {
        	 
       		if (tutor_form[counter].value == "") {
           		return true
            }
        }
    }
}

function its_a_digit(input_name,character) {

    var digit_characters = "0123456789,"
    
    // Allow the "." character where a field can have decimal places.
    
    if (input_name == "gross_margin_rate" ||
    	input_name == "gp_margin" || 
    	input_name == "baseline_cost_price" || 
    	get_prefix(input_name,"_") == "grossmargin" ||
    	get_prefix(input_name,"_") == "effrate" ||
    	get_prefix(input_name,"_") == "rate") {
    		digit_characters = digit_characters + "."
	}

    // If it's not in the digit_characters string, then it's not a digit so return false
    if (digit_characters.indexOf(character) == -1) {
        return false
    }
    return true
}

function its_integer(input_name,input_value) {

    for (var counter = 0; counter < input_value.length; counter++) {
        current_char = input_value.charAt(counter)
        if (!its_a_digit(input_name,current_char)) {
            return false
        }
    }
    return true
}

function its_a_letter(character) {

    var lowercase_letters = "abcdefghijklmnopqrstuvwxyz"
    var uppercase_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    // If it's not in the lowercase_letters string or the
    // uppercase_letters string, then it's not a letter, 
    // so return false
    
    if (lowercase_letters.indexOf(character) == -1 &&
        uppercase_letters.indexOf(character) == -1) {
        return false
    }
    
    // Otherwise, it's a letter, so return true
    return true
}

function its_alphabetic(string_value) {

    // Run through each character in the string
    for (var counter = 0; counter < string_value.length; counter++) {
        
        // Get the current character
        current_char = string_value.charAt(counter)
        
        // If it's not a letter, return false
        if (!its_a_letter(current_char)) {
            return false
        }
    }
    
    // Otherwise, the string has nothing but
    // alphabetic characters, so return true
    return true
}

function actual_reset_value(id,orig_value) {        
	
	var control = document.getElementById(id)
	
	// for some reason, an empty string comes out as "".  If this happens then we need to ensure the
	// field value is set to an empty string.

	if (orig_value == '""') {
		control.value = ""      
	}
	else {
		control.value = orig_value
	}
	
	// Now we put the cursor back into the field the user was trying to change.
	control.focus()
}

function reset_value(current_field,orig_value) {

	// The setTimeout overcomes a bug in Internet Explorer where the it won't put the cursor into
	// field you want.
	var converted_string = orig_value.toString()
	setTimeout("actual_reset_value('" + current_field.id + "','" + converted_string + "')",1)
}

function reset_table(current_form) {

	// Cycle through all form fields that are "text" areas and reset them back to blank.  Note that
	// we need to exclude the header fields and the month and year headings for the six month tutor.
 
	var total_fields  = current_form.elements.length
	var confirm_reset = confirm("Are you sure want to clear all values in the table below?")
	
	if (confirm_reset == true) {
		for (counter = 0; counter < total_fields; counter++) {
			if (current_form.elements[counter].type == "text") {
				if (current_form.elements[counter].name != "company_name" && 
				    current_form.elements[counter].name != "start_month"  &&
				    current_form.elements[counter].name != "report_date"  && 
				    current_form.elements[counter].name.substr(0,4) != "year" &&
				    current_form.elements[counter].name.substr(0,5) != "month") {
   				    	current_form.elements[counter].value = ""
				}
			}
		}
	}

	// Set the target_stock_mix from the inventory_sales calculator to its default value.
	// Set the product names back to their defaults as well.

	if (current_form.name == "invsales_form") {
		current_form.target_stock_mix.value = "6"
		current_form.product_1.value		= "            A"
		current_form.product_2.value		= "            B"
		current_form.product_3.value		= "            C"
		current_form.product_4.value		= "            D"
		current_form.product_5.value		= "            E"
		current_form.product_6.value		= "            F"
		current_form.product_7.value		= "            G"
		current_form.product_8.value		= "            H"
		current_form.product_9.value		= "            I"
		current_form.product_10.value		= "            J"
	}
}

function formatnumber(num,dec) {

	// Add a comma in to separate thousands and add the required number of decimal places.
	
	var x = Math.round(num * Math.pow(10,dec))
	var neg = ""
	
	if (x < 0) { neg = "-" }
	
	var y = (''+Math.abs(x)).split('')
	var z = y.length - dec
	
	y.splice(z, 0, '.')
	
	while (z > 3) {
		z-=3
		y.splice(z,0,',')
	}
	
	var r = neg+y.join('')
	return r
}

function add_commas(num) {

	// Need to strip any commas here in case the user has changed the number eg. 1,234 to 1,25. 
	// We are trying to ensure that "num" is always a number.
	
	if (num.toString().indexOf(",") != -1) {
		num = del_commas(num)
	}
	
	if (num >= 1000 || num <= -1000) {
        
        // Work with the absolute value
        var number_string = Math.abs(num).toString()
        var insert_position
 
        // Calculate the position of the first comma
        switch (number_string.length % 3) {
            case 1 :
                insert_position = 1
                break
            case 2 :
                insert_position = 2
                break
            case 0 :
                insert_position = 3
                break
        }
        
        while (insert_position < number_string.length) {
            number_string = number_string.left(insert_position) + "," + 
                            number_string.substring(insert_position)
            insert_position += 4
        }
        
        // If the original number was negative, tack on the minus sign
        if (num < 0) {
            return "-" + number_string
        }
        else {
            return number_string
        }
    }
    else {
    
        // If the number is between -1000 and 1000, just return it
        return num.toString()
    }
}

function del_commas(num_string) {
	
	// remove any commas from the string
	var output_num = ""
	
	// check whether a "," exists or not
	if (num_string.indexOf(",") != -1) {
		for (var i = 0; i < num_string.length; i++) {
			if (num_string.charAt(i) != ",") {
				output_num = output_num + num_string.charAt(i)
			}
		}
		return output_num 
	}
	else {
		return num_string
	}
}

function round_decimals(original_number, decimals) {
    
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string & locate the decimal point.
    var value_string = rounded_value.toString()
    var decimal_location = value_string.indexOf(".")

    // Decide whether to tack on a decimal point or pad decimal places with zeros
    if (decimal_location == -1) {
        decimal_part_length = 0
        value_string += decimal_places > 0 ? "." : ""
    }
    else {
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

function GetDay(nDay)
{
	var Days = new Array("Sunday","Monday","Tuesday","Wednesday",
	                     "Thursday","Friday","Saturday");
	return Days[nDay]
}

function GetMonth(nMonth)
{
	var Months = new Array("January","February","March","April","May","June",
	                       "July","August","September","October","November","December");
	return Months[nMonth] 	  	 
}

function date_to_string(input_date) {

	// Convert a date into a string for nice display
	
	var suffix = "th"
	switch (input_date.getDate())
	{
		case 1:
		case 21:
		case 31: 
			suffix = "st"
			break
		case 2:
		case 22:
			suffix = "nd"; break;
		case 3:
		case 23:
			suffix = "rd"; break;
	}

	var strDate = GetDay(input_date.getDay()) + ", " + input_date.getDate();
	strDate += suffix + " " + GetMonth(input_date.getMonth()) + " " + input_date.getYear();
	return strDate
}

function timestring() {
	
	var time = new Date()
    var hr = time.getHours()
    var min = time.getMinutes()
    var sec = time.getSeconds()
    var ampm = " PM"
  
    if (hr < 12){
    	ampm = " AM"
    }
  	if (hr > 12){
    	hr -= 12
    }
  	if(min < 10){
    	min = "0" + min
    }
  	if(sec < 10){
    	sec = "0" + sec
    } 
  
  	return hr + ":" + min + ":" + sec + ampm
}

function addWorkingDays(myDate,days) { 

	//myDate = starting date, days = no. working days to add.

	var temp_date = new Date()
	var i = 0
	var days_to_add = 0
	
	while (i < (days)){
		temp_date = new Date(myDate.getTime() + (days_to_add*24*60*60*1000))
		//0 = Sunday, 6 = Saturday, if the date not equals a weekend day then increase by 1
		if ((temp_date.getDay() != 0) && (temp_date.getDay() != 6)){
			i+=1
		}
		days_to_add += 1
	}
	return new Date(myDate.getTime() + days_to_add*24*60*60*1000)
}

function valid_email(email_address) {

    // Check the length
    if (email_address.length < 5) {
        return false
    }
    
    // Check @ and .
    at_location = email_address.indexOf("@")
    dot_location = email_address.lastIndexOf(".")
    
    if (at_location == -1 || dot_location == -1 || at_location > dot_location ) {
        return false
    }

    // Is there at least one character before @?
    if (at_location == 0) {
        return false
    }
    
    // Is there at least one character between @ and .?
    if (dot_location - at_location < 2 ) {
        return false
    }

    // Is there at least one character after .?
    if (email_address.length - dot_location < 2) {
        return false
    }

    // Otherwise, it's a valid address, so return true
    return true
}

function extract_left(total_chars) {
    return this.substring(0, total_chars)
}

String.prototype.left = extract_left

function xxxxformatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {

// number formatting function
// copyright Stephen Chapman 24th March 2006
// permission to use this function is granted provided
// that this copyright notice is retained intact

	var x = Math.round(num * Math.pow(10,dec))
	
	if (x >= 0) n1=n2=''
	
	var y = (''+Math.abs(x)).split('')
	var z = y.length - dec
	
	y.splice(z, 0, pnt)
	
	while (z > 3) {
		z-=3
		y.splice(z,0,thou)
	}
	
	var r = curr1+n1+y.join('')+n2+curr2
	return r
}
