var CategoryID = "0";
var CategoryName = "";
var BaseUrl = ""; 
var CancelUpload = false;
var UploadInProgress = false;
var Errors = null;

function IsCategory()
{
	var combo = document.getElementById(CategoryListId);
	var textBox = document.getElementById(NewCategoryId);
	var res = true;
	if (combo.value == "new" && textBox.value == "") {
		res = false;
		textBox.focus();
	}
	return res;
}

function SetSelectedCount()
{
	var selectedCount = JamShellListX.SelCount;
	JamSelectImages.innerHTML = selectedCount;
	upload = deselect = (selectedCount > 0);
	ButtonSetEnabled(ButtonUploadId, upload);
	ButtonSetEnabled(ButtonUnSelectId, deselect);
}

function ButtonSetEnabled(buttonId, state) {
	button = document.getElementById(buttonId);
	state ? enableButton(button) : disableButton(button);
}

function SetMaxCount(count, progressBarId) {
	
}

function SetWidth(width, progressBarId) {
	
}

var CurrentUploadingIndex;
var TotalImagesUploading;
var FileToUpload;

function StartUpload()
{
	Errors = null;
	CancelUpload = false;
	UploadInProgress = true;
	CurrentUploadingIndex = 0;

	var res = GetSelectedResolution();
	var cat = GetCategoryParam();
	FileUploader.MaxWidth = res.Width;
	FileUploader.MaxHeight = res.Height;
	CategoryID = cat.ID;
	CategoryName = cat.Name;
	
	TotalImagesUploading = JamShellListX.SelCount;
	if (TotalImagesUploading <= 0) {
		alert(SbGetLocaleByKey('NO-IMAGES-SELECTED'));
		return;
	}

	SetMaxCount(TotalImagesUploading, ProgressBarId);
	SetWidth(0, ProgressBarId);

	var from = document.getElementById(FromFileCountId);
	from.innerHTML = TotalImagesUploading;
	FileToUpload = JamShellListX.getSelectedItems();

	HideModalBoxControl(MultipleUploadDialogId);
	// From here on no one should access JamShellListX object as it was destoryed
	// when it was assigned display:none style
	ShowModalBoxControl(StatusUploadDialogId);
	SwitchStatusToError(false);
	
	UpdateUploadStatus(0);
	UploadFileAsync(CurrentUploadingIndex);
}

function shorten(str, len) {
	if (str.length <= len) {
		return str;
	}

	// try to extract basename
	parts = str.split(/\\|\//);
	str = parts[parts.length-1];

	// still too long?
	if (str.length > len) {
		str = "..." + str.substring(str.length-len-3);
	}
	return str;
}

function UpdateUploadStatus(index) {
	var uploaded = document.getElementById(UploadetFileCountId);
	var left = document.getElementById(FileLeftCountId);
	var file = document.getElementById(FileNameId);
	var from = document.getElementById(FromFileCountId);
	var fileName = "";

	if (index < FileToUpload.length) {
		fileName = FileToUpload[index];
	}

	uploaded.innerHTML = index;
	left.innerHTML = TotalImagesUploading - index;
	file.innerHTML = shorten(""+fileName, 40);
	from.innerHTML = TotalImagesUploading;
	UpdateStatus(index/TotalImagesUploading, ProgressBarId);
}

function UploadFinished(file, _javaStatus) {
	status = parseInt(""+_javaStatus);
	if (status == 6) {
		CancelUpload = true;
	}
	if (CancelUpload) return;

	if (status > 0) {
		if (Errors == null) { 
			Errors = new Array();
		}
		var er = new Object();
		er.FileName = file;
		er.Status = status;
		Errors.push(er);
	}
	else {
		//remove any files that has been successfully uploaded
		FileToUpload[CurrentUploadingIndex] = null;
		if (CategoryID == "0" && CategoryName != null)	{
			//Ok, this hack is to convert FileUploader.ResponseText which is 
			//java.lang.String to pure js string. Otherwise GetCategoryIdFromResponseText
			//fails with java exception while calling split()
			text=""+FileUploader.ResponseText;
			CategoryID = GetCategoryIdFromResponseText(text);
			CategoryName = null;
		}
	}
	++CurrentUploadingIndex;
	UpdateUploadStatus(CurrentUploadingIndex);
	if (CurrentUploadingIndex < TotalImagesUploading){
		UploadFileAsync(CurrentUploadingIndex);
	}
	else {
		UploadInProgress = false;
		if (Errors == null)	{
			MakePostBack();
		}
		else {
			SwitchStatusToError(true, TotalImagesUploading, Errors.length);
			SetErrorMessages();
			//SetSelectedCount();
		}
	}
}

function UploadFileAsync(index) {
	var fileName = FileToUpload[index];
	var foo = BaseUrl + "&categoryId=" + CategoryID;
	if (CategoryName != null) {
		foo += "&categoryName=" + encodeURI(CategoryName);
	}
	FileUploader.UploadURL = foo;
	FileUploader.FileName = fileName;
	FileUploader.SendRequestAsync();
}

function CancelUploadFiles()
{
	CancelUpload = true;
	UploadInProgress = false;
	FileUploader.cancel();

	HideModalBoxControl(StatusUploadDialogId);
	ShowModalBoxControl(MultipleUploadDialogId);
}

function HideModalBoxControl(dialogId) {
	document.getElementById(dialogId).hide();
}

function ShowModalBoxControl(dialogId) {
	document.getElementById(dialogId).show();
}

function UpdateStatus(status, progressBarId) {
	sbProgressBar._setStatus(status);
}

function SetErrorMessages()
{
	var errorLabelId = document.getElementById(ErrorLabelId);
	var status1 = 0;
	var status2 = 0;
	var status3 = 0;
	for (var i = 0; i < Errors.length; i++)
	{
		switch (Errors[i].Status)
		{
			case 1:
				status1++;
				break;
			case 2:
				status2++;
				break;
			case 3:
				status3++;
				break;
		}
	}
	var str = "";
	if (status1 > 0)
	{
		str += SbGetLocaleByKey("FILE-NOT-FOUND") + "&nbsp;(" + status1 +")<br/>";
	}
	if (status2 > 0)
	{
		str += SbGetLocaleByKey("CANNOT-RESIZE-FILE") + "&nbsp;(" + status2 +")<br/>";
	}
	if (status3 > 0)
	{
		str += SbGetLocaleByKey("HTTP-ERROR") + "&nbsp;(" + status3 +")<br/>";
	}
	str += SbGetLocaleByKey('FURIOUS-ERROR-MESSAGE');
	errorLabelId.innerHTML = str;
}

function SetCaption(dialogId, caption) {
	var dialog = document.getElementById(dialogId);
	dialog.setTitle(caption);
}

function SwitchStatusToError(error, count, failed)
{
	var bar = document.getElementById(ProgressBarId);
	var upload = document.getElementById(UploadetFileCountId);
	var from = document.getElementById(FromFileCountId);
	var left = document.getElementById(FileLeftCountId);
	var fileName = document.getElementById(FileNameId);
	var errorImage = document.getElementById(ErrorImageId);
	var progressImage = document.getElementById(ProgressImageId);
	var panelErrors = document.getElementById(PanelErrorsId);
	var panelPBId = document.getElementById(PanelPBId);
	var panelFileNameId = document.getElementById(PanelFileNameId);
	var errorLabelId = document.getElementById(ErrorLabelId);
	var panelProgressButtonsId = document.getElementById(PanelProgressButtonsId);
	var panelErrorButonsId = document.getElementById(PanelErrorButonsId);
	if (error == true)
	{
		SetCaption(StatusUploadDialogId, SbGetLocaleByKey("ALERT"));
		upload.innerHTML = count - failed;
		from.innerHTML = count;
		left.innerHTML = failed;
		errorImage.style.display = "block"; 
		progressImage.style.display = "none";
		
		panelErrors.style.display = "inline";
		panelPBId.style.display = "none";
		
		panelFileNameId.style.display = "none";
		panelProgressButtonsId.style.display = "none";
		panelErrorButonsId.style.display = "inline";
	}
	else
	{
		SetCaption(StatusUploadDialogId, SbGetLocaleByKey('PROGRESS'));
		upload.innerHTML = "0";
		from.innerHTML = count;
		left.innerHTML = count;
		errorImage.style.display = "none";
		progressImage.style.display = "block";
		
		panelErrors.style.display = "none";
		panelPBId.style.display = "inline";
		
		panelFileNameId.style.display = "inline";
		panelProgressButtonsId.style.display = "inline";
		panelErrorButonsId.style.display = "none";
	}
}

function RetryUpload()
{
	SwitchStatusToError(false);

	Errors = null;
	CancelUpload = false;
	UploadInProgress = true;
	CurrentUploadingIndex = 0;
	//Array.compact is from prototype
	FileToUpload = FileToUpload.compact();

	TotalImagesUploading = FileToUpload.length;
	if (TotalImagesUploading <= 0) {
		alert(SbGetLocaleByKey('NO-IMAGES-SELECTED'));
		return;
	}

	SetMaxCount(TotalImagesUploading, ProgressBarId);
	SetWidth(0, ProgressBarId);

	var from = document.getElementById(FromFileCountId);
	from.innerHTML = TotalImagesUploading;
	SwitchStatusToError(false);
	UpdateUploadStatus(0);
	UploadFileAsync(CurrentUploadingIndex);
}

function GetCategoryIdFromResponseText(text)
{
	var res = "0";
	try {
		var temp = text.split("[ID:");
		var temp1 = temp[1].split("]");
		res = temp1[0];
	}
	catch(e){}
	return res;
}

function GetCategoryParam()
{
	var res = new Object();
	try
	{
		var combo = document.getElementById(CategoryListId);
		var ID = combo.value;
		if (ID == "0") {
			//No category
			res.ID = "0";
			res.Name = null;
		}
		else if (ID == "new") {
			//New category
			var el = document.getElementById(NewCategoryId);
			res.ID = "0";
			res.Name = el.value;
		}
		else {
			//Existing category
			res.ID = ID;
			res.Name = null;
		}
	}
	catch(e)
	{
		res.ID = "0";
		res.Name = null;
	}
	return res;
}

function GetSelectedResolution()
{
	var res = new Object();
	try
	{
		var combo = document.getElementById(ResizeResolutionId);
		var value = combo.value;
		var par = new Array();
		par = value.split("|");
		res.Width = par[0];
		res.Height = par[1];
	}
	catch(e)
	{
		res.Width = "100000";
		res.Height = "100000";
	}
	return res;
}

function ControlsInit()
{
	JamShellTreeX.RootedAt = 3;
	JamShellTreeX.BorderStyle = 0;
	JamShellTreeX.ShellLink = JamShellLinkX;
	JamShellTreeX.ShowFiles = false;
	JamShellTreeX.ShowRecycleBin = false;
	JamShellTreeX.FileSystemOnly = true;	
	JamShellListX.ShellLink = JamShellLinkX;
	JamShellListX.Filter = '*.jpg;*.jpeg;*.gif;*.png;*.bmp';
	JamShellListX.ShowFolders = false;
	JamShellListX.BorderStyle = 0;
	JamShellListX.Thumbnails = true;	
	JamShellComboX.ShowFiles = false;
	JamShellComboX.ShowRecycleBin = false;
	JamShellComboX.FileSystemOnly = true;
	JamShellComboX.SelCount
	JamShellComboX.ShellLink = JamShellLinkX;

	var combo = document.getElementById(CategoryListId);
	var textBox = document.getElementById(NewCategoryId);

	textBox.style.display = (combo.value  == "new" ? "block" :"none");

	try
	{
		JamShellComboX.focus();
		JamShellTreeX.focus();
		JamShellListX.focus();
	}
	catch(e){}
}

function SelectCategory(comboBox, eventArgs)
{
	var category = comboBox.Value;
	var textBox = document.getElementById(NewCategoryId);

	textBox.style.display = (category == "new" ? "block" :"none");
	if (category == "new") {
		textBox.value = "";
	}
}

