function $(o) 
{
	// a jquery-like function, a shortcut to document.getElementById
    return document.getElementById(o);
}

function init() 
{
	
	var sPath = window.location.pathname;
	if ( sPath.indexOf("cgi-bin") != -1)
	{
		return;
	}

	document.getElementsByTagName('sessid');
	// Init script called on page load
    // Make up a session ID.
    var hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
               "A", "B", "C", "D", "E", "F"];
    var ses = "";

    for (var i = 0; i < 16; i++) 
	{
        var rnd = Math.floor(Math.random() * 16);
        ses += hex[rnd];
    }


    $("sessid").value = ses;

    // we set the form action to send the sessid in the query string, too.
    // this way it's available inside the CGI hook function in a very easy
    // way. In real life this would probably be done better.
	$("theform").action += "?" + ses;

}


//window.onload = init;

function basename(path) 
{
	return path.replace(/\\/g, '/').replace(/.*\//, '');
}

function bytesToSize(bytes, precision)
{  
    var kilobyte = 1024;
    var megabyte = kilobyte * 1024;
    var gigabyte = megabyte * 1024;
    var terabyte = gigabyte * 1024;
   
    if ((bytes >= 0) && (bytes < kilobyte)) {
        return bytes + ' B';
 
    } else if ((bytes >= kilobyte) && (bytes < megabyte)) {
        return (bytes / kilobyte).toFixed(precision) + ' KB';
 
    } else if ((bytes >= megabyte) && (bytes < gigabyte)) {
        return (bytes / megabyte).toFixed(precision) + ' MB';
 
    } else if ((bytes >= gigabyte) && (bytes < terabyte)) {
        return (bytes / gigabyte).toFixed(precision) + ' GB';
 
    } else if (bytes >= terabyte) {
        return (bytes / terabyte).toFixed(precision) + ' TB';
 
    } else {
        return bytes + ' B';
    }
}

function validate()
{


	setTimeout("validateForm()",500);

}


function filecheck()
{


	setTimeout("updateFileCheckLoaderStart()",50);
	setTimeout("filecheckForm()",500);

}


function updateLoaderStart() 
{

	document.getElementById("val_status").value = "Checking Email ... Please wait";
    document.getElementById("loader").style.display = "block";
	
	return false;

}

function updateFileCheckLoaderStart() 
{

	document.getElementById("val_status").value = "File Check ... Please wait";
    document.getElementById("loader").style.display = "block";
	
	return false;

}


function updateLoaderStop() 
{
    document.getElementById("loader").style.display = "none";

	document.getElementById("val_status").value = "";
	
	return false;

}
function validateForm() 
{
	init();
	var isIE6 = (navigator.userAgent.toLowerCase().substr(25,6)=="msie 6") ? true : false;
	if ( isIE6 )
	{
		alert("Internet Explorer 6 is not supported");
		return false;
	}
	theForm = document.getElementById("theform");
	
	file = document.getElementById("savename").value;
	
	file=ascii127(file);
	file=file.replace(/[(|)|&|,|;|$|%|@|"|<|>|\*|'|?|\[|\]]/g, "_");
    file=file.replace(/ /g,"_");
	

	document.getElementById("savename").value = file;

    //Change email case to lower case
    
    theForm.from_email.value = theForm.from_email.value.toLowerCase();
    theForm.to_email.value = theForm.to_email.value.toLowerCase();

	// Request to update refering page

	if (!validEmail(theForm.from_email, "From email address", true)) 
	{
		return false;
	}

	if (!validEmail(theForm.to_email, "To email address", true)) 
	{
		return false;
	}

	if (!validRequired(theForm.filename, "Local Filename")) 
	{
		return false;
	}

	  if (!validRequired(theForm.savename, "Remote Filename")) 
	{
		return false;
	}
	
	
 
	setTimeout("updateLoaderStart()",50);
	
    var oRequest = new XMLHttpRequest();
	var sURL = "/cgi-bin/xfer_upload.cgi?do=validate&to_email=" + theForm.to_email.value + "&from_email=" + theForm.from_email.value +"&savename=" + theForm.savename.value + "&sessid="+ theForm.sessid.value;
	
    oRequest.open("GET", sURL, false);
    oRequest.setRequestHeader("User-Agent", navigator.userAgent);
	oRequest.send(null);
	

    var parts = oRequest.responseText.split(":");
	var result = false;
	var file_result = false;
	var email_result = false;
	
	if ( parts[0] == "sessid" && parts[1] == theForm.sessid.value )
	{
	
		// Email Fails LDAP Validation
		if ( parts[2] == "email" && parts[3] == "false" )
		{
			alert("At least one of the email addresses entered must be a valid Avnet individual email address. No matches were found.");
	        theForm.to_email.focus();
			document.getElementById("validemail").value = 0;
		    email_result = false;
		}
		else if ( parts[2] == "email" && parts[3] == "true" )
		{
			document.getElementById("validemail").value = 1;
			document.getElementById("val_status").value = "Email Passed Check";
			email_result = true;
		}

		// File Exists on server
		if ( parts[4] == "file" && parts[5] == "false" )
		{
			var alert_message = theForm.savename.value  + ' already exists on the XFER server. Please change ' +  theForm.savename.value + ' to a different name and press \"Upload File\".';
			alert(alert_message);
			
			theForm.filename.focus();
			file_result = false;
		}
		else if ( parts[4] == "file" && parts[5] == "true" )
		{
			file_result = true;

		}

	}
	else
	{
		alert("Session Error");
		theForm.to_email.focus();
		result = false;
	}


	if  ( email_result === true && file_result === true)
	{
		result = true;
		document.getElementById('upload_submit').click();
	}
	setTimeout("updateLoaderStop()",5);

	return result;
}

function filecheckForm() 
{
	
	theForm = document.getElementById("theform");

	// Request to update refering page

	if (!validEmail(theForm.from_email, "From email address", true)) 
	{
		return false;
	}

	if (!validEmail(theForm.to_email, "To email address", true)) 
	{
		return false;
	}

	if (!validRequired(theForm.filename, "Local Filename")) 
	{
		return false;
	}

	  if (!validRequired(theForm.savename, "Remote Filename")) 
	{
		return false;
	}
	
	
	document.getElementById("validemail").value = 1;
    var oRequest = new XMLHttpRequest();
	var sURL = "/cgi-bin/xfer_upload.cgi?do=filecheck&to_email=" + theForm.to_email.value + "&from_email=" + theForm.from_email.value +"&savename=" + theForm.savename.value + "&sessid="+ theForm.sessid.value;
	
    oRequest.open("GET", sURL, false);
    oRequest.setRequestHeader("User-Agent", navigator.userAgent);
	oRequest.send(null);
	

    var parts = oRequest.responseText.split(":");
	var result = true;
	
	if ( parts[0] == "sessid" && parts[1] == theForm.sessid.value )
	{
	
		// File Exists on server
		if ( parts[4] == "file" && parts[5] == "false" )
		{
			var alert_message = theForm.savename.value  + ' already exists on the XFER server. Please change ' +  theForm.savename.value + ' to a different name and press \"Upload File\".';
			alert(alert_message);
			
			theForm.filename.focus();
			result = false;
		}
	}
	else
	{
		alert("Session Error");
		theForm.to_email.focus();
		result = false;
	}


	if  ( result === true )
	{
		document.getElementById('upload_submit').click();
	}
	setTimeout("updateLoaderStop()",5);
	return result;
}

function ping() 
{
	// Request to update refering page

    var oRequest = new XMLHttpRequest();
    var sURL = "/cgi-bin/xfer_upload.cgi?do=ping&sessid=" + $("sessid").value;

    oRequest.open("GET", sURL, false);
    oRequest.setRequestHeader("User-Agent", navigator.userAgent);
    oRequest.send(null);

    setTimeout("ping()", 5);

    var parts = oRequest.responseText.split(":");

    if (parts.length == 3) 
	{
		if  ( $("received").innerHTML != null )
		{
			$("received").innerHTML = bytesToSize(parts[0],2);
			$("total").innerHTML = bytesToSize(parts[1],2);
			$("percent").innerHTML = parts[2];
			$("bar").style.width = parts[2] + "%";
		}
    }

	if (parts[2] == 100)
	{

        $("upload_status").innerHTML = "Calculating checksum ... Please wait";
	}

}

function isEmailAddr(email) 
{
    var result = false;
    var theStr = email;
    var index = theStr.indexOf("@");
    if (index > 0) 
	{
        var pindex = theStr.indexOf(".", index);
        if ((pindex > index + 1) && (theStr.length > pindex + 1)) 
		{
			result = true;
		}
    }
    return result;
}

function validRequired(formField, fieldLabel) 
{
    var result = true;

    if (formField.value  === "") 
	{
        alert('Please enter a value for the "' + fieldLabel + '" field.');
        formField.focus();
        result = false;
    }

    return result;
}

function validEmail(formField, fieldLabel, required) 
{
    var result = true;

    if (required && !validRequired(formField, fieldLabel)) 
	{
		result = false;
	}

    if (result && ((formField.value.length < 3) || !isEmailAddr(formField.value))) 
	{
        alert("Please enter a complete email address in the form: yourname@yourdomain.com");
        formField.focus();
        result = false;
    }

    return result;
}

function setSaveName(checked)
{
	if ( checked == "on" ) 
	{
		document.getElementById("savename").value = basename(document.getElementById("filename").value);
	}
	else
	{

		document.getElementById("savename").value = "";
	}
}

function copySaveName(file)
{
	file = ascii127(file);

	file=file.replace(/[(|)|&|,|;|$|%|@|"|<|>|\*|'|?|\[|\]]/g, "_");
	file=file.replace(/ /g,"_");

	var copy_name = document.getElementById("savename").value = basename(file);
	
}

function ascii127 ( in_string )
{
	var i = 0;
	var c = 0;
	var out_string = "";

	while ( i < in_string.length ) 
	{
		c = in_string.charCodeAt(i);
		
		if (c > 127 ) 
		{
			if ( c > 127 & c < 192 )
			{
				//?
				c = 63; 
			}

			if ( c > 191 & c < 199 )
			{
				//A
				c = 65;
			}
			
			if ( c == 199  ) 
			{
				//C
				c = 67;
			}
			if ( c > 199 & c < 204 )
			{
				//E
				c = 69;
			}

			if ( c > 203 & c < 208 )
			{
				//I
				c = 73;
			}

			if ( c == 208 ) 
			{
			    //D
				c = 68;
			}

			if ( c == 209 ) 
			{
			    //N
				c = 78;
			}
			
			if ( c > 209 & c < 215 ) 
			{
				//O
				c = 79;
			}

			if ( c == 215 ) 
			{
			    //x
				c = 120;
			}

			if ( c == 216 ) 
			{
			    //O
				c = 79;
			}

			if ( c > 216 & c < 221 ) 
			{
				//U
				c = 85;
			}

			if ( c == 221 ) 
			{
			    //Y
				c = 89;
			}

			if ( c == 222 ) 
			{
			    //p
				c = 112;
			}

			if ( c == 223 ) 
			{
			    //B
				c = 66;
			}

			if ( c > 223 & c < 231 ) 
			{
				//a
				c = 97;
			}

			if ( c == 231 ) 
			{
			    //c
				c = 99;
			}

			if ( c > 231 & c < 236 ) 
			{
				//e
				c = 101;
			}

			if ( c > 235 & c < 240 ) 
			{
				//i
				c = 105;
			}

			if ( c == 240 ) 
			{
			    //?
				c = 95;
			}
			
			if ( c == 241 ) 
			{
			    //n
				c = 110;
			}

			if ( c > 241 & c < 249 ) 
			{
				//o
				c = 111;
			}
			
			if ( c > 248 & c < 253 ) 
			{
				//u
				c = 117;
			}

			if ( c == 254 ) 
			{
			    //p
				c = 112;
			}

			if ( c == 253 | c == 255 ) 
			{
			    //y
				c = 121;
			}

			if ( c > 255 )
			{
				//_
				c = 95; 
			}

		}
		out_string += String.fromCharCode(c);
		i++;
	}
	return out_string;

}

function startUpload(theForm) 
{

	document.getElementById("val_status").value = "";
	// Hide the form.
    $("upload-form").style.display = "none";
    // Display the progress bar
    $("progress-div").style.display = "block";

    // Begin making ajax requests.
    setTimeout("ping()", 5);
    

    // Allow the form to continue submitting.
    return true;
}


