//Will be trickered when the file gets selected
$(document).on('change', '.btn-file :file', function() {
  var input = $(this),
	  numFiles = input.get(0).files ? input.get(0).files.length : 1,
	  label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
  input.trigger('fileselect', [numFiles, label]);
});	
$(document).ready( function() {
	$('.btn-file :file').on('fileselect', function(event, numFiles, label) {
		
		var input = $(this).parents('.input-group').find(':text'),
			log = numFiles > 1 ? numFiles + ' files selected' : label;
		
		if( input.length ) {
			input.val(log);
		} else {
			if( log ) alert(log);
		}      
	});
});
var emails = [];

//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 = '';
				document.getElementById('uploadDiv').style.height = '440px';
				if($('#uploadSettings').length) {
					document.getElementById('uploadSettings').style.height = '440px';
				}
				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'); });
	}
}

//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;
});

//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);

//Will be trickered whne some starts the upload using the upload button
$('body').on('click', '#submit_upload', function(e){
	var customValues = document.getElementById('customValues');
	customValues.innerHTML = customValues.innerHTML + '<input type="hidden" name="id" value="'+value+'">';

	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]);
	var totalSizefiles = 0;

	var files = $("#files")[0].files
	for (i = 0; i < files.length; i++) {
		totalSizefiles+= files[i].size;
	}
	if (totalSizefiles > maxSize * 1048576) {
		document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_file_to_large+'</div>';
	}
	else
	{
		if (validateEmail(emailsTo) || emailsTo == '' || emailsTo == null) {
			if (validateEmail(emailfrom) || emailfrom == '' || emailfrom == null) {
				if(shareOption == 'mail' && emailfrom == '' || emailfrom == null || filesInput == '' || filesInput == null || receiverId == 0 && shareOption == 'mail') {
					document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_fill_fields+'</div>';
				}
				else
				{
					$.ajax({
					    url: 'src/upload.php',
					    type: 'POST',
					    dataType: 'json',
					    xhr: function() {
					        var myXhr = $.ajaxSettings.xhr();
					        if(myXhr.upload){
					            myXhr.upload.addEventListener('progress',uploadProgress, false);
					        }
					        return myXhr;
					    },
					    success: function(res)
						{
							if(res.upload_error == 'true'){
								errorMode();
								document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_upload_error+'</div>';
							}
							if(res.email_error == 'true'){
								errorMode();
								document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_upload_error+'</div>';
							}
							if(res.type_error == 'true'){
								errorMode();
								document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_file_blocked+'</div>';
							}
							if(res.fields == 'false'){
								errorMode();
								document.getElementById("errorDiv").innerHTML = '<div class="alert alert-danger" role="alert">'+msg_fill_fields+'</div>';
							}
						},				
					    data: form,
					    cache: false,
					    contentType: false,
					    processData: false
					});
				}
			}
			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'); });
		}
	}
});

//Will be trickered when the upload is getting progressed
var started_at = new Date();
function uploadProgress(evt) {
	if($('#errorDiv').length) {
		document.getElementById('errorDiv').innerHTML = "";
	}
  	if (evt.lengthComputable) {
  		//Get some info about the upload
	    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
	    var totalMb = evt.total/1048576;
	    var uploadedMb = evt.loaded/1048576;

	    // Append progress percentage.
        var loaded = evt.loaded;
        var total = evt.total;

        // 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 / 125000;
        var remaining_bytes =   total - loaded;
        var seconds_remaining = seconds_elapsed ? remaining_bytes / bytes_per_second : 'calculating' ;

        //Outputs estimated reaminig 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";
	    document.getElementById('progressMb').innerHTML = '<p align="center"><i>' + Math.round(uploadedMb).toFixed(1) + ' MB '+msg_uploaded_of+' ' + Math.round(totalMb).toFixed(1) + ' 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(uploadedMb == totalMb) {
			uploadComplete();
		}
  	} else {
    	document.getElementById('uploadDiv').innerHTML = 'unable to compute';
  	}
}

//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) {
	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 = '<button class="btn btn-success btn-block btn-sm" id="copy-button" data-clipboard-text="'+siteUrl+value+'">'+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) {
  	document.getElementById('uploadProcess').style.display = "none";
	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>';
}

//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);
    }
}