//---------Init Flash Uploader--------------------------

var flashUploader, currentGallery, currentAlbum, disableLinks = false;
var timestamp = new Date().getTime();
var flashvars = {};
flashvars.phpUrl = options.adminUrl + "/image-upload.php";
flashvars.contentDir = options.contentDir;
var params = {};
params.wmode = "transparent";
params.allowscriptaccess = "always";
var attributes = {};
swfobject.embedSWF(options.adminUrl+"/ImageUploader.swf?"+timestamp, "flashUploader", "75", "30", "9.0.0", false, flashvars, params, attributes, onFlashRegister);

function onFlashRegister(evt) {
	flashUploader = evt.ref;	
};


//------------Flash/JS communication methods-------------

//flash uploader calls this function when it has been loaded
function onFlashLoaded() {
	
	if(disableLinks) {
		flashUploader.disable();
	}

	jQuery('#albumSelecter').change(function() {

		jQuery('#mediaList').empty();
		currentAlbum = jQuery('#albumSelecter').val();
		if(!currentAlbum) {
			
			alert("You have created no albums yet. Please create an album first!\nYou will be redirected to the 'Manage albums' page.");
			location.href = 'admin.php?page=fancy-gallery-albums';
			return false;
		}
		
		currentGallery = jQuery('#albumSelecter option:selected').parent().attr('label');
		
		toggleAjaxLoading();
		flashUploader.setUploadDirectory(currentGallery + '/' + currentAlbum);

		jQuery.ajax({ url: options.Ajax_Url, data: { action: 'loadfiles', gallery: currentGallery, album: currentAlbum }, type: 'post', success: function(data) {
			
			jQuery.each(data, function() {
				addListItem('prepend', this.file, this.thumbnail, this.title, this.description);
			});
			
			toggleAjaxLoading();
			showSuccessBox('Album successfully loaded!');
			
		  }
		});
	}).change();
};

//open a modal loading box
function openModalLoading() {
	
	var windowWidth = jQuery(window).width();
	var windowHeight = jQuery(window).height();
	jQuery('body').append("<div id='ajaxOverlay' style='width:"+windowWidth+"px; height:"+windowHeight+"px;'></div>");
	jQuery('body').append("<div id='ajaxImageBox' style='left:"+ (windowWidth * 0.5 - 200)+"px; top:"+ (windowHeight * 0.5 - 250) +"px;'><div id='preloader'></div><span id='currentImage'></span><h4>Loading status:</h4><ul></ul><input type='submit' class='button-secondary' value='Close' disabled='disabled' /></div>");
	jQuery('#ajaxOverlay').fadeTo(0, 0.5);
	
	jQuery('#ajaxImageBox .button-secondary').live('click', function() {
		
		jQuery('#ajaxOverlay').remove();
		jQuery('#ajaxImageBox').remove();	
		return false;
		
	});
};

//function called from flash to set the loading status
function setUploadStatus(file, loaded) {
	
	jQuery('#ajaxImageBox #currentImage').text(file);
	jQuery('#ajaxImageBox h4').text("Loading status("+loaded+"):");
	
};

//when file has been loaded, start loading the next one
function setImageStatus(file, res) {
	
	if(res) {
		jQuery('#ajaxImageBox ul').append("<li class='successList'>"+file+"</li>");	
	}else {
		jQuery('#ajaxImageBox ul').append("<li class='errorList'>"+file+"</li>");
	}
	
	flashUploader.loadNextImage();
};

//add an image to the media list, when loading was successful
function addImage(filename) {
	if(filename != "") {
		var file = options.contentUrl+"/fancygallery/"+currentGallery+"/"+currentAlbum+"/"+filename;
		jQuery.ajax({ url: options.Ajax_Url, data: { action: 'savefile', gallery: currentGallery, album: currentAlbum, file: file, thumbnail: file, sortId: jQuery('#mediaList li').size() }, type: 'post', success: function(data) {
					
			addListItem('append', file, file, '', '');		
			setImageStatus(filename, 1);
			
		  }
		});
	}
};

//all images has been loaded
function loadingCompleted() {
		
	jQuery('#ajaxImageBox #preloader').hide();
	if(jQuery().jquery < "1.6.1") {
		jQuery('#ajaxImageBox .button-secondary').attr('disabled', '');
	}
	else {
		jQuery('#ajaxImageBox .button-secondary').prop('disabled', false);	
	}
	
	jQuery('#ajaxImageBox #currentImage').text("Loading completed!");
	
};

//adds a new list item to the media list
function addListItem(where, file, thumbnail, title, description) {
	
	var listItem = '<li><input type="checkbox" name="selected" value="'+file+'" /><input type="hidden" name="files[]" value="'+file+'" /><input type="hidden" name="thumbnails[]" value="'+thumbnail+'" /><span class="description">Title</span><br /><input type="text" name="titles[]" value="'+stripslashes(title)+'" style="width:100%;" /><img src="'+thumbnail+'" width="120" height="105" /><span class="description" style="float:left;">Description</span><textarea rows="4" name="descriptions[]" style="width:55%;">'+stripslashes(description)+'</textarea></li>';
	
	if(where == 'append') {
	    jQuery('#mediaList').append(listItem);
	}
	else {
	    jQuery('#mediaList').prepend(listItem);		
	}
};

function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
};

//-----------Document ready----------

jQuery(document).ready(function() {
				
	//init sortable for image list
	jQuery("#mediaList").sortable();
	jQuery("select, input:text").uniform();
	
	//set a thumbnail for the media
	var thumbnailInput, thumbPreview;
	jQuery('#mediaUpload img').click(function() {
		
		thumbnailInput = jQuery(this).parent().find('input[name=file_thumb]');
		thumbPreview = jQuery(this).parent().find('img');
	    tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
	    return false;
		
	});	
	window.send_to_editor = function(html) {
		
	    imgurl = jQuery('img',html).attr('src');
	    thumbnailInput.val(imgurl);
		thumbPreview.attr('src', imgurl);
	    tb_remove();
		
	};
	
	//add media to the list
	jQuery('#addMedia').click(function(evt) {
				
		var mediaThumb = jQuery('#mediaUpload input[name=file_thumb]').val();
		var mediaFile = jQuery('#mediaUpload input[name=media_file]').val();
		
		if(mediaFile == null || mediaFile == 'Enter here the URL of the media') {
			alert("Please enter a URL for the media!");
			return false;
		};
		
		if(mediaThumb == null || mediaThumb == "...or enter the URL of the thumbnail here") {
			alert("Please set a thumbnail for the media!");
			return false;
		};
		
		toggleAjaxLoading();
		jQuery.ajax({ url: options.Ajax_Url, data: { action: 'savefile', gallery: currentGallery, album: currentAlbum, file: mediaFile, thumbnail: mediaThumb, sortId: jQuery('#mediaList li').size() }, type: 'post', success: function(data) {
					
			addListItem('append', mediaFile, mediaThumb, '', '');
			jQuery('#mediaUpload input[name=file_thumb]').val('');
			jQuery('#mediaUpload input[name=media_file]').val('Enter here the link of the movie');
			jQuery('#mediaUpload img').attr('src', options.adminUrl + '/images/image_add_48.png');	
			toggleAjaxLoading();
			showSuccessBox('Media successfully uploaded!');
			
		  }
		});;
				
		return false;
	});
	
	//selects all list items
	jQuery("#selectAll, #deselectAll").click(function(evt) {
		jQuery("input:checkbox").each(function() {
		  this.checked = evt.currentTarget.id == 'selectAll' ? 'checked' : '';
		});
		
		return false;
	});
	
	
	//delete media from the media list
	jQuery('#deleteFiles').click(function(evt){
		
		if(jQuery("input:checked").length == 0) {
			alert("No media selected!");
			return false;
		}
		
		r = confirm("You are going to delete the selected media! Sure?");
		if(!r) {
			return false;
		}
		
		toggleAjaxLoading();
		
		var files = jQuery("input:checked").serializeArray();
		jQuery.ajax({ url: options.Ajax_Url, data: { action: 'deletefiles', files: files, gallery: currentGallery, album: currentAlbum }, type: 'post', success: function(data) {
			jQuery("input:checked").parent().remove();
			toggleAjaxLoading();
			showSuccessBox('Media successfully deleted!');
		  }
		});
		
		return false;
	});
	
	//update all media
	jQuery('#updateMedia').click(function() {
				
		toggleAjaxLoading();
		
		var files = jQuery('input[name*=files]').serializeArray();
		var thumbnails = jQuery('input[name*=thumbnails]').serializeArray();
		var titles = jQuery('input[name*=titles]').serializeArray();
		var descriptions = jQuery('textarea[name*=descriptions]').serializeArray();
						
		jQuery.ajax({ url: options.Ajax_Url, data: { action: 'updatefiles', gallery: currentGallery, album: currentAlbum, files: files, thumbnails: thumbnails, titles: titles, descriptions: descriptions }, type: 'post', success: function(data) {
			
			toggleAjaxLoading();
			showSuccessBox('Media successfully updated!');
			
		  }
		});
		
		return false;
	});
	
	//disable all links
	if(jQuery(document).find('.fg-disable-links').length) {
		disableLinks = true;
		jQuery('.fg-disable-links').find('object, .button-secondary, .button-primary').unbind().die().fadeTo(0, 0.5);
		jQuery('.fg-disable-links').find('input:submit').attr('disabled', 'disabled');
		return false;
	};
});