function archive (id,cl) {
	if (confirm("Delete film from database and server?\nThis can not be undone.")) {
		window.location = (".?archiveFilm="+id+"&client_id="+cl);
	}
	return;
}


function confirmRemove (id,isAdmin) {
	var url;
	if (confirm("This profile will permanently be removed from the database, would you like to continue?")) {
		url = ".?remAcct="+id;
		if (isAdmin == "yes") url += "&admin=yes";
		window.location=(url);
	}
	return;
} 


function archiveClient (id) {
	if (confirm("Send to the archive?\nThis will hide the client account but not delete it.")) {
		window.location = (".?archiveClient="+id);
	}
	return;
}

function vmsHelp(id) {
	vmsHelpWindow=window.open("/myaccount/help/?id="+id,"vmsHelpWindow","width=400,height=400,left=0,top=0,resizable=no,scrollbars=no");
	vmsHelpWindow.focus();
}

function loginTO() {
	setCookie('bid3','');
	alert('Red Jet Films, your session has timed out');
	window.location = (".");
}
function logOut() {
	setCookie('bid3','');
	window.location = (".");
}
function expandCollapse() {
	for (var i=0; i<expandCollapse.arguments.length; i++) {
		var element = document.getElementById(expandCollapse.arguments[i]);
		element.style.display = (element.style.display == "none") ? "block" : "none";
	}
}

function uploadExpand(upfile) {
	if (upfile != '') expandCollapse('uploadStatus', 'on1');
}


//cookie function
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" +
((expires == null) ? "" : "; expires=" + expires.toGMTString());
}

function isDigit(num) {
	if (num.length>1){return false;}
	var string="1234567890";
	if (string.indexOf(num)!=-1){return true;}
	return false;
}

function isBlank(val){
	if(val==null){return true;}
	for(var i=0;i<val.length;i++) {
		if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){return false;}
		}
	return true;
}

function isInteger(val){
	if (isBlank(val)){return false;}
	for(var i=0;i<val.length;i++){
		if(!isDigit(val.charAt(i))){return false;}
		}
	return true;
}

function movieCheck(clientStr,expireStr){
	var alertMsg = '';
	if (clientStr == 'noClient' || isInteger(expireStr) == false){
		if (clientStr == 'noClient'){
			alertMsg+="In order to upload a film, please select a client from the client list.\n";
		}
		if (isInteger(expireStr) == false){
			alertMsg+="Please enter an integer for film expiration.\n";
		}
		alert(alertMsg);
		return false;
	}
	return true;
}

function emailCheck (emailStr,companyStr,firstNameStr,lastNameStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	var alertMsg = ' ';
	if(emailStr == '' || companyStr == '' || firstNameStr == '' || lastNameStr == ''){
		if (emailStr == ''){
			alertMsg+="Please enter an email address to complete account creation.\n";
		}
		if (companyStr == ''){
			alertMsg+="Please enter a company name complete account creation.\n";
		}
		if (firstNameStr == ''){
			alertMsg+="Please enter a first name to complete account creation.\n";
		}
		if (lastNameStr == ''){
			alertMsg+="Please enter a last name to complete account creation.\n";
		}
		alert(alertMsg);
		return false;
	}
	if (matchArray==null) {
		alert("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("Ths username contains invalid characters.");
			return false;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("Ths domain name contains invalid characters.");
			return false;
		}
	}
	if (user.match(userPat)==null) {
		alert("The username doesn't seem to be valid.");
		return false;
	}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!");
				return false;
			}
		}
		return true;
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("The domain name does not seem to be valid.");
			return false;
		}
	}
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}
	if (len<2) {
		alert("This address is missing a hostname!");
		return false;
	}
	return true;
}

function PeriodicalAjax(url, parameters, frequency, decay, onSuccess, onFailure) {
	function createRequestObject() {
		var xhr;
		try {
			xhr = new XMLHttpRequest();
		}
		catch (e) {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
		return xhr;
	}
	
	function send() {
		if(!stopped) {
			xhr.open('post', url, true);
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			xhr.onreadystatechange = function() { self.onComplete(); };
			xhr.send(parameters);
		}
	}
	
	this.stop = function() {
		stopped = true;
		clearTimeout(this.timer);
	}
	
	this.start = function() {
		stopped = false;
		this.onTimerEvent();
	}
	
	this.onComplete = function() {
		if(this.stopped) return false;
		if ( xhr.readyState == 4) {
			if(xhr.status == 200) {
				if(xhr.responseText == lastResponse) {
					decay = decay * originalDecay;
				} else {
					decay = 1;
				}
				lastResponse = xhr.responseText;
				if(onSuccess instanceof Function) {
					onSuccess(xhr);
				}
				this.timer = setTimeout(function() { self.onTimerEvent(); }, decay * frequency * 1000);
			} else {
				if(onFailure instanceof Function) {
					onFailure(xhr);
				}
			}
		}
	}
	
	this.getResponse = function() {
		if(xhr.responseText) {
			return xhr.responseText;
		}
	}
	
	this.onTimerEvent = function() {
		send();
	}
	
	var self = this;
	var stopped = false;
	var originalDecay = decay || 1.2;
	decay = originalDecay;
	var xhr = createRequestObject();
	var lastResponse = "";
	this.start();
}

function ProgressTracker(sid, options) {
	var startTime=new Date();
	var startSec=startTime.getTime();
	this.onSuccess = function(xhr) {
		if(parseInt(xhr.responseText) >= 100) {
			periodicalAjax.stop();
			if(options.onComplete instanceof Function) {
				options.onComplete();
			}
		} else if(xhr.responseText && xhr.responseText != lastResponse) {
			if(options.onProgressChange instanceof Function) {
				options.onProgressChange(xhr.responseText);
			}
			if(options.progressBar && options.progressBar.style) {
				var curTime=new Date();
				var curSec=curTime.getTime();
				var elapsed = ( curSec - startSec )/60000;
				if ( parseInt(xhr.responseText) > 0 ) var remaining = Math.round(elapsed/parseInt(xhr.responseText)*(100-parseInt(xhr.responseText)));
				else var remaining="n/a";
				elapsed = Math.round(elapsed);
				options.progressBar.style.width = parseInt(xhr.responseText) + "%";
				options.progressText.innerHTML = parseInt(xhr.responseText) + "%&nbsp;-&nbsp;elapsed:&nbsp;" + elapsed + "&nbsp;m&nbsp;-&nbsp;remaining:&nbsp;" + remaining + "&nbsp;m";
			}
		}
	}
	
	this.onFailure = function(xhr) {
		if(options.onFailure instanceof Function) {
			options.onFailure(xhr.responseText);
		} else {
			alert(xhr.responseText);
		}
		periodicalAjax.stop();
	}

	var self = this;
	var lastResponse = -1;
	options = options || {};
	var url = options.url || 'fileprogress.php';
	var frequency = options.frequency || 0.5;
	var decay = options.decay || 2;
	var periodicalAjax = new PeriodicalAjax(url, 'sid=' + sid, frequency, decay, function(request){self.onSuccess(request);},function(request){self.onFailure(request);});
}

function beginAsyncUpload(ul,sid) {
  var ext=ul.value;
  var ext=ext.substring(ext.length-4,ext.length)
  var pb = document.getElementById(ul.name + "_progress");
  frames['iframe_file'].location.href="/scripts/index.html";
  uploads_in_progress = 1;
  pb.parentNode.style.display='none';
  if ( ext == ".mov" || ext == ".wmv" || ext == ".mpg" || ext == "mpeg" || ext == ".avi" ) {
	  ul.form.submit();
		uploads_in_progress = uploads_in_progress + 1;
		var pt = document.getElementById(ul.name + "_progresstext");
		pb.parentNode.style.display='block';
		new ProgressTracker(sid,{
			progressBar: pb,
			progressText: pt,
			url: "/myaccount/films/fileprogress.php",
			onComplete: function() {
				var inp_id = pb.id.replace("_progress","");
				uploads_in_progress = 0;
				var inp = document.getElementById(inp_id);
				if(inp) {
					inp.value = sid;
				}
				pb.parentNode.style.display='none';
			},
			onFailure: function(msg) {
				pb.parentNode.style.display='none';
				alert(msg);
				uploads_in_progress = 0;
			}
		});
	} else {
		alert("Please choose a file in one of the following formats: mov, wmv, mpg, mpeg, avi.");
		ul.value = "";
	}
}

var uploads_in_progress = 0;

function uploadNow (frm) {
	var alertMsg="";
	if(uploads_in_progress > 0) {
		alertMsg+="File upload in progress. Please wait until upload finishes and try again.\n";
	}
	if (frm.clientSelect.value == 'noClient'){
		alertMsg+="In order to upload a film, please select a client from the client list.\n";
	}
	if (isInteger(frm.ttl.value) == false){
		alertMsg+="Please enter an integer for film expiration.";
	}
	if ( alertMsg == "" ) frm.submit();
	else alert(alertMsg);
}

