var FILE_CHECKBOXES = "input[type=checkbox][id^='files']";

var ToolbarButtons = {'settings' : 0,'properties' : 1,'share' : -6,'play' : -2,'delete' : -1,'rename' : 1,'paste' : -3,'cut' : -1,'new_folder' : 0,'download' : -1, 'upload': 0,
'add_photos': -4, 'new_album': -5, 'new_ph_category': -5
};


String.prototype.replaceAll = function(search, replace)
{
	return this.split(search).join(replace);
}

String.prototype.jq = function()
{
	return '#' + this.replace(/(:|\.|!|%)/g,'\\$1').replaceAll("/", "\\/");
}



var flipdrive = {

	publicArea: false,
	publicUsername: '',
	currentSubdir: '',
	currentPhotoCategory: 0,
	skipTreeActions: false,
	divPopup: 'divPopup',
	divFilesList: 'divFilesList',
	currentMyDriveItem: null,

	setDefaultButton: function(input, button) {

		$(input).keypress(function (e) {
			if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
				$(button).click();
				return false;
			} else {
				return true;
			}
		});

	},


	postData: function(data2post, url, id, method) {
		if (data2post == null) {
			data2post = '';
		} else
		if (typeof data2post === "object") {
			data2post = $.param(data2post);
		}
		var date = new Date;
		var _url = url + ((url.indexOf('?') == -1) ? '?' : '&') + 'rnd='+date.getTime();
		$.ajax({type:method? method : 'POST',
			dataType:'html',
			data:data2post,
			success:function(data, textStatus) {$('#'+id).show().html(data);},
			beforeSend:function(XMLHttpRequest){ },
			complete:function(XMLHttpRequest, textStatus){focusInput('#'+id);},
			url: _url
		});
	},

	post: function(elem, url, id, method) {
		if (!id) id = this.divFilesList;
		var form = $(elem).parents("form:first");
		if (!url) {
			url = form.attr('action');
		}
		var date = new Date;
		var _url = url + ((url.indexOf('?') == -1) ? '?' : '&') + 'rnd='+date.getTime();
		$.ajax({type:method? method : 'POST',
			dataType:'html',
			data:form.serialize(),
			success:function(data, textStatus) {$('#'+id).show().html(data);},
			beforeSend:function(XMLHttpRequest){ },
			complete:function(XMLHttpRequest, textStatus){focusInput('#'+id);},
			url: _url
		});
		//this.closepopup();
	},

	gotoUrl: function(url, id) {
		
		if (!id && $('#' + flipdrive.divFilesList).length == 0) {
			id = 'divContent';
			url += '&full=1';
		}
		
		flipdrive.goto(url, id);
		
		//document.location.href = url;
	},

	goto: function(url, id) {
		if (!id) id = this.divFilesList;
		
		var date = new Date;
		var _url = url + ((url.indexOf('?') == -1) ? '?' : '&') + 'rnd='+date.getTime();
		
		$.ajax({type:'GET',
			dataType:'html',
			success:function(data, textStatus) {$('#'+id).show().html(data);},
			beforeSend:function(XMLHttpRequest){},
			complete:function(XMLHttpRequest, textStatus){ focusInput('#'+id);},
			url: _url
		});
	},

	popup: function(url) {
		this.goto(url, this.divPopup);
	},

	popup_https: function(url) {

		var href = document.location.href;

		var href2 = href.replace('http://', 'https://');
		var href2 = href2.replace(/#.*/, '');

		if (href != href2) {
			var and = '?';
			if (href2.indexOf('?') > -1) {
				and = '&';
			}
			href2 += and + 'allow_https=1&popupurl=' + escape(url);

			document.location.href = href2;
			//$(document).ready(function() { alert(document.location.href); flipdrive.goto(url, this.divPopup);} );
			//setTimeout(function() { alert(document.location.href); flipdrive.goto(url, this.divPopup);}, 1000);
		} else {
			this.goto(url, this.divPopup);
		}
	},


	closepopup: function() {
		$('#' + this.divPopup).hide();
	},

	history: function(path) {

		path = flipdrive.encodeHash(path);
		$.history.load(path);

	},

	checkHash: function(hash) {
		//alert(hash + '!=' + encodeURIComponent(flipdrive.currentSubdir));
		if (flipdrive.currentSubdir == '') return false;
		if (hash == flipdrive.encodeHash(flipdrive.currentSubdir)) return false;
		return true;
	},

	checkHashPhoto: function(hash) {
		//alert(hash + '!=' + encodeURIComponent(flipdrive.currentSubdir));
		if (flipdrive.currentPhotoCategory == 0) return false;
		if (hash == flipdrive.encodeHash(flipdrive.currentPhotoCategory)) return false;
		return true;
	},

	gotoHash: function(hash) {
		hash = flipdrive.decodeHash(hash);
		flipdrive.gotoDir(hash);
	},
	
	gotoPhotoHash: function(hash) {
		hash = flipdrive.decodeHash(hash);
		flipdrive.gotoPhotoCat(hash);
	},

	encodeHash: function(hash) {
		return 'p' + hash.replaceAll('/', '~');
	},

	decodeHash: function(hash) {
		return hash.replaceAll('~', '/').substring(1);
	},

	encodeNode: function(path) {
		return encodeURIComponent(path).replaceAll("'", '%27').replaceAll('%', 'z_z');
	},
	
	encodeNodeAlt: function(path) {
		return encodeURI(path).replaceAll("'", '%27').replaceAll('%', 'z_z');
	},

	decodeNode: function(path) {
		if (!path) return 0;
		return decodeURIComponent(path.replaceAll('z_z', '%'));
	},
	
	decodeNodeAlt: function(path){
		if (!path) return 0;
		return decodeURI(path.replaceAll('z_z', '%'));
	},



	//////////////////////My Photos////////////////////////////

	gotoPhotoCat: function(catId, sort) {

		if (flipdrive.publicArea) {
			flipdrive.gotoUrl( '/' + flipdrive.publicUsername + "?cat_id=" + catId);
			return false;
		}

		if (sort) sort = '&sort=name'; else sort = '';
		flipdrive.goto("/apps/photos/albums?cat_id=" + catId + sort);
	},

	viewAlbum: function(albumId) {


		if (flipdrive.publicArea) {
			flipdrive.gotoUrl( '/' + flipdrive.publicUsername + '/viewalbum?album_id=' + albumId, 'divContent');
			return false;
		}


		flipdrive.goto("/apps/photos/viewalbum?album_id=" + albumId);
		return false;
	},

	viewPhoto: function(albumId, page) {


		if (flipdrive.publicArea) {
			flipdrive.gotoUrl('/' + flipdrive.publicUsername + '/viewphoto?album_id=' + albumId + "&page=" + page, 'divContent');
			return false;
		}



		if (!albumId) {
			if (flipdrive.currentMyDriveItem) {

				var filesid = flipdrive.currentMyDriveItem.attr('id');
				var imgid = filesid.replace('files', 'img');
				$('#' + imgid).click();
			}
		} else {
			flipdrive.goto("/apps/photos/viewphoto?album_id=" + albumId + "&page=" + page);
		}
		return false;
	},
	
	postCategory: function(elem, url, id, method) {
		if (!id) id = this.divFilesList;
		var form = $(elem).parents("form:first");
		if (!url) {
			url = form.attr('action');
		}
		var date = new Date;
		var _url = url + ((url.indexOf('?') == -1) ? '?' : '&') + 'rnd='+date.getTime();
		$.ajax({type:method? method : 'POST',
			dataType:'html',
			data:form.serialize(),
			success:function(data, textStatus) {
				$('#'+id).show().html(data);
		    	$("#left_tree").tree({
		        data  : {
		          type  : "json",
		          url   : "/apps/photos/nodes",
		          async : true,
		          async_data : function (NODE) { return { id : flipdrive.decodeNode($(NODE).attr("id")) || 0, rnd : (new Date()).getTime() } }
		        },
		        callback: {
		      	  onload: function(TREE_OBJ) {  },
		      	  onselect: function(NODE,TREE_OBJ) { if (flipdrive.skipTreeActions) return; flipdrive.gotoPhotoCat(  $(NODE).attr("id") ); flipdrive.skipTreeActions = true; },
		      	  onJSONdata: function(DATA, TREE_OBJ) {if (DATA.length == 0 && flipdrive.currentPhotoCategory == 0) {$('#divNoFolders').show();$('#divTreeView').hide();} else {$('#divNoFolders').hide();$('#divTreeView').show();} flipdrive.onTreeLoadInterval = setTimeout(function() {flipdrive.onTreeLoad();}, 500); return DATA; }
		        }
		      });
		      
		      $("#left_tree").click(function() {flipdrive.skipTreeActions = false;});
			},
			beforeSend:function(XMLHttpRequest){ },
			complete:function(XMLHttpRequest, textStatus){focusInput('#'+id);},
			url: _url
		});
		//this.closepopup();
	},

	photocategory: function(elem) {
		url = '/apps/photos/category';
		method = 'GET';
		id = flipdrive.divPopup;

		data2post = flipdrive.currentMyDriveItem;
		if (data2post == null) {
			data2post = '';
		} else
		if (typeof data2post === "object") {
			data2post = $.param(data2post);
		}
		var date = new Date;
		var _url = url + ((url.indexOf('?') == -1) ? '?' : '&') + 'rnd='+date.getTime();
		$.ajax({type:method? method : 'POST',
			dataType:'html',
			data:data2post,
			success:function(data, textStatus) {$('#'+id).show().html(data);},
			beforeSend:function(XMLHttpRequest){ },
			complete:function(XMLHttpRequest, textStatus){focusInput('#'+id);},
			url: _url
		});

		return false;
	},

	newphotoalbum: function(elem, redirect) {
		
		var url = '/apps/photos/newalbum';
		if (redirect) url = url + '?redirect=1';
	
		return flipdrive.mydriveAction(elem, url, flipdrive.divPopup, 'GET');
	},

	deletePhotoItems: function(elem, isphoto) {
		if (!isphoto) isphoto = '';
		if ($('div.imageBox').length > 0 || isphoto == 'uploadedphoto') {
			if (isphoto == 'uploadedphoto') isphoto = '?uploadedphoto=1';
			return flipdrive.mydriveAction(elem, '/apps/photos/deletephoto'+isphoto, flipdrive.divPopup, 'GET');
		} else {
			return flipdrive.mydriveAction(elem, '/apps/photos/delete', flipdrive.divPopup, 'GET');
		}
	},

	cutPhotoItems: function(elem) {

		if ($('div.imageBox').length > 0) {
			return flipdrive.mydriveAction(elem, '/apps/photos/cutphotos');
		} else {
			return flipdrive.mydriveAction(elem, '/apps/photos/cutitems');
		}
	},

	pastePhotoItems: function(elem) {

		if ($('div.imageBox').length > 0) {

			if (elem) {
				if ($(elem).attr('disabled')) return;
				flipdrive.goto('/apps/photos/pastephotos', flipdrive.divFilesList);
			} else {

				flipdrive.goto('/apps/photos/pastephotos?cat_id=' + flipdrive.currentPhotoCategory, flipdrive.divFilesList);

			}

		} else {

			if (elem) {
				if ($(elem).attr('disabled')) return;
				flipdrive.goto('/apps/photos/pasteitems', flipdrive.divFilesList);
			} else {

				flipdrive.goto('/apps/photos/pasteitems?cat_id=' + flipdrive.currentPhotoCategory, flipdrive.divFilesList);

			}


		}


		return false;
	},

	propertiesPhotoItems: function(elem) {
		if ($('div.imageBox').length > 0) {
			return flipdrive.mydriveAction(elem, '/apps/photos/photoprop', flipdrive.divPopup, 'GET');
		} else {
			return flipdrive.mydriveAction(elem, '/apps/photos/properties', flipdrive.divPopup, 'GET');
		}
	},

	shareAlbum: function(elem) {
		return flipdrive.mydriveAction(elem, '/apps/photos/share');
	},

	downloadPhoto: function(elem) {
		if (!elem) elem = flipdrive.currentMyDriveItem;

		document.location.href = '/apps/photos/download?' + $.param(elem);
		return false;

		//return flipdrive.mydriveAction(elem, '/apps/photos/download', flipdrive.divPopup);
	},


	//////////////////////My Drive////////////////////////////

	gotoDir: function(dir) {
		flipdrive.goto("/apps/mydrive/files?subdir=" + encodeURIComponent(dir));
	},

	properties: function(elem) {
		return flipdrive.mydriveAction(elem, '/apps/mydrive/properties', flipdrive.divPopup, 'GET');
	},

	cut: function(elem) {
		return flipdrive.mydriveAction(elem, '/apps/mydrive/cut');
	},

	paste: function(elem) {
		if (elem) {
			if ($(elem).attr('disabled')) return;
			flipdrive.goto('/apps/mydrive/paste', flipdrive.divFilesList);
		} else {
			flipdrive.goto('/apps/mydrive/paste?subdir=' + encodeURIComponent(flipdrive.currentMyDriveItem.attr('value')), flipdrive.divFilesList);
		}
		return false;
	},

	rename: function(elem) {
		return flipdrive.mydriveAction(elem, '/apps/mydrive/directory?mode=rename', flipdrive.divPopup, 'GET');
	},

	deleteDirectory: function(elem) {
		return flipdrive.mydriveAction(elem, '/apps/mydrive/delete', flipdrive.divPopup, 'GET');
	},

	share: function(elem) {
		var info = getCheckedInfo();
		var total_dir = Number(shared_count) + Number(info.dir_count);
		var total_files = Number(shared_count_files) + Number(info.files_count);
		if(user_type == 'free'){
			//DIR
			if(Number(shared_count) == 5){
				return flipdrive.popup('/apps/mydrive/upgradepopup?mode=1&total='+total_dir+'&try='+info.dir_count);
			}
			else if(shared_count > 0 && total_dir > 5){
				return flipdrive.popup('/apps/mydrive/upgradepopup?mode=2&total='+total_dir+'&try='+info.dir_count);
			}
			else if(Number(shared_count) == 0 && total_dir > 5){
				return flipdrive.popup('/apps/mydrive/upgradepopup?mode=3&total='+total_dir+'&try='+info.dir_count);
			}
			//FILES
			if(Number(shared_count_files) == 10){
				return flipdrive.popup('/apps/mydrive/upgradepopup?mode=1&t=file&total='+total_dir+'&try='+info.dir_count);
			}
			else if(shared_count_files > 0 && total_files > 10){
				return flipdrive.popup('/apps/mydrive/upgradepopup?mode=1&t=file&total='+total_files+'&try='+info.files_count);
			}
			else if(Number(shared_count_files) == 0 && total_files > 10){
				return flipdrive.popup('/apps/mydrive/upgradepopup?mode=3&t=file&total='+total_files+'&try='+info.files_count);
			}
			
//			if(shared_count_files >= 10 && info.files_count){
//				return flipdrive.popup('/apps/mydrive/upgradepopup?mode=1&t=file');
//			}
//			if(Number(shared_count_files) > 0 && total_files > 10 ){
//				return flipdrive.popup('/apps/mydrive/upgradepopup?mode=3&t=file&total='+total_files);
//			}else if(Number(shared_count_files) == 0 && total_files > 10){
//				return flipdrive.popup('/apps/mydrive/upgradepopup?mode=3&t=file&total='+total_files);
//			}
		}
		return flipdrive.mydriveAction(elem, '/apps/mydrive/share');
	},

	directLink: function(elem) {

		if (elem) {
			return flipdrive.mydriveAction(elem.attr('value'), '/apps/mydrive/direct', flipdrive.divPopup);
		}
		return flipdrive.mydriveAction(elem, '/apps/mydrive/direct', flipdrive.divPopup);
	},

	download: function(elem) {
		return flipdrive.mydriveAction(elem, '/apps/mydrive/download', flipdrive.divPopup);
	},
	//////////////////////My Drive////////////////////////////


	mydriveAction: function(elem, url, div, method) {
			
		if (!div) div = flipdrive.divFilesList;
		if (!method) method = 'POST';
		if (elem) {
			if (typeof elem === "object") {
				if ($(elem).attr('disabled')) return;
				flipdrive.post(elem, url, div, method);
			} else {
				flipdrive.postData(encodeURIComponent("files[]")+"="+elem, url, div, method);
			}
		} else {
			flipdrive.postData(flipdrive.currentMyDriveItem, url, div, method);
		}
		return false;
	},

	photosAction: function(elem, url, div, method) {
		if (!div) div = flipdrive.divFilesList;
		if (!method) method = 'POST';
		if (elem) {
			if (typeof elem === "object") {
				if ($(elem).attr('disabled')) return;
				flipdrive.post(elem, url, div, method);
			} else {
				flipdrive.postData(encodeURIComponent("files[]")+"="+elem, url, div, method);
			}
		} else {
			flipdrive.postData(flipdrive.currentMyDriveItem, url, div, method);
		}
		return false;
	},


	onTreeLoad: function() { },
	onTreeLoadInterval: false

}



function manageButton(button, enable) {
	button = $(button);
	var div = button.parent("div");
	if (enable) {
		div.removeClass("item_in");
		div.addClass("item");
		button.removeAttr("disabled");
		button.unbind(".killlink");
	} else {
		div.removeClass("item");
		div.addClass("item_in");
		button.attr("disabled", true);
		button.bind("click.killlink", function (e) {disableLink(e);} );
	}
}

var ToolbarDisabled = false;

function disableToolbar() {

	var toolbarButtons = $("a[id^='tp_']");

	toolbarButtons.each(

	function(i, button) {
		manageButton(button, false);
	}
	);

	ToolbarDisabled = true;


}

function manageToolbar() {

	checkForAllCheckboxes();

	if (ToolbarDisabled) {
		ToolbarDisabled = false;
		return;
	}
	var info = getCheckboxesInfo();
	var elems = info.checkboxes;
	var checkedCount = info.checkedCount;
	var allCount =  info.allCount;

	mp3Count = 0;
	dirCount = 0;
	elems.each(
	function(i, checkbox) {
		if (checkbox.isdir == 1) dirCount++;
		if (checkbox.ismp3 == 1) mp3Count++;
	}
	);


	var toolbarButtons = $("a[id^='tp_']");

	toolbarButtons.each(

	function(i, button) {


		var key = button.id.replace('tp_', '');
		var value = ToolbarButtons[key];



		switch(value) {

			case -6:

			if ($('div.imageBox').length > 0) {
				manageButton(button, false)
			} else
			{
				if ($('photos_table').length > 0) {

					if (checkedCount < 1 || dirCount > 0) {
						manageButton(button, false)
					}	else {
						manageButton(button, true)
					}

				} else {
					if (checkedCount < 1) {
						manageButton(button, false)
					}	else {
						manageButton(button, true)
					}
				}
			}

			break;


			case -1:
			if (checkedCount < 1) {
				manageButton(button, false)
			}	else {
				manageButton(button, true)
			}

			break;

			case -2:
			if (mp3Count == 1 && checkedCount == 1) {
				manageButton(button, true)
			}	else {
				manageButton(button, false)
			}

			break;

			case -5:

			if ($('div.imageBox').length > 0 || $('#in_photo_img').length > 0) {
				manageButton(button, false)
			} else
			{
				manageButton(button, true)
			}

			break;


			case -4:

			if ($('div.imageBox').length > 0) {
				manageButton(button, true)
			} else

			if (dirCount == 0 && checkedCount == 1) {
				manageButton(button, true)
			}	else {
				manageButton(button, false)
			}

			break;

			case -3:
			if (HasCuttedItems) {
				manageButton(button, true)
			}	else {
				manageButton(button, false)
			}

			break;

			case 1:

			if (checkedCount != 1) {
				manageButton(button, false)
			}	else {
				manageButton(button, true)
			}

			break;

			case 0:

			manageButton(button, true)

			break;
		}
	}
	);
}

function swithShowMore(el, e) {

	var span = $(el).prev();
	var span2 = span.prev();

	span.toggleClass('show_more_description');
	span2.toggleClass('show_more_description');

	if (span.hasClass('show_more_description')) {
		$(el).html('show&nbsp;more&nbsp;&raquo;');
	} else {
		$(el).html('&laquo;&nbsp;show&nbsp;less');
	}
	e.stopPropagation();
}

function getCheckboxesInfo() {
	var checkboxes = $(FILE_CHECKBOXES);
	var checkedCount =   checkboxes.filter(":checked").length;
	var allCount =  checkboxes.length;
	return { checkboxes: checkboxes, checkedCount : checkedCount, allCount: allCount};
}

function getCheckedInfo() {
	var checkboxes = $(FILE_CHECKBOXES);
	var cdir = 0;
	var cfile = 0;
	checkboxes.filter(":checked").each(function(i,el){
		var ele = $(el);
		if(ele.attr('isdir') == '1') cdir++;
		else cfile++;
	});
	return { files_count: cfile, dir_count:cdir};
}


function checkForAllCheckboxes() {
	var info = getCheckboxesInfo();
	if (info.allCount > 0 && info.allCount == info.checkedCount) {
		$('#cbCheckAll').attr('checked', true);
	} else {
		$('#cbCheckAll').attr('checked', false);
	}
}

function focusInput(elem) {
	var input = $(elem).find('input[type=text]:first');
	if (input.length == 0) {
		input = $(elem).find('textarea:first');
	}
	input.focus();
}

function prepareLinks() {

	$("a[id^='tp_']").not("a[href^='#']").click(function(e) { if ($(this).attr('disabled')) return;  flipdrive.popup($(this).attr('href')); e.preventDefault(); } )

}

function disableLink(e) {
	// cancels the event
	e.preventDefault();
	return false;
}

function upload_file(changeDir)
{
	var url = "/upload/index";
	if (changeDir && flipdrive.currentMyDriveItem) {
		url = url + "?subdir=" + encodeURIComponent(flipdrive.currentMyDriveItem.attr('value'));
	}

//	window.open (url, "uploadFile","menubar=0,resizable=0,width=615,scrollbars=0,height=500");
	window.open(url,
		 		"", 
		 		"toolbar=0,location=0,menubar=0,width=615,height=500,resizable=0,scrollbars=0");
}


function upload_photo(currentAlbum)
{
	if (!currentAlbum) {

		if ($('div.imageBox').length > 0) {
			currentAlbum = CURRENT_ALBUM_ID;
		} else {

			var checkboxes = $(FILE_CHECKBOXES);
			var check = checkboxes.filter(":checked").get(0);
			currentAlbum = check.value.replace('a', '');
		}
	}


	var url = "/upload/index?photos=1&album_id=" + currentAlbum;

	window.open (url, "uploadFile","menubar=0,resizable=0,width=615,scrollbars=0,height=500");
}

function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
	else
	{
		// You have to sign the code to enable this or allow the action in about:config by changing
		user_pref("signed.applets.codebase_principal_support", true);
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;

		// create a transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;

		// specify the data we wish to handle. Plaintext in this case.
		trans.addDataFlavor('text/unicode');

		// To get the data from the transferable we need two new objects
		var str = new Object();
		var len = new Object();

		var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);

		var copytext=meintext;

		str.data=copytext;

		trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);

		var clipid=Components.interfaces.nsIClipboard;

		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);
	}
}

function checkShowpopup() {
	var href = document.location.href;

	if (href.indexOf('popupurl') > -1) {
		var re = /popupurl=(.*)(&|$)/
		var matches = href.match(re);
		var popup = matches[1];
		//alert(popup);
		flipdrive.popup(popup);
	}
}

function cleanAddParams() {
	var href = document.location.href;
	var re1 = /popupurl=(.*)(&|$)/
	var re2 = /allow_https=1/
	var result = href.replace(re1, '');
	result = result.replace(re2, '');
	result = result.replace(/\?\&/, '');
	return result;
}

function forceCacheUpdate() {
	date = new Date;
	return 'rnd='+date.getTime();
}









