var emails = [];
window.onbeforeunload;

//Checks if the email is an actual real email
function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}
var receiverId = 0;

function openInlinePage(click_id) {
	if(mobileVersion == 'yes') {
		var click = click_id + '_body';
		$(document).ready(function(){ $('#' + click).modal('show'); });
	} else {
		var body = document.getElementsByClassName("settingsBodyContent");
		var nav = document.getElementsByClassName("settingsNav");
		for (var i = 0; i < body.length; i++) {
	   		body[i].style.display = "none";
		}
		for (var i = 0; i < nav.length; i++) {
	   		nav[i].style.fontWeight = "normal";
		}

		document.getElementById(click_id).style.fontWeight = 'bold';
		document.getElementById(click_id + '_body').style.display = "block";
	}	
}

//Function will be trickered when someone clicks the Add more button
function addReceiver() {
	var emailInput = document.getElementById("emailTo").value;
	if (validateEmail(emailInput)) {
		if (emailInput == '' || emailInput == null) {
			$('#receivers').addClass('shake animated has-error').one('animationEnd webkitAnimationEnd',function () { $("#receivers").removeClass('shake animated has-error'); });
		} 
		else
		{
			var emailExist = emails.indexOf(emailInput);
			if(emailExist == -1) {
				receiverId++;
				emails.push(emailInput);
				var divReceivers = document.getElementById('receiverList');
				var divHiddenReceivers = document.getElementById('receiverHiddenList');
				var emailToValue = document.getElementById("emailTo").value;

				divReceivers.innerHTML = divReceivers.innerHTML + '<p style="margin: 0 0 0;" id="receiver_'+receiverId+'"><i class="fa fa-angle-right"></i> '+emailToValue+' <a onclick="removeReceiver(\''+receiverId+'\',\''+emailToValue+'\');"><i class="fa fa-trash" id="receiver_'+receiverId+'"></a></p>';
				divHiddenReceivers.innerHTML = divHiddenReceivers.innerHTML + '<input type="hidden" name="email_to[]" class="emailToInput" id="email_to_'+receiverId+'" value="'+emailToValue+'">';
				document.getElementById("emailTo").value = '';

				if(receiverId == 1) {
					var uploadBox = $('#uploadDiv');
					//get the current height
					var uploadBoxHeight = uploadBox.height();
					//Set the height of the upload div
					uploadBox.height(uploadBoxHeight + 40);

					if($('#uploadSettings').length) {
						$('#uploadSettings').height(uploadBoxHeight + 40);
					}
				}
				
				document.getElementById('receivers').style.display = "block";
				document.getElementById('receiverList').style.display = "block";
			} else {
				$('#receivers').addClass('shake animated has-error').one('animationEnd webkitAnimationEnd',function () { $("#receivers").removeClass('shake animated has-error'); });
				document.getElementById("emailTo").value = '';
			}
		}
	} else {
		$('#emailTo').addClass('shake animated has-error').one('animationEnd webkitAnimationEnd',function () { $("#emailTo").removeClass('shake animated has-error'); });
	}
}

//Check if there are commas in the list, if so then split them up in different inputs
$('#emailTo').on('blur', function() {
    var input = $(this);
    var value = $(input).val();
    //If comma
    if(value.indexOf(',') > -1) {
        var email_array = value.split(',');

        //Make field empty
        $(input).val('');

        //Add every email to the list
        $.each(email_array, function( key, value ) {
            $(input).val(value);
            addReceiver();
        });
    }
});

//Will be trickered when someone removes the recipient
Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}
Array.prototype.delete = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};
function removeReceiver(id, email_value) {
	emails.delete(email_value);
	document.getElementById("receiver_"+id).remove();
	document.getElementById("email_to_"+id).remove();
}

//Values of the progress round
$(function() {
    $(".progressCircle").knob({
    	'min':0,
        'max':100,
        'readOnly': true,
        'width': 250,
        'height': 250,
        'fgColor': '#828282',
        'thickness': 0.2,
    });
});

//Will be trickered when someone submits the password
$('body').on('click', '#submitpassword', function(){
	document.getElementById("errorDiv").innerHTML = "";
	document.getElementById('downloadPassword').style.display = "none";
	document.getElementById('downloadLogo').innerHTML = '<i class="fa fa-check-square-o fa-5x" style="padding-top: 100px;"></i>';	
	document.getElementById("statusDownload").innerHTML = msg_download_started;
});

//Will make popup if you're leaving the page while uploading
function preventUploadLeave() {
    window.onbeforeunload = function() {
        return 'Are you sure you want to navigate away from this page?';
    };
}

//Creating a random string as upload ID
function shuffle(string) {
    var parts = string.split('');
    for (var i = parts.length; i > 0;) {
        var random = parseInt(Math.random() * i);
        var temp = parts[--i];
        parts[i] = parts[random];
        parts[random] = temp;
    }
    return parts.join('');
}
var long_value = shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
var value = long_value.substr(0, 7);

$(document).ready(function () {
	if($('#uploadDiv').length) {
		var previewNode = document.querySelector("#uploaded-file");
		previewNode.id = "";
		var previewTemplate = previewNode.parentNode.innerHTML;
		previewNode.parentNode.removeChild(previewNode);

		largerForm = false;

		Dropzone.autoDiscover = false;
		new Dropzone(document.body, {
			url: "src/upload.php",
			previewsContainer: "#upload-form-list",
			previewTemplate: previewTemplate,
		    autoProcessQueue: false,
		    forceFallback: false,
		    uploadMultiple: true,
		    parallelUploads: maxFiles,
		    maxThumbnailFilesize: maxSize,
		    maxFilesize: maxSize,
		    maxFiles: maxFiles,
		    acceptedFiles: "",
		    clickable: "#files",

		    init: function () {
		        var submitButton = document.querySelector("#submit_upload");
		        var wrapperThis = this;

		        submitButton.addEventListener("click", function (e) {
		        	e.preventDefault();
					
					//Getting formdata
					var filesInput = document.getElementById("files").value;
					var emailfrom = document.getElementById("emailFrom").value;
					var shareOption = document.getElementById("share").value;
					var emailsTo = document.getElementById("emailTo").value;
					for (var i = 0; i < emailsTo.length; i++) {
					    receiverId++;
					}

					var form = new FormData($('#uploadForm')[0]);

					if (validateEmail(emailsTo) || emailsTo == '' || emailsTo == null) {
						if (validateEmail(emailfrom) || emailfrom == '' || emailfrom == null) {
							if(shareOption == 'mail' && emailfrom == '' || emailfrom == null || receiverId == 0 && shareOption == 'mail') {
								document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_fill_fields+'</div>';
							}
							else
							{
								if (wrapperThis.getQueuedFiles().length > 0) {   
									process_activate = true;
									wrapperThis.processQueue();
                                    preventUploadLeave();
								}
								else
								{
									document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_fill_fields+'</div>';
								}
							}
						}
						else
						{
							$('#emailFrom').addClass('shake animated has-error').one('animationEnd webkitAnimationEnd',function () { $("#emailFrom").removeClass('shake animated has-error'); });
						}
					}
					else
					{
						$('#emailTo').addClass('shake animated has-error').one('animationEnd webkitAnimationEnd',function () { $("#emailTo").removeClass('shake animated has-error'); });
					}
		        });

		        this.on("addedfile", function (file) {
		        	document.getElementById("errorDiv").innerHTML = "";
		        	$('#submit_upload').prop('disabled', false);

		        	if(largerForm == false) {
						//Set the height of the upload div
						$('#uploadDiv').height($('#uploadDiv').height() + 40);

						if($('#uploadSettings').length) {
							$('#uploadSettings').height($('#uploadSettings').height() + 40);
						}

						largerForm = true;
		        	}
		        	if(total_size_left - file.size > 0) {
		        		var fileTypeArray = disallowedFiles.split(',');

		        		if(fileTypeArray.indexOf(file.type) != -1) {
				        	document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_file_blocked+'</div>';
				        	//Remove the file
			        		wrapperThis.removeFile(file);
				        }
				        else
				        {
				        	total_size_left -= file.size;
				        	document.getElementById("total_upload_size").innerHTML = "(" + Number(Math.round(total_size_left / 1073741824+'e2')+'e-2')+" GB "+msg_remaining + ")";
				        }
				    }
			        else
			        {
			        	//Remove the file
			        	total_size_left -= file.size;
			        	document.getElementById("total_upload_size").innerHTML = "(" + Number(Math.round(total_size_left / 1073741824+'e2')+'e-2')+" GB "+msg_remaining + ")";
			        	wrapperThis.removeFile(file);
			        	document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_file_to_large+'</div>';
			        }
		        });

		        this.on('sendingmultiple', function (data, xhr, formData) {
		        	formData.append('id', value);
		        	formData.append('share', $('input[name=share]').val());
		        	formData.append('email_from', $('input[name=email_from]').val());
		        	//formData.append('email_to[]', $('input[name^=email_to]').val());
		        	formData.append('destruct', $('input[name=destruct]').val());
		        	formData.append('message', $('textarea[name=message]').val());
		        	formData.append('password', $('input[name=password]').val());

					var email_to_values = [];
					var fields = document.getElementsByName("email_to[]");
					for(var i = 0; i < fields.length; i++) {
					    //email_to_values.push(fields[i].value);
					    formData.append('email_to[]', fields[i].value);
					}

                    //Cancel upload when button is clicked.
					var cancelButton = document.getElementById('cancelUpload');
                    cancelButton.addEventListener("click", function(){
                        if(confirm('Are you sure ?')) {
                            process_activate = false;
                            wrapperThis.removeAllFiles(true);
                            document.getElementById("progresscircle").value = '0';
                            document.getElementById('uploadSuccess').style.display = "none";
                            document.getElementById('uploadingDiv').style.display = "none";
                            document.getElementById('uploadingDivSocial').style.display = "none";
                            document.getElementById('uploadDiv').style.display = "block";
                            document.getElementById('uploadDivSocial').style.display = "block";
                        }
                    });
		        });

		        this.on("removedfile", function(file) {
		        	total_size_left += file.size;
			        document.getElementById("total_upload_size").innerHTML = "(" + Number(Math.round(total_size_left / 1073741824+'e2')+'e-2')+" GB "+msg_remaining + ")";
		        });

		        this.on("totaluploadprogress", function(progress, totalBytes, totalBytesSent) {
		        	if(process_activate == true) {
			        	uploadProgress(progress, totalBytes, totalBytesSent);
			        }
		        });

	            //When maximum file selection is reached.
	            this.on("maxfilesexceeded", function(file) {
	            	//Remove the file
	            	total_size_left -= file.size;
			        document.getElementById("total_upload_size").innerHTML = "(" + Number(Math.round(total_size_left / 1073741824+'e2')+'e-2')+" GB "+msg_remaining + ")";
			        wrapperThis.removeFile(file);
			        document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_max_files+'</div>';
	            });

	            this.on("error", function(file, response) {
	                if(response == 'size_to_big') {
						document.getElementById('uploadSuccess').style.display = "none";
						document.getElementById('uploadingDiv').style.display = "none";
						document.getElementById('uploadingDivSocial').style.display = "none";
						document.getElementById('uploadDiv').style.display = "block";
						document.getElementById('uploadDivSocial').style.display = "block";
	                	document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_file_to_large+'</div>';
	                }
	            });
		    }
		});
		
		$(document.body).bind('dragover', function(){
	        document.getElementById('drop-overlay').style.display = "block";
	    });
	    $(document.body).bind('dragleave', function(){
	        document.getElementById('drop-overlay').style.display = "none";
	    });
	    $(document.body).bind('drop', function(){
	        document.getElementById('drop-overlay').style.display = "none";
	    });
	}
});

//Will be trickered when the upload is getting progressed
var executed = false;
var started_at = 0;

function uploadProgress(progress,uploadTotal,uploadTotalSent) {
	if(!executed) {
		executed = true;
		started_at = new Date();
	}

	if($('#errorDiv').length) {
		document.getElementById('errorDiv').innerHTML = "";
	}
		//Get some info about the upload
    var percentComplete = progress;
    var totalMb = (Math.round(uploadTotal * 100 / (1000 * 1000)) / 100).toFixed(1);
    var uploadedMb = (Math.round(uploadTotalSent * 100 / (1000 * 1000)) / 100).toFixed(1);

    // Append progress percentage.
    var loaded = uploadTotalSent;
    var total = uploadTotal;

    // Time Remaining
    var seconds_elapsed =   (new Date().getTime() - started_at.getTime())/1000;

    var bytes_per_second =  (seconds_elapsed) ? (loaded / seconds_elapsed) : 0 ;
    var Mbytes_per_second = bytes_per_second / 1000000;
    var remaining_bytes =   total - loaded;
    var seconds_remaining = (seconds_elapsed) ? (remaining_bytes / bytes_per_second) : 'calculating' ;

    //Outputs estimated remaining upload time
    if(seconds_remaining > 3600) {
    	time_sum = seconds_remaining / 3600;
    	progress_time = '&plusmn; '+Math.round(time_sum).toFixed(1)+' '+msg_hours+' '+msg_remaining;
    }
    else if(seconds_remaining > 60) {
    	time_sum = seconds_remaining / 60;
    	progress_time = '&plusmn; '+Math.round(time_sum)+' '+msg_minutes+' '+msg_remaining;
    }
    else
    {
    	progress_time = '&plusmn; '+Math.round(seconds_remaining)+' '+msg_seconds+' '+msg_remaining;
    }

    //Settings the progress styles and inserting data
    document.getElementById('uploadDiv').style.display = "none";
    document.getElementById('uploadDivSocial').style.display = "none";
    if($('#uploadSettings').length) {
    	document.getElementById('uploadSettings').style.display = "none";
   	}
    document.getElementById('uploadingDiv').style.display = "block";
    document.getElementById('uploadingDivSocial').style.display = "block";
    if(seconds_elapsed < 10) {
    	document.getElementById('progressMb').innerHTML = '<p align="center"><i>' + uploadedMb + ' MB '+msg_uploaded_of+' ' + totalMb + ' MB </i></p><p>'+progress_time+'</p>';
    }
    else
    {
    	document.getElementById('progressMb').innerHTML = '<p align="center"><i>' + uploadedMb + ' MB '+msg_uploaded_of+' ' + totalMb + ' MB ('+(Mbytes_per_second).toFixed(1)+' MB/s)</i></p><p>'+progress_time+'</p>';
    }
    document.getElementById("progresscircle").value = percentComplete.toString();
    $('.progressCircle')
		.val(percentComplete.toString())
		.trigger('change');

	if (totalMb > maxSize) {
		//uploadSize();
	}
	if(uploadTotal == uploadTotalSent) {
		uploadComplete();
	}
}

//Will be trickered when somone selects another language
function changeLanguage() {
	var lang = document.getElementById('languagePicker').value;
	window.location.href = 'src/action.php?action=lang&lang='+lang;
}

//Will be trickered when the upload has been completed
function uploadComplete(evt) {
    window.onbeforeunload = null;
	setTimeout(function() {
		var shareOption = document.getElementById("share").value;
		if(shareOption == 'mail') {
			document.getElementById('emailMessage').style.display = "block";
			document.getElementById('okButton').style.display = "block";
		}
		if(shareOption == 'link') {
			document.getElementById('linkMessage').style.display = "block";
			document.getElementById('downloadLink').innerHTML = '<a href="' + siteUrl + value + '">'  + siteUrl + value + '</a>';
			document.getElementById('copyButton').innerHTML = '<input id="copyUrl" value="'+siteUrl+value+'" style="z-index: -100; opacity: 0;"><button class="btn btn-success btn-block btn-sm" id="copy-button" data-clipboard-target="#copyUrl">'+msg_copy_url+'</button>';
            activateCopy();
		}
		document.getElementById('uploadProcess').style.display = "none";
		document.getElementById('uploadSuccess').style.display = "block";
	}, 1000);
}

//Will be trickered when the upload failed
function uploadFailed(evt) {
  	alert("There was an error while attempting to upload the file.");
}

//Will be trickered when the upload size is too large
/*function uploadSize(evt) {
  	
}*/

//Will be trickered when someone cancels the upload
function uploadCanceled(evt) {
  	alert("The upload has been canceled by the user or the browser dropped the connection.");
}

//Will be trickered when someone clicks on the settings button (Gear button)
function openSettings(evt) {
  	document.getElementById('uploadSettings').style.display = "block";
}

function closeSettings(evt) {
	document.getElementById('uploadSettings').style.display = "none";
}

//Will be trickered when somone clicks on the share type email
function shareEmail() {
	var share = 'mail';
	document.getElementById('EmailToSection').style.display = "block";
	document.getElementById('EmailFromSection').style.display = "block";
	document.getElementById('share').value = 'mail';

}

//Will be trickered when somone clicks on the share type link
function shareLink() {
	var share = 'link';
	document.getElementById('EmailToSection').style.display = "none";
	document.getElementById('EmailFromSection').style.display = "none";
	document.getElementById('share').value = 'link';
}

//Will be trickered when someone selects the upload settings tab
function uploadSettings() {
	document.getElementById('languageSettingsContent').style.display = "none";
	document.getElementById('termsContent').style.display = "none";
	document.getElementById('aboutContent').style.display = "none";
	document.getElementById('upload_settings_nav').style.fontWeight = "bold";
	document.getElementById('terms_nav').style.fontWeight = "normal";
	document.getElementById('about_nav').style.fontWeight = "normal";
	document.getElementById('language_settings_nav').style.fontWeight = "normal";
	document.getElementById('uploadSettingsContent').style.display = "block";
}

//Will be trickered when someone selects the language settings tab
function languageSettings() {
	document.getElementById('uploadSettingsContent').style.display = "none";
	document.getElementById('termsContent').style.display = "none";
	document.getElementById('aboutContent').style.display = "none";
	document.getElementById('terms_nav').style.fontWeight = "normal";
	document.getElementById('about_nav').style.fontWeight = "normal";
	document.getElementById('upload_settings_nav').style.fontWeight = "normal";
	document.getElementById('language_settings_nav').style.fontWeight = "bold";
	document.getElementById('languageSettingsContent').style.display = "block";
}

//Will be trickered when someone selects the terms of service tab
function viewTerms() {
	document.getElementById('uploadSettingsContent').style.display = "none";
	document.getElementById('termsContent').style.display = "block";
	document.getElementById('terms_nav').style.fontWeight = "bold";
	document.getElementById('upload_settings_nav').style.fontWeight = "normal";
	document.getElementById('language_settings_nav').style.fontWeight = "normal";
	document.getElementById('languageSettingsContent').style.display = "none";
	document.getElementById('aboutContent').style.display = "none";
	document.getElementById('about_nav').style.fontWeight = "normal";
}

//Will be trickered when someone selects the about tab
function viewAbout() {
	document.getElementById('uploadSettingsContent').style.display = "none";
	document.getElementById('termsContent').style.display = "none";
	document.getElementById('terms_nav').style.fontWeight = "normal";
	document.getElementById('upload_settings_nav').style.fontWeight = "normal";
	document.getElementById('language_settings_nav').style.fontWeight = "normal";
	document.getElementById('languageSettingsContent').style.display = "none";
	document.getElementById('aboutContent').style.display = "block";
	document.getElementById('about_nav').style.fontWeight = "bold";
}

//Will be trickered when someone sets the destruction to true
function destructTrue() {
	document.getElementById('destruct').value = 'yes';
}

//Will be trickered when somone sets the destruction to false
function destructFalse() {
	document.getElementById('destruct').value = 'no';
}

//Will be trickered when a error occured
function errorMode() {
	document.getElementById('uploadDiv').style.display = "block";
	document.getElementById('uploadDivSocial').style.display = "block";
	document.getElementById('uploadSettings').style.display = "none";
	document.getElementById('uploadingDiv').style.display = "none";
	document.getElementById('uploadingDivSocial').style.display = "none";
}

//Will be trickered when somone clicks on the password submit button
$('#submit_password').click(function()
{
	//Getting formdata
	var downloadId=$("#download_id").val();
	var password=$("#password").val();
	var formAction = 'download';
	var dataString = 'action='+formAction+'&download_id='+downloadId+'&password='+password;
	
	//Checks if the password is not empty
	if (password==null || password=="")
	{
		document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_fill_fields+'</div>';
	}else{
		//Make the post to the php file
		$.ajax({
			type: "POST",
			url: 'src/action.php',
			dataType: 'json',
			data: dataString,
			cache: false,
			success: function(data){
				if(data.password == 'true')
				{
					window.location = '../../../../src/action.php';
				}
				if(data.password == 'false')
				{
					document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_wrong_pass+'</div>';
				}
			}
		});
	}
	return false;
});

//Will be trickered when someone clicks the download button
$('#submitpass').click(function()
{
	if(document.getElementById('password').value != '') {
		document.getElementById('downloadForm').style.display = "none";
		document.getElementById('downloadSuccess').style.display = "block";
	}
});
$('#submitdownload').click(function()
{
	document.getElementById('downloadForm').style.display = "none";
	document.getElementById('downloadSuccess').style.display = "block";
});

//________________________________________Plugin coding________________________________________
$(function () {
    $('.button-checkbox').each(function () {

        // Settings
        var $widget = $(this),
            $button = $widget.find('button'),
            $checkbox = $widget.find('input:checkbox'),
            color = $button.data('color'),
            settings = {
                on: {
                    icon: 'glyphicon glyphicon-check'
                },
                off: {
                    icon: 'glyphicon glyphicon-unchecked'
                }
            };

        // Event Handlers
        $button.on('click', function () {
            $checkbox.prop('checked', !$checkbox.is(':checked'));
            $checkbox.triggerHandler('change');
            updateDisplay();
        });
        $checkbox.on('change', function () {
            updateDisplay();
        });

        // Actions
        function updateDisplay() {
            var isChecked = $checkbox.is(':checked');

            // Set the button's state
            $button.data('state', (isChecked) ? "on" : "off");

            // Set the button's icon
            $button.find('.state-icon')
                .removeClass()
                .addClass('state-icon ' + settings[$button.data('state')].icon);

            // Update the button's color
            if (isChecked) {
                $button
                    .removeClass('btn-default')
                    .addClass('btn-' + color + ' active');
            }
            else {
                $button
                    .removeClass('btn-' + color + ' active')
                    .addClass('btn-default');
            }
        }

        // Initialization
        function init() {

            updateDisplay();

            // Inject the icon if applicable
            if ($button.find('.state-icon').length == 0) {
                $button.prepend('<i class="state-icon ' + settings[$button.data('state')].icon + '"></i> ');
            }
        }
        init();
    });
});
//Load all photos before site load
function preloadImages(srcs, imgs) {
    var img;
    var remaining = srcs.length;
    for (var i = 0; i < srcs.length; i++) {
        img = new Image();
        img.onload = function() {
        };
        img.src = srcs[i];
        imgs.push(img);
    }
}