var imageUploader1 = null;
var uniqueId = 0;
var prevUploadFileCount = 0;
var dragAndDropEnabled = true;

var iu; 

var allowDrag = false;

function fullPageLoad(){	
	imageUploader1 = getImageUploader("ImageUploader1");

	var UploadPane=document.getElementById("UploadPane");    
	
	while (UploadPane.childNodes.length > 0){
		UploadPane.removeChild(UploadPane.childNodes[0]);
	}
	
	//Fix Opera applet z-order bug
	if (__browser.isOpera){
		UploadPane.style.height = "auto";
		UploadPane.style.overflow = "visible";
	}
	
	
	//Handle drag & drop.
	if (__browser.isIE || __browser.isSafari){
		var target = __browser.isIE ? UploadPane : document.body;
		target.ondragenter = function(){
			var e=window.event;
			var data = e.dataTransfer;
			if (data.getData('Text')==null){
				this.ondragover();
				data.dropEffect="copy";
				allowDrag=true;
			}
			else{
				allowDrag=false;
			}
		}
		
		target.ondragover=function(){
			var e = window.event;
			e.returnValue = !allowDrag;
		}

		target.ondrop = function(){
			var e = window.event;
			this.ondragover();
			e.dataTransfer.dropEffect = "none";
			processDragDrop();
		}
    }
    else {
		window.captureEvents(Event.DRAGDROP);
		window.addEventListener("dragdrop", function(){
				processDragDrop();
			}, true);
    }
	
}

function processDragDrop(){
	alert("Adding files with drag & drop can not be implemented in standard version due security reasons. However it can be enabled in private-label version."+
		"\r\n\r\nFor more information please contact us at sales@aurigma.com");
	if (imageUploader1){
		//imageUploader1.AddToUploadList();
	}
}

//To identify items in upload list, GUID are used. However it would work 
//too slow if we use GUIDs directly. To increase performance, we will use 
//hash table which will map the guid to the index in upload list. 

//This function builds and returns the hash table which will be used for    
//fast item search.
function getGuidIndexHash(){
	var uploadFileCount = imageUploader1.getUploadFileCount();
	var guidIndexHash = new Object();			
	for (var i = 1; i <= uploadFileCount; i++){
		guidIndexHash[imageUploader1.getUploadFileGuid(i)] = i;
	}
	return guidIndexHash;
}

//This function returns HTML which represent the single item in the custom upload pane.
//It contains of the Thumbnail object and form elements for each piece of data (in our 
//case - title and description). If you want to upload extra data, you should write
//additional form elements here.
//
//It is highly recommended not to copy this function into the main HTML page to 
//avoid problems with activation of ActiveX controls in Internet Explorer with
//security update 912945. You can read more detailed about activation on Microsoft website:
//
//http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/overview/activating_activex.asp 
function addUploadFileHtml(index)
{
	var guid = "" + imageUploader1.getUploadFileGuid(index);
	var fileName = "" + imageUploader1.getUploadFileName(index);

	var h = "<table cellspacing=\"5\"><tbody>";
	h += "<tr>";
	h += "<td class=\"Thumbnail\" align=\"center\" valign=\"middle\">";

	//Add thumbnail control and link it with Image Uploader by its name and GUID.
	var tn = new ThumbnailWriter("Thumbnail" + uniqueId, 96, 96);
	//Copy codebase and version settings from ImageUploaderWriter instance.
	tn.activeXControlCodeBase = iu.activeXControlCodeBase;
	tn.activeXControlVersion = iu.activeXControlVersion;
	tn.javaAppletCodeBase = iu.javaAppletCodeBase;
	tn.javaAppletCached = iu.javaAppletCached;
	tn.javaAppletVersion = iu.javaAppletVersion;

	tn.addParam("ParentControlName", "ImageUploader1");
	tn.addParam("Guid", guid);
	tn.addParam("FileName", fileName);
	h += tn.getHtml();

	h += "</td>";
	h += "<td valign=\"top\">";

	//Add Title element.
	h += "Title:<br />";
	h += "<input id=\"Title" + uniqueId + "\" class=\"Title\" type=\"text\" /><br />";

	//Add Description element.
	h += "Description:<br />";
	h += "<textarea id=\"Description" + uniqueId + "\" class=\"Description\"\"></textarea>";

	h += "</td>";
	h += "</tr>";
	h += "<tr>";
	h += "<td align=\"center\"><a href=\"#\" onclick=\"return Remove_click('" + guid + "');\">Remove</a></td>";
	h += "<td></td>";
	h += "</tr>";
	h += "</tbody></table>";

	//Create DIV element which will represent the upload list item.
	var div = document.createElement("div");
	div.className = "UploadFile";
	div.innerHTML = h;
	div._guid = guid;
	//_uniqueId is used for fast access to the Title and Description form elements.
	div._uniqueId = uniqueId;

	//Append this upload list item to the custom upload pane.
	document.getElementById("UploadPane").appendChild(div);

	//Increase the ID to guaranty uniqueness.
	uniqueId++;
}

//Synchronize custom upload pane with Image Uploader upload list when 
//some files are added or removed.
function ImageUploader_UploadFileCountChange(){
	imageUploader1 = getImageUploader("ImageUploader1");
	if (imageUploader1){
		var uploadFileCount  = imageUploader1.getUploadFileCount();
		
		//Files are being added.
		if (prevUploadFileCount <= uploadFileCount){
			for (var i = prevUploadFileCount + 1; i <= uploadFileCount; i++){
				addUploadFileHtml(i);
			}
		}
		//Files are being removed.
		else{		
			var guidIndexHash = getGuidIndexHash();
			var UploadPane = document.getElementById("UploadPane");
			var i = UploadPane.childNodes.length - 1;
			while (i >= 0){
				if (guidIndexHash[UploadPane.childNodes[i]._guid] == undefined){
					UploadPane.removeChild(UploadPane.childNodes[i]);
				}
				i--;	
			}
		}
				
		prevUploadFileCount = uploadFileCount;		
		
		document.getElementById("UploadButton").disabled = (uploadFileCount == 0);
	}
}

/**
 * Adds the uploader to the page
 */
/*function EnhancePage()
{

	// First, replace the message with instructions
	//$('#imageUploader').html('<p id="loadingmessage">Loading the image uploader&hellip;</p>');
	
	// Next, add the various elements
	$('#instructions').removeClass('hidden');//html('<p>Browse your computer using the area on the left. Choose the files to upload on the right.</p>');	// Add the instructions
	
	var h = iu.getHtml();
	$('#appletContainer').html(h);	// Add the image uploader applet
	
	//$('#imageUploader').append('<div id="UploadPaneFrame"><div id="UploadPane"></div></div>');
	
	//$('#UploadPaneFrame').append('<div class="buttons"><button id="UploadButton" type="button" disabled="disabled">Upload Files</button></div>');	// Add the UPLOAD button	
}*/

function ImageUploaderID_AfterUpload(Html)
{
	history.go(-1);
	//...your code...
}


//Append the additional data entered by the user (title and description)
//to the upload. If you add more fields, do not forget to modify this event 
//handler to call AddField for these fields.
function ImageUploader_BeforeUpload()
{
	var guidIndexHash = getGuidIndexHash();
	
	var UploadPane = document.getElementById("UploadPane");
	
	// Add FatDog required fields
	imageUploader1.AddField('Type', $('#mediaType').html());		// 1 = $MediaType['Image']
	imageUploader1.AddField('IG', $('#ID_Gallery').html());

	for (var i = 0; i < UploadPane.childNodes.length; i++){
		var div = UploadPane.childNodes[i];
		
		var index = guidIndexHash[div._guid];		
		
		//Description will be sent as a native Description POST field 
		//provided by Image Uploader.
		imageUploader1.setUploadFileDescription(index, 
			document.getElementById("Description" + div._uniqueId).value);

		//Title will be sent as a custom Title_N POST field, where N is an 
		//index of the file.
		imageUploader1.AddField("Title_" + index, document.getElementById("Title" + div._uniqueId).value);
	}	
}

//This function is used to handle Remove link click. It removes an item 
//from the custom upload pane by specified GUID.
function Remove_click(guid){
	var guidIndexHash = getGuidIndexHash();	
	imageUploader1.UploadFileRemove(guidIndexHash[guid]);
}

//This function posts data on server.
function UploadButton_click(){
	imageUploader1.Send();
}

/**
 * This function will initialize Java image uploader
 */
function InitImageUploader()
{
	//Create JavaScript object that will embed Image Uploader to the page.
	iu = new ImageUploaderWriter("ImageUploader1", 650, 250);
	
	//For ActiveX control full path to CAB file (including file name) should be specified.
	iu.activeXControlCodeBase = "/downloads/ImageUploader4.cab";
	iu.activeXControlVersion = "4,5,50,0";
	
	//For Java applet only path to directory with JAR files should be specified (without file name).
	iu.javaAppletCodeBase = "/downloads/";
	iu.javaAppletCached = true;
	iu.javaAppletVersion = "2.5.50.0";
	
	iu.showNonemptyResponse = "off";
	
	//Configure appearance.
	iu.addParam("PaneLayout", "ThreePanes");
	iu.addParam("FolderView", "Thumbnails");
	
	iu.addParam("BackgroundColor", "#eff1f9");
	iu.addParam("ShowUploadListButtons", "true");
	iu.addParam("ButtonRemoveFromUploadListText", "");
	iu.addParam("ButtonRemoveAllFromUploadListText", "");
	
	iu.addParam("ShowDescriptions", "false");
	iu.addParam("AllowRotate", "false");
	iu.addParam("ShowButtons", "false");
	
	//Hide standard upload pane.
	iu.addParam("FolderPaneHeight", "-1");
	
	//Add event handlers.
	iu.addEventListener("UploadFileCountChange", "ImageUploader_UploadFileCountChange");
	iu.addEventListener("BeforeUpload", "ImageUploader_BeforeUpload")
	iu.fullPageLoadListenerName = "fullPageLoad";
	
	/**
	 * Mars Custom Options
	 */
	iu.addParam("FilesPerOnePackageCount", "1");
	iu.addParam("LicenseKey", "9096-5952-6520-9903;5451-5322-5298-7735;5695-6611-9099-7084;7759-7381-6119-7732");
	
	// Thumbnail 1 is used on FatDog as the thumbnail
	iu.addParam("UploadThumbnail1FitMode", "Fit");
	iu.addParam("UploadThumbnail1Width", "120");
	iu.addParam("UploadThumbnail1Height", "120");
	iu.addParam("UploadThumbnail1JpegQuality", "70");
	iu.addParam("UploadThumbnail1ResizeQuality", "ResizeQualityHigh");
	
	// Thumbnail 2 is used on FatDog as the large version
	iu.addParam("UploadThumbnail2FitMode", "Fit");
	iu.addParam("UploadThumbnail2Width", "550");
	iu.addParam("UploadThumbnail2Height", "400");
	iu.addParam("UploadThumbnail2JpegQuality", "90");
	iu.addParam("UploadThumbnail2ResizeQuality", "ResizeQualityHigh");
	
	//Configure URL files are uploaded to.
	iu.addParam("Action", "media_add_handler.php");
	
	//Configure URL where to redirect after upload.
	iu.addParam("RedirectUrl", "game.php");
	
	// Do not upload the source file (original file)
	iu.addParam("UploadSourceFile", "false");

	// UI messages
	iu.addParam("ButtonAddToUploadListText", "Add Selected");
	iu.addParam("ButtonAddAllToUploadListText", "Add Folder");
	iu.addParam("MessageUploadCompleteText", "Your photos have been submitted for approval. They will appear once they are approved.");
	
	//Tell Image Uploader writer object to generate all necessary HTML code to embed 
	//Image Uploader to the page.
	iu.writeHtml();
	
	window.onload = function () {
		document.getElementById("UploadButton").onclick = function () {
			UploadButton_click();
		}
	}
}

/**
 * when the page is ready, initialize the uploader and add the controls to the page
 */
/*$(document).ready(function () {
	InitImageUploader();
	EnhancePage();
});*/
