var FeaturesDemoHandlers = {
	swfUploadLoaded : function () {
		FeaturesDemo.start(this);  // This refers to the SWFObject because SWFUpload calls this with .apply(this).
	},

	fileDialogStart : function () {
		try {
			//FeaturesDemo.selEventsQueue.options[FeaturesDemo.selEventsQueue.options.length] = new Option("File Dialog Start", "");
		} catch (ex) {
			this.debug(ex);
		}
	},

	fileQueued : function (file) {
		try {
			var queueString = file.name + ": 0%. "+lang_waiting+".";
			FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.options.length] = new Option(queueString, file.id);
						//FeaturesDemo.selEventsQueue.options[FeaturesDemo.selEventsQueue.options.length] = new Option("File Queued: " + file.id, "");
		} catch (ex) {
			this.debug(ex);
		}
	},

	fileQueueError : function (file, errorCode, message) {
		try {
			var imageName = "error.gif";
			var errorName = "";
			switch (errorCode) {
			case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
				errorName = "QUEUE LIMIT EXCEEDED";
				break;
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				imageName = "toobig.gif"
				errorName = "FILE EXCEEDS SIZE LIMIT";
				break;
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				imageName = "zerobyte.gif";
				errorName = "ZERO BYTE FILE";
				break;
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
				errorName = "INVALID FILE TYPE";
				break;
			default:
				errorName = "UNKNOWN";
				break;
			}

			addImage("/res/img/" + imageName);
		} catch (ex) {
			this.debug(ex);
		}
	},

	fileDialogComplete : function (numFilesSelected, numFilesQueued) {
		try {
			FeaturesDemo.btnStartAllFiles.style.display = 'block';
			//FeaturesDemo.selEventsQueue.options[FeaturesDemo.selEventsQueue.options.length] = new Option("File Dialog Complete: " + numFilesSelected + ", " + numFilesQueued, "");
		} catch (ex) {
			this.debug(ex);
		}
	},

	uploadStart : function (file) {
		try {
		} catch (ex) {
			this.debug(ex);
		}

		return true;
	},

	uploadProgress : function (file, bytesLoaded, totalBytes) {
		try {
			var percent = Math.ceil((bytesLoaded / file.size) * 100);
			if (percent < 10) {
				percent = "  " + percent;
			} else if (percent < 100) {
				percent = " " + percent;
			}

			FeaturesDemo.selQueue.value = file.id;
			var queueString = file.name + ": " + percent + "%. "+lang_uploading+"...";

			FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.selectedIndex].text = queueString;

			// start progress block
			var progress = new FileProgress(file,  this.customSettings.upload_target);
			progress.setProgress(percent);
			if (percent === 100) {
				progress.setStatus(lang_thumb_creating);
				progress.toggleCancel(false, this);
			} else {
				progress.setStatus(lang_uploading);
				progress.toggleCancel(true, this);
			}
			// finish progress block

		} catch (ex) {
			this.debug(ex);
		}
	},

	uploadSuccess : function (file, serverData) {

		try {

			addImage("/res/thumbnail.php?id=" + serverData + "&PHPSESSID=" + this.customSettings.php_session_id,serverData,this.customSettings.section_id);

			var queueString = file.name + ": "+lang_done+".";
			FeaturesDemo.selQueue.value = file.id;
			FeaturesDemo.selQueueTxt.value = FeaturesDemo.selQueueTxt.value+','+serverData;
			FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.selectedIndex].text = queueString;
			FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.selectedIndex].style.color = '#007bda';

			// start progress block
			var progress = new FileProgress(file,  this.customSettings.upload_target);

			//progress.setStatus("Thumbnail Created.");
			progress.setStatus(lang_thumb_created);
			progress.toggleCancel(false);
			// finish progress block

		} catch (ex) {
			this.debug(ex);
		}
	},

	uploadError : function (file, errorCode, message) {
		try {
			var imageName =  "error.gif";
			var progress;
			var errorName = "";
			switch (errorCode) {
			case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
				FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.selectedIndex].text = file.id + ":HTTP:" + file.name;
				errorName = "HTTP ERROR";
				break;
			case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
				errorName = "MISSING UPLOAD URL";
				break;
			case SWFUpload.UPLOAD_ERROR.IO_ERROR:
				FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.selectedIndex].text = file.id + ":IO  :" + file.name;
				errorName = "IO ERROR";
				break;
			case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
				FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.selectedIndex].text = file.id + ":SEC :" + file.name;
				errorName = "SECURITY ERROR";
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				imageName = "uploadlimit.gif";
				errorName = "UPLOAD LIMIT EXCEEDED";
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
				errorName = "UPLOAD FAILED";
				break;
			case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
				errorName = "SPECIFIED FILE ID NOT FOUND";
				break;
			case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
				errorName = "FILE VALIDATION FAILED";
				break;
			case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
				try {
					imageName = undefined;
					errorName = "FILE CANCELLED";

					FeaturesDemo.selQueue.value = file.id;
					FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.selectedIndex].text = file.name + ": Canceled.";
					FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.selectedIndex].style.color = '#777';

					progress = new FileProgress(file,  this.customSettings.upload_target);
					progress.setCancelled();
					progress.setStatus("Cancelled");
					progress.toggleCancel(false);
				}
				catch (ex) {
					this.debug(ex);
				}
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
				try {
					imageName = undefined;
					errorName = "FILE STOPPED";

					FeaturesDemo.selQueue.value = file.id;
					FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.selectedIndex].text = file.name + ": 0%. "+lang_waiting+"...";
					FeaturesDemo.selQueue.options[FeaturesDemo.selQueue.selectedIndex].style.color = '#000';

					progress = new FileProgress(file,  this.customSettings.upload_target);
					progress.setCancelled();
					progress.setStatus("Stopped");
					progress.toggleCancel(true);
				}
				catch (ex) {
					this.debug(ex);
				}
				break;
			default:
				errorName = "UNKNOWN";
				break;
			}

			if (imageName != undefined)
				addImage("/res/img/" + imageName);

		} catch (ex) {
			this.debug(ex);
		}
	},

	uploadComplete : function (file) {
		try {
		
		
			if (my_is_uploading_stoped == true) {
				my_is_uploading_stoped = false;
				return;
			}
			
			//alert(this.getStats().files_queued);
			if( this.getStats().files_queued == 0 && my_is_bulk_uploading==false )		
			{
				var progress = new FileProgress(file,  this.customSettings.upload_target);
				progress.setComplete();
				progress.setStatus("All images received.");
				progress.toggleCancel(false);
				go(this.customSettings.return_url);
			}
			
			
			/*

			if (this.getStats().files_queued > 0 && my_is_bulk_uploading) {
				this.startUpload();
			}
			// start progress block
			else {
				var progress = new FileProgress(file,  this.customSettings.upload_target);
				progress.setComplete();
				progress.setStatus("All images received.");
				progress.toggleCancel(false);
				go(this.customSettings.return_url);
			}*/
			
			// finish progress block
		} catch (ex) {
			this.debug(ex);
		}
	}
};

function createTextarea(value){

	var t = document.createElement('div');
	t.setAttribute("name","adddesct_block"+value);
	t.setAttribute("id","adddesct_block"+value);
	//t.setAttribute("style","text-align: center;");
	//t.setAttribute("style","width:120px;");
	document.getElementById("img_block"+value).appendChild(t); // add it to some form

	var t = document.createElement('div');
	t.setAttribute("name","addlink_block"+value);
	t.setAttribute("id","addlink_block"+value);
	document.getElementById("img_block"+value).appendChild(t); // add it to some form

	var t = document.createElement('textarea');
	t.setAttribute("name","data[Listing][PhotoComments]["+value+"]");
	t.setAttribute("id","description_"+value);
	t.setAttribute("cols","5");
	t.setAttribute("rows","4");
	t.setAttribute("class","inputbox");
	t.setAttribute("style","width:99%;");
	document.getElementById("adddesct_block"+value).appendChild(t); // add it to some form
	
	/* doen't work at IE
	var t = document.createElement('input');
	t.setAttribute("value","Change");
	t.setAttribute("type","button");
	t.setAttribute("onclick","commentsViaAjax(\'"+value+"\',jQuery(this).parents(\'form\'),\'description_"+value+"\',\'&ownphotoid='+value+'&ajax=true\');");
	t.setAttribute("class","button");
	document.getElementById("adddesct_block"+value).appendChild(t); // add it to some form
	*/
	
	var t = document.createElement('div');
	t.setAttribute("name","changelink_block"+value);
	t.setAttribute("id","changelink_block"+value);
	document.getElementById("adddesct_block"+value).appendChild(t); // add it to some form
	document.getElementById("changelink_block"+value).innerHTML = '<input type="button" onclick="commentsViaAjax(\''+value+'\',jQuery(this).parents(\'form\'),\'description_'+value+'\',\'\');" class="button" value="Saugoti" />';

	
	document.getElementById("putcomment").style.visibility =  "visible";
	document.getElementById("adddesct_block"+value).style.display =  "none";
	document.getElementById("addlink_block"+value).innerHTML = '<a href="#" id="desct_block'+value+'" onclick="toogleDescriptionBlock(this, document.getElementById(\'adddesct_block'+value+'\'));return false;"><span id="anchor_block'+value+'">Komentaras</span></a>';
}

function createCheckbox(value){

	var cb = null;
	var type = 'radio';
   // Try the IE way; this fails on standards-compliant browsers
   try {
      cb = document.createElement('<input type="'+type+'" name="data[Listing][mainImg]" value="'+value+'">');
   } catch (e) {
   }
   if (!cb ) {
      // Non-IE browser; use canonical method to create named element
		cb = document.createElement("input"); // create input node
		cb.type = "radio"; // set type
		cb.name = "data[Listing][mainImg]"; // set name if necessary
		//cb.name = "data"; // set name if necessary
		cb.value = value; // make it checked now and by default
   }

	document.getElementById("thumbnails").appendChild(cb); // add it to some form
	document.getElementById("primary").style.visibility =  "visible";

}

// thumbnails creation part
function addImage(src,value,section_id) {
	var newImg = document.createElement("img");

	newImg.style.margin = "5px";
	
	//createCheckbox(value);
	
	var t = document.createElement('div');
	t.setAttribute("name","img_block"+value);
	t.setAttribute("id","img_block"+value);
	//t.setAttribute("style","text-align: center;");
	t.setAttribute("style","clear: both; width:100%;");
	document.getElementById("thumbnails").appendChild(t); // add it to some form
	
	 //<div id="preloader_<?=$photo->key?>" align="center" style="position:absolute; top:50px; left:50px; display:none;"><img src="/res/img/loading.gif"></div>
	var t = document.createElement('div');
	t.setAttribute("id","preloader_"+value);
	t.setAttribute("style","position:absolute; top:50px; left:50px; display:none;");
	document.getElementById("thumbnails").appendChild(t); // add it to some form
	document.getElementById("preloader_"+value).style.display = 'none';
	document.getElementById("preloader_"+value).innerHTML = '<img src="/res/img/loading.gif">';
		 
	document.getElementById("img_block"+value).appendChild(newImg);
	// show comments block only for Photo Album
	//if(section_id==42)
	createTextarea(value);
	//alert(value);
	
	if (newImg.filters) {
		try {
			newImg.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.
			newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
		}
	} else {
		newImg.style.opacity = 0;
	}

	newImg.onload = function () {
		fadeIn(newImg, 0);
	};
	newImg.src = src;


}

function fadeIn(element, opacity) {
	var reduceOpacityBy = 5;
	var rate = 30;	// 15 fps


	if (opacity < 100) {
		opacity += reduceOpacityBy;
		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);
	}
}

/* ******************************************
 *	FileProgress Object
 *	Control object for displaying file info
 * ****************************************** */

function FileProgress(file, targetID) {
	this.fileProgressID = "divFileProgress";

	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.fileProgressID;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
		progressText.appendChild(document.createTextNode(file.name));

		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = "&nbsp;";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBar);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
		fadeIn(this.fileProgressWrapper, 0);

	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name;
	}

	this.height = this.fileProgressWrapper.offsetHeight;

}
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, swfuploadInstance) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfuploadInstance) {
		var fileID = this.fileProgressID;
		this.fileProgressElement.childNodes[0].onclick = function () {
			swfuploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};

	function toogleDescriptionBlock(src,dsc){
		jsrc = jQuery(src);
		if(dsc.style.display == 'block'){
			dsc.style.display='none';
			jsrc.html(jsrc.attr('descCache'));			
		}else{	
			dsc.style.display='block';
			jsrc.attr('descCache',jsrc.html());
			//jsrc.html("Uždaryti");
			jsrc.html("");
		}
	}

	function commentsViaAjax(value,form,area,url){			
		//jQuery('#preloader_'+value).show();
		//var r_url = jQuery(form).attr('action');
		//jQuery.post(r_url+url,{'Description':jQuery('#'+area).val()},
		//	(function(data){
		//		try{
		//			if(data.photo_id){
						//jQuery('#preloader_'+value).hide();
						jQuery('#adddesct_block'+value).hide();
						jQuery('#desct_block'+value).show();
						if(jQuery('#'+area).val()=='')
						jQuery('#desct_block'+value).html(jQuery('#desct_block'+value).attr('descCache'));
						else
						jQuery('#desct_block'+value).html(jQuery('#'+area).val());
						
						//jQuery('#anchor_block'+value).html(jQuery('#'+area).val());
						//jQuery('#description_'+data.photo_id).val(data.desc_full);												
						//jQuery('#desct_block'+data.photo_id).html(data.desc);
					
		//			}					
		//		}catch(e){alert(e);}	
		//	})
		//,'json');
	}