/// <reference name="MicrosoftAjax.debug.js" />

var uploadWhere = -1;
// 0 = UserProfileImage
// 1 = Access Card Image
// 2 = Classifieds Images
// 3 = Directory Images
// 4 = Directory Logo
var imgsArray = new Array();

function fileDialogStart_UserProfile()
{
	uploadWhere = 0;
	imgsArray = new Array();
}
function fileDialogStart_Classifieds()
{
	uploadWhere = 2;
	imgsArray = new Array();
}
function fileDialogStart_DirectoryPhotos()
{
	uploadWhere = 3;
	imgsArray = new Array();
}
function fileDialogStart_DirectoryLogo()
{
	uploadWhere = 4;
	imgsArray = new Array();
}

//The fileQueued event is fired for each file that is queued after the File Selection Dialog window is closed.
function fileQueued(fileObj) {
    $get('Limg').style.display = 'none';
    $get('accesscardLoadingImage').style.display = 'block';
    switch (uploadWhere)
    {
    	case 2: //Classifieds Images
    		if ($get('Upload_LoadingImage_Classified'))
    			$get('Upload_LoadingImage_Classified').style.display = "block";
    		break;
    	case 3: //Directory Images
    		if ($get('Upload_LoadingImage_DirectoryPhotos'))
    			$get('Upload_LoadingImage_DirectoryPhotos').style.display = "block";
    		break;
    	case 4: //Directory Logo
    		if ($get('Upload_LoadingImage_DirectoryLogo'))
    			$get('Upload_LoadingImage_DirectoryLogo').style.display = "block";
    		break;
    }
    this.addFileParam(fileObj.id, "file_id", fileObj.id);

}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesQueued > 0) {
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadStart(fileObj)
{
	switch (uploadWhere)
	{
		case 2: //Classifieds Images
			var iAdPhotosCount = document.getElementsByName('UploadPhotos_Classified').length - 1; //remove the initial template photo
			if (iAdPhotosCount >= 20)
			{
				$get('Upload_LoadingImage_Classified').style.display = "none";
				showMessage('exceeds max number of images, please delete some images to add others', 1);
				while (this.getStats().files_queued > 0)
					this.cancelUpload();
			}
			break; 
		case 3: //Directory Images
			var iAdPhotosCount = document.getElementsByName('UploadPhotos_DirectoryPhotos').length - 1; //remove the initial template photo
			if (iAdPhotosCount >= 20)
			{
				$get('Upload_LoadingImage_DirectoryPhotos').style.display = "none";
				showMessage('exceeds max number of images, please delete some images to add others', 1);
				while (this.getStats().files_queued > 0)
					this.cancelUpload();
			}
			break;
	}
}

function uploadProgress(fileObj, bytesLoaded) {

}

function uploadSuccess(fileObj, server_data)
{
	try
	{
		imgsArray.push(server_data);
		switch(uploadWhere)
		{
			case 0://UserProfileImage
				if (imgsArray.length == 1)
					ReplaceUserProfileImage(imgsArray[0]);
				break;
			case 2://Classifieds Images
				AddUploadImage(server_data,"Classified");
				break;
			case 3: //Directory Images
				AddUploadImage(server_data, "DirectoryPhotos");
				break;
			case 4: //Directory Logo
				if (imgsArray.length == 1)
					SetUploadImage(imgsArray[0], 'DirectoryLogo')
				break;
		}		
	}
    catch (ex) { this.debugMessage(ex); }
}

function uploadComplete(file) {
	try {
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued > 0)
		{
			this.startUpload();
		}
		else
		{
			switch (uploadWhere) {
				case 0: //UserProfileImage
					break;
				case 2: //Classifieds Images
					$get('Upload_LoadingImage_Classified').style.display = "none";
					break;
				case 3: //Directory Images
					$get('Upload_LoadingImage_DirectoryPhotos').style.display = "none";
					break;
				case 4: //Directory Logo
					$get('Upload_LoadingImage_DirectoryLogo').style.display = "none";
					break;
			}				
		}
	} catch (ex) {
		this.debug(ex);
	}
}


function fileCancelled(fileObj) {
}


function uploadError(error_code, fileObj, message) {
    try {
        var error_name = "";
        switch (error_code) {
            case SWFUpload.ERROR_CODE_QUEUE_LIMIT_EXCEEDED:
                error_name = "you can't upload more than 10 images in the same time.";
                break;
        }

        if (error_name !== "") {
            showMessage(error_name, 1);
            return;
        }

        switch (error_code) {
            case SWFUpload.ERROR_CODE_ZERO_BYTE_FILE:
                showMessage('zero byte file', 1);
                break;
            case SWFUpload.ERROR_CODE_UPLOAD_LIMIT_EXCEEDED:
                showMessage('upload limit exceeded, max 10 images', 1);
                break;
            case SWFUpload.ERROR_CODE_FILE_EXCEEDS_SIZE_LIMIT:
                showMessage('image exceeds size limit, max 2MB', 1);
                break;
            case SWFUpload.ERROR_CODE_HTTP_ERROR:
            case SWFUpload.ERROR_CODE_MISSING_UPLOAD_TARGET:
            case SWFUpload.ERROR_CODE_UPLOAD_FAILED:
            case SWFUpload.ERROR_CODE_IO_ERROR:
            case SWFUpload.ERROR_CODE_SECURITY_ERROR:
            default:
                showMessage(error_code, 1);
                break;
        }

        switch (uploadWhere)
        {
        	case 2: //Classifieds Images
        		AddUploadImage("/Images/classifieds/" + image_name, "Classified");
        		break;
        	case 3: //Directory Images
        		AddUploadImage("/Images/directory/" + image_name, "DirectoryPhotos");
        		break;
        } 

        var progress = new FileProgress(fileObj, this.getSetting("upload_target"));
        progress.SetStatus("Error.");
        progress.ToggleCancel(false);


    } catch (ex) { this.debugMessage(ex); }

}


/* ******************************************
*	FileProgress Object
*	Control object for displaying file info
* ****************************************** */

function FileProgress(fileObj, target_id)
{
}
FileProgress.prototype.SetProgress = function(percentage)
{
    this.fileProgressElement.className = "progressContainer green";
    this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
    this.fileProgressElement.childNodes[3].style.width = percentage + "%";
}
FileProgress.prototype.SetComplete = function()
{
    this.fileProgressElement.className = "progressContainer blue";
    this.fileProgressElement.childNodes[3].className = "progressBarComplete";
    this.fileProgressElement.childNodes[3].style.width = "";

}
FileProgress.prototype.SetError = function()
{
    this.fileProgressElement.className = "progressContainer red";
    this.fileProgressElement.childNodes[3].className = "progressBarError";
    this.fileProgressElement.childNodes[3].style.width = "";

}
FileProgress.prototype.SetCancelled = function()
{
    this.fileProgressElement.className = "progressContainer";
    this.fileProgressElement.childNodes[3].className = "progressBarError";
    this.fileProgressElement.childNodes[3].style.width = "";

}
FileProgress.prototype.SetStatus = function(status)
{
    this.fileProgressElement.childNodes[2].innerHTML = status;
}

FileProgress.prototype.ToggleCancel = function(show, upload_obj)
{
    this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
    if (upload_obj) {
        var file_id = this.file_progress_id;
        this.fileProgressElement.childNodes[0].onclick = function() { upload_obj.cancelUpload(file_id); return false; };
    }
}


function onSaveUserImageComplete(result)
{
}

function onSaveUserImageError(result)
{
}
function onSaveUserImageTimeOut(result)
{
}


function ReplaceUserProfileImage(src) {
    $get('accesscardLoadingImage').style.display = 'none';
    if ($get('UserProfileImageEditDiv'))
        $get('UserProfileImageEditDiv').innerHTML = "<img id='UserProfileImageEdit' src='/Images/Users/original/" + src + " ' />"

    $get('Limg').src = '/Images/Users/original/' + src;
    $get('Limg').style.display = 'block';
    Auth.SaveUserImage(ID, src, onSaveUserImageComplete, onSaveUserImageError, onSaveUserImageTimeOut);
}

function SetUploadImage(strImageName, strUploadType)
{
	switch (strUploadType)
	{
		case "DirectoryLogo":
			$get('imgDirectoryLogo').src = 'Images/Directory_Logo/' + strImageName;
			g_Upload_DirectoryLogo = strImageName;
			$get('divDirectoryLogo').style.display = 'block';
			break;
	}
}

function AddUploadImage(strImageName,strUploadType)
{
	var iAdPhotosCount = document.getElementsByName('UploadPhotos_' + strUploadType).length - 1; //remove the initial template photo
	if (iAdPhotosCount < 20)
	{
		var imgDiv = document.createElement('div');
		imgDiv.innerHTML = $get('UploadImageTemplate_' + strUploadType).innerHTML;
		imgDiv.id = 'UploadImageTemplate_' + strUploadType + '_' + strImageName;
		imgDiv.className = 'PhotoUpLoadDiv';
		var new_img = $get('UploadImage', imgDiv);
		//new_img.name = 'UploadPhotos_' + strUploadType;
		new_img.id = strImageName;
		$get('Upload_MakeDefaultLink', imgDiv).innerHTML = 'Make it default';
		if (iAdPhotosCount == 0)
		{//make the initial photo default
			$get('Upload_MakeDefaultLink', imgDiv).innerHTML = '';
			eval("g_UploadDefaultImage_" + strUploadType + " = strImageName;"); 
		}
		var new_SetDefaultLink = $get('Upload_MakeDefaultLink', imgDiv);
		//$get('Upload_MakeDefaultLink', imgDiv).setAttribute('onclick', 'SetAsDefaultImage("' + strImageName + '",'+strUploadType+')');
		$get('Upload_MakeDefaultLink', imgDiv).href = 'javascript:SetAsDefaultImage("' + strImageName + '","'+strUploadType+'");';
		$get('Upload_MakeDefaultLink', imgDiv).name = 'setDefaultImageLink_' + strUploadType;
		$get('Upload_MakeDefaultLink', imgDiv).id = 'set_' + strImageName;

		$get('Upload_DeleteLink', imgDiv).href = 'javascript:DeleteImage("' + strImageName + '","' + strUploadType + '");';
		$get('Upload_Thumbnails_' + strUploadType).appendChild(imgDiv);
		switch (strUploadType)
		{
			case "Classified":
				new_img.src = "/Images/classifieds_sml/" + strImageName;
				break;
			case "DirectoryPhotos":
				new_img.src = "/Images/directory_sml/" + strImageName;
				break;
		}
		imgDiv.style.display = '';
		//document.getElementById("Upload_Thumbnails_" + strUploadType).appendChild(new_img);
		if (new_img.filters)
		{
			try
			{
				new_img.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
			} catch (e)
			{
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				new_img.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
			}
		} else
		{
			new_img.style.opacity = 0;
		}
		new_img.onload = function() { FadeIn(new_img, 0); };
	}
}

function FadeIn(element, opacity)
{
    var reduce_opacity_by = 15;
    var rate = 30; // 15 fps


    if (opacity < 100) {
        opacity += reduce_opacity_by;
        if (opacity > 100) opacity = 100;

        if (element.filters) {
            try {
                element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
            } catch (e) {
                // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
                element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
            }
        } else {
            element.style.opacity = opacity / 100;
        }
    }

    if (opacity < 100) {
        setTimeout(function() { FadeIn(element, opacity); }, rate);
    }
}

 