/** whitelist **/
$(document).ready(function () {
	var xhr;
	var fullScreenOverlay = $('.contactupload-overlay');
	var innerOffsetBox = fullScreenOverlay.find('.inner-fullscreen-offset');

	var checkContactUploaderArrowStatus = function () {
		//var $top = Math.max(0, (($(window).height() - $(".contactupload-overlay .navigation-overlay").outerHeight()) / 2)) - 69 + "px";
		//$(".contactupload-overlay .navigation-overlay").css("top", $top);
		var $option = $(".contactupload-overlay .options.active"),
				$set = $option.attr("data-set");
		$(".contactupload-overlay .navigation-overlay .active").removeClass("active");
		$(".contactupload-overlay .u-navigationCircle[data-set='" + $set + "']").addClass("active");
		$(".contactupload-overlay .u-navigationCircle.active").prevAll().addClass("u-setDone");
	};

	$('.contactupload-overlay .close-overlay').bind({
		click: function () {
			removeContactUploadOverlay();
			return false;
		}
	});

	$('.contactupload-overlay .navigation-overlay a').not(".u-gotOSummary").bind({
		click: function () {
			var $this = $(this),
					$set = $this.attr("data-set"),
					$navigation = $this.attr("data-navigation"),
					$options = $(".contactupload-overlay .options"),
					setActive = $(".contactupload-overlay .options.active"),
					$activeSet = setActive.attr("data-set");
			if ($set == $activeSet) {
				return false;
			} else {
				var validate = validateBlock($this, setActive);
				if (validate) {
					//$(".c-Footer a").removeClass("active");
					var setTwo = $(".contactupload-overlay .options[data-set='" + $set + "']");
					setActive.removeClass("active").fadeOut(800, function () {
						var twoHeight = setTwo.height();
						var windowHeight = $(window).height();
						var offsetTwo = (windowHeight / 2) - (twoHeight / 2) - 69;// + windowOffset;
						setTwo.css('top', offsetTwo).fadeIn(800, function () {
							setTwo.addClass("active");
							lastContactUploaderSlideClose(setTwo);
							checkContactUploaderArrowStatus();
							$(".csvcontactupload .c-option-csvUpload .addperson-text").text("UPLOAD TEMPLATE");
						});
					});
				}
			}
			return false;
		}
	});
	function validateBlock($this, $activeOption) {
		var $set = $this.attr("data-set"),
				$navigation = $this.attr("data-navigation"),
				$options = $(".contactupload-overlay .options"),
				setActive = $(".contactupload-overlay .options.active"),
				$activeSet = setActive.attr("data-set");

		var $result = true;
		if ($this.prev(".u-navigationCircle").length) {
			if (!$this.prev(".u-navigationCircle").hasClass("u-setDone")) {
				$result = false;
			}
		} else if (!$this.hasClass("u-setDone")) {

			if ($(".contactupload-overlay .options.active").find(".option").length) {
				if (!$(".contactupload-overlay .options.active").find(".option.active").length) {
					$result = false;
				}
			} else if ($(".contactupload-overlay .options.active").find(".existing-names").length) {
				if (!$(".contactupload-overlay .options.active").find(".existing-names a.active").length) {
					$result = false;
				}
			} else if ($(".contactupload-overlay .c-Circle-Option").length) {
				if (!$(".contactupload-overlay .c-Circle-Option.active").length) {
					$result = false;
				}
			} else {

			}


			if ($(".contactupload-overlay .options.active .c-CirclesOption").length) {
				$result = false;
			}
		}
		return $result;
	}

	function isValid(str){
		return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
	}

	var csvupload_existing_names_actions = function () {
		$('.csvcontactupload .existing-names').on('click', 'a', function () {
			$(".c-input-error").removeClass(".c-input-error");

			var $this = $(this),
					$val = $this.text(),
					$parents = $this.parents(".option-container"),
					$set = $this.parents('.options').attr("data-set");

			if (!$parents.find(".option-container-firstbox").hasClass("isHidden")) {
				$parents.find(".option-container-firstbox").fadeOut(200, function () {
					$parents.find(".option-container-secondbox").fadeIn(200);
				});
			}

			$this.parents(".existing-names").find("a").removeClass("active");
			$this.addClass("active");

			if ($set == "three") {
				var $uid = $this.attr("data-uid"),
						$nameButton = $("#contact-add-name"),
						$surnameButton = $("#contact-add-surname"),
						$vehiclenumberButton = $("#contact-add-vehiclenumber"),
						$firstname = $this.attr("data-name"),
						$surname = $this.attr("data-surname"),
						$vehiclenumber = $this.attr("data-vehiclenumber");

				$nameButton.val("").trigger("keyup").val($firstname);
				if(!isValid($firstname) || '' == $firstname){
					$nameButton.addClass("c-input-error");
				}

				$surnameButton.val("").trigger("keyup").val($surname);
				if(!isValid($surname) || '' == $surname){
					$surnameButton.addClass("c-input-error");
				}

				$vehiclenumberButton.val("").trigger("keyup").val($vehiclenumber);
				if(!isValid($vehiclenumber) || '' == $vehiclenumber){
					$vehiclenumberButton.addClass("c-input-error");
				}
				$parents.find(".c-BtnClear").show();
				$(".c-ContactUpload-ContactSelection .c-ContactUpload-ContactSelection-BtnSave").text("SAVE").attr("data-update", $uid);
				$(".c-ContactUpload-ContactSelection .c-ContactUpload-ContactSelection-BtnClear").show();
			}

			checkContactUploaderArrowStatus();
			return false;
		}).on("click", ".c-contact-delete", function () {
			var $this = $(this),
					$parents = $this.parents("a"),
					$uid = $parents.attr("data-uid");
			$parents.fadeOut(function(){
				$parents.remove();
			});
			checkUploadFooterButton();

			// update assign widget contact list same
			var $assignContact = $(".assignwidget-overlay .c-AssignContact-Contacts .c-AssignContact-Box-Contacts-Item a[data-uid='" + $uid + "']");
			if ($assignContact.length) {
				$assignContact.remove();
			}
			return false;
		});
	};
	csvupload_existing_names_actions();

	$('.c-Upload-Button').bind({
		click: function () {
			removeContactUploadOverlay();
			addContactUploadOverlay();
			/*extendOverlay('contactupload');*/
			var outerTarget = fullScreenOverlay.find('.csvcontactupload').css({display: 'block'});
			$('.csvcontactupload .set-two').css({display: 'none', top: 0});

			var innerTarget = outerTarget.find('.set-one');
			var targetHeight = innerTarget.height();
			var windowHeight = $(window).height();
			var windowOffset = $(window).scrollTop();
			var offsetTop = (windowHeight / 2) - (targetHeight / 2) - 50;// + windowOffset;

			innerTarget.css({top: offsetTop, display: 'block'});
			outerTarget.fadeIn(800, function () {
				innerTarget.addClass("active");
				checkContactUploaderArrowStatus();
				//$(".contactupload-overlay .navigation-overlay .u-navigationCircle.active").addClass("u-setDone");
			});

			return false;
		}
	});

	$('.csvcontactupload').on("click", ".c-Footer.c-ContactTemplateDownload-Footer", function () {
		$('.contactupload-overlay .navigation-overlay a.u-navigationCircle.active').addClass("u-setDone").next().trigger("click");
		return false;
	}).on("click", ".c-Footer.c-ContactDownload-Assign-Footer a", function () {
		var $this = $(this);
		var setOne = $(".contactupload-overlay .options.active");
		var setNext = $(".contactupload-overlay .options.active").next(".options");

		if (!$this.hasClass("c-Footer-Cancel-Button")) {
			setOne.removeClass("active").fadeOut(1000, function () {
				$(".contactupload-overlay .close-overlay").trigger("click");
				$(".c-Assignwidget-Button:first").trigger("click");
			});
		} else {
			var setOne = $(".contactupload-overlay .options.active");
			var setNext = $(".contactupload-overlay .options.c-Option-ContactPending");
			setOne.removeClass("active").fadeOut(800, function () {
				var twoHeight = setNext.height();
				var windowHeight = $(window).height();
				var offsetTwo = (windowHeight / 2) - (twoHeight / 2) - 69;// + windowOffset;

				setNext.css('top', offsetTwo).fadeIn(800, function () {
					setNext.addClass("active");
					$('.contactupload-overlay .navigation-overlay').removeClass("active");
					lastContactUploaderSlideClose(setNext);
				});
			});
		}
		return false;
	}).on("click", ".c-Option-ContactPending .c-AssignPending-Footer a", function () {
		var $this = $(this);
		var setOne = $(".contactupload-overlay .options.active");
		var setNext = $(".contactupload-overlay .options.active").next(".options");

		fullScreenOverlay.find(".navigation-overlay").hide();
		
		if (!$this.hasClass("c-Footer-Cancel-Button")) {
			setOne.removeClass("active").fadeOut(1000, function () {
				$(".contactupload-overlay .close-overlay").trigger("click");
				$(".c-Assignwidget-Button:first").trigger("click");
			});
		} else {
			var setOne = $(".contactupload-overlay .options.active");
			var setNext = $(".contactupload-overlay .options.c-option-done");
			setOne.removeClass("active").fadeOut(800, function () {
				var twoHeight = setNext.height();
				var windowHeight = $(window).height();
				var offsetTwo = (windowHeight / 2) - (twoHeight / 2) - 69;// + windowOffset;

				setNext.css('top', offsetTwo).fadeIn(800, function () {
					setNext.addClass("active");
					$('.contactupload-overlay .navigation-overlay').removeClass("active");
					lastContactUploaderSlideClose(setNext);
				});
			});
		}
		return false;
	}).on("click", ".c-Footer.c-ContactDownload-Footer", function () {
		var namesError = $(".contactupload-overlay .set-three .existing-names a.c-namesError");

		if (namesError.length) {
			$(this).addClass("c-footerError").delay(2500).queue(function () {
				/*$(this).removeClass("c-footerError");
				 $(this).dequeue();*/
			});
			$(this).find("a").text("PLEASE AMEND ANY CONTACTS IN RED");
			namesError.addClass("hvr-buzz-out-hover").delay(5000).queue(function () {
				$(this).removeClass("hvr-buzz-out-hover");
				$(this).dequeue();
			});
		} else {
			var $this = $(this);
			var setOne = $(".contactupload-overlay .options.active");
			var setNext = $(".contactupload-overlay .options.active").next(".options");
			setOne.removeClass("active").fadeOut(800, function () {
				var twoHeight = setNext.height();
				var windowHeight = $(window).height();
				var offsetTwo = (windowHeight / 2) - (twoHeight / 2) - 69;// + windowOffset;

				setNext.css('top', offsetTwo).fadeIn(800, function () {
					setNext.addClass("active");
					$('.contactupload-overlay .navigation-overlay').removeClass("active");
					lastContactUploaderSlideClose(setNext);
				});
			});
		}
		return false;
	}).on("click", ".option-container-firstbox .option-container-firstbox-BtnGo", function () {
		var $this = $(this),
				$parents = $this.parents(".option-container");
		if (!$parents.find(".option-container-firstbox").hasClass("isHidden")) {
			$parents.find(".option-container-firstbox").fadeOut(200, function () {
				$parents.find(".option-container-secondbox").fadeIn(200).find(".c-add-input").focus();
				$(".c-ContactUpload-ContactSelection .c-ContactUpload-ContactSelection-BtnSave").text("ADD").attr("data-update", "");
			});
		}
		return false;
	}).on("click", ".c-ContactUpload-ContactSelection .c-ContactUpload-ContactSelection-BtnClear", function () {
		var $this = $(this),
				$parents = $this.parents(".option-container"),
				existing_div = $parents.find(".existing-div");
		$(".c-ContactUpload-ContactSelection .c-add-input").val("");
		//if (!$parents.find(".option-container-firstbox").hasClass("isHidden")) {
		$parents.find(".option-container-secondbox").fadeOut(200, function () {
			$parents.find(".option-container-firstbox").fadeIn(200);
		});
		//}
		existing_div.find(".existing-names .active").removeClass("active");
		return false;
	}).on("click", ".c-ContactUpload-ContactSelection .c-ContactUpload-ContactSelection-BtnSave", function () {
		var $this = $(this),
				$update = $this.attr("data-update"),
				optioncontainer = $this.parents(".option-container"),
				$ContactUploadButtons = $(".c-ContactUpload-ContactSelection .c-add-input"),
				existing_div = $this.parents(".option-container"),
				existing_name = existing_div.find(".existing-names"),
				$nameButton = $("#contact-add-name"),
				$nameButtonval = $("#contact-add-name").val(),
				$surnameButton = $("#contact-add-surname"),
				$surnameButtonval = $("#contact-add-surname").val(),
				$vehiclenumberButton = $("#contact-add-vehiclenumber"),
				$vehiclenumberButtonval = $("#contact-add-vehiclenumber").val();

		var DateError = function ($error) {
			optioncontainer.find(".ContactUpload-Box-overlay").addClass("active").find(".c-Contentbox span").html($error);
			setTimeout(function () {
				optioncontainer.find(".ContactUpload-Box-overlay").removeClass("active");
			}, 4000);
		};

		if($(".c-ContactUpload-ContactSelection .c-input-error").length){
			DateError("Oops! Pls fix special characters!");
		} else if ("" !== $nameButtonval && "" !== $surnameButtonval && "" !== $vehiclenumberButtonval) {

			existing_name.find("a").find(".active").removeClass("active");

			if ("" !== $update) {
				existing_name.find("a[data-uid=" + $update + "]").attr({"data-name": $nameButtonval, "data-surname": $surnameButtonval, "data-vehiclenumber": $vehiclenumberButtonval}).html($nameButtonval + ' ' + $surnameButtonval + '<span class="c-contact-delete icon-cross c-circle" href="#"></span>').removeClass("c-namesError");
				// update assign widget contact list same
				var $assignContact = $(".assignwidget-overlay .c-AssignContact-Contacts .c-AssignContact-Box-Contacts-Item a[data-uid='" + $update + "']");
				if ($assignContact.length) {
					$assignContact.attr({"data-name": $nameButtonval, "data-surname": $surnameButtonval, "data-vehiclenumber": $vehiclenumberButtonval}).text($nameButtonval + ' ' + $surnameButtonval);
				}
			} else {
				var $uid = parseInt(existing_name.find("a").last().attr("data-uid")) + 1;
				existing_name.append('<a data-uid="' + $uid + '" data-name="' + $nameButtonval + '" data-surname="' + $surnameButtonval + '" data-vehiclenumber="' + $vehiclenumberButtonval + '" href="#" class="active">' + $nameButtonval + ' ' + $surnameButtonval + '<span class="c-contact-delete icon-cross c-circle" href="#"></span></a>');
				
				// add new contact to assign widget contact list same
				var $assignContact = $(".assignwidget-overlay .c-AssignContact-Contacts .c-AssignContact-Box-Contacts-List");
				$assignContact.prepend('<div class="c-AssignContact-Box-Contacts-Item ui-draggable ui-draggable-handle"><a href="#" data-group="" data-uid="' + $uid + '" data-name="' + $nameButtonval + '" data-surname="' + $surnameButtonval + '" data-vehiclenumber="' + $vehiclenumberButtonval + '">' + $nameButtonval + ' ' + $surnameButtonval + '</a><span href="#" class="c-AssignContact-Clear icon-cross"></span></div>');
				dragAssignHandle();
			}
			csvupload_existing_names_actions();
			$(".c-ContactUpload-ContactSelection .c-ContactUpload-ContactSelection-BtnClear").trigger("click").hide();
		} else {
			DateError("Oops! Pls amend anything you’ve left blank!");
		}
		checkUploadFooterButton();
		return false;
	}).on("keyup", ".c-ContactUpload-ContactSelection .c-add-input", function () {
		var $this = $(this),
				$val = $this.val(),
				$startTimeInput = $("#c-TimerSelect-EndTime");
		if ("" !== $val) {
			$(".c-ContactUpload-ContactSelection .c-ContactUpload-ContactSelection-BtnClear").show();
		}

		$this.removeClass("c-input-error");
		if (!isValid($val)) {
			$this.addClass("c-input-error");
		}
		return false;
	});

	var checkUploadFooterButton = function () {
		if (!$(".contactupload-overlay .set-three .existing-names a.c-namesError").length) {
			$(".c-ContactDownload-Footer").removeClass("c-footerError").find("a").text("UPLOAD");
			$(".contactupload-overlay .navigation-overlay .u-navigationCircle.active").addClass("u-setDone");
		}
	};

	var lastContactUploaderSlideClose = function (setNext) {
		if (setNext.hasClass("c-option-done")) {
			$('.contactupload-overlay .navigation-overlay').removeClass("active");
			setTimeout(function () {
				setNext.fadeOut(800, function () {
					removeContactUploadOverlay();
				});
			}, 1000);
		} else {
			checkContactUploaderArrowStatus();
		}
	};

	setInterval(function () {
		if ($(".contactupload-overlay .existing-names a.c-found").length) {
			$(".contactupload-overlay .existing-names a.c-found").removeClass("hvr-buzz-out-active").addClass("hvr-buzz-out-hover");
			setTimeout(function () {
				$(".contactupload-overlay .existing-names a.c-found").removeClass("hvr-buzz-out-hover");
			}, 500);
		}
	}, 3000);

	$(".ContactUpload-Box-overlay").unbind("click").bind("click", function () {
		$(this).removeClass("active");
		$(this).parents(".option-container").find('.c-add-input').trigger("focus").trigger("keyup");
	});

	function addContactUploadOverlay() {
		$('body').addClass('activate-full-screen');
		$('.contactupload-overlay').addClass('activate-overlay-screen');
		innerOffsetBox.css({position: 'absolute', top: $(window).scrollTop() + 50});
		$(".contactupload-overlay").removeClass("active");
		$(".contactupload-overlay .options").attr("style", "");
		$(".c-TipHelp-Container").fadeOut().removeClass("active");
	}

	function removeContactUploadOverlay() {
		$('body').removeClass('activate-full-screen');
		$('.contactupload-overlay').removeClass('activate-overlay-screen');
		$(".contactupload-overlay .csvcontactupload").removeClass("active");
		$(".contactupload-overlay").find(".c-input-error").removeClass("c-input-error");
		$(".contactupload-overlay").find(".active").removeClass("active");
		$(".contactupload-overlay").find(".c-found").removeClass("c-found");
		$(".contactupload-overlay .navigation-overlay a").not(".u-gotOSummary").show();
		$('.contactupload-overlay .csvcontactupload').hide();
		$(".contactupload-overlay .csvcontactupload input").val("");
		$(".contactupload-overlay .csvcontactupload .option-container-firstbox").show();
		$(".contactupload-overlay .csvcontactupload .option-container-secondbox").hide();
		$(".contactupload-overlay .navigation-overlay .u-setDone").removeClass("u-setDone");
		$(".contactupload-overlay .navigation-overlay .active").removeClass("active");
		$(".contactupload-overlay .hovered").removeClass("hovered");
	}



	var $inputImage = $('.csvcontactupload #inputcsv'),
			URL = window.URL || window.webkitURL;
	if (URL) {
		$inputImage.on('change', function () {
			var files = this.files;
			if (files && files.length) {
				var file = files[0];

				var data = new FormData();
				data.append("upload-contacts", 1);
				data.append("csv", file);
				var type = file.type;
				if (type !== "text/csv" && type !== "text/x-csv" && type !== "text/comma-separated-values"  && type !== "application/vnd.ms-excel") {
					alert("Please upload valid csv file!");
					return false;
				}
				xhr = new XMLHttpRequest();
				xhr.upload.addEventListener('load', function (e) {
					$(".csvcontactupload .c-option-csvUpload .addperson-text").text("UPLOAD TEMPLATE");
				}, false);
				xhr.upload.addEventListener('progress', function (e) {
					$(".csvcontactupload .c-option-csvUpload .addperson-text").text("" + parseInt((100 * e.loaded / e.total)) + "% Loading...");
				}, false);
				xhr.onreadystatechange = function (e) {

					if (xhr.readyState == 4 && xhr.status == 200) {

						var response = $.parseJSON(xhr.responseText);
						if (response.status == "success") {
							$(".csvcontactupload .c-option-csvUpload .addperson-text").text("TEMPLATE UPLOADED");
							$(".csvcontactupload .set-three .existing-names").html(response.html);
							$(".contactupload-overlay .navigation-overlay .u-navigationCircle.active").addClass("u-setDone");
							$(".contactupload-overlay .navigation-overlay .u-navigationCircle.active.u-setDone").next().trigger("click");
							csvupload_existing_names_actions();

							// append same contacts to assign widget as well
							$(".assignwidget-overlay .c-AssignContact-Container .c-AssignContact-Contacts .c-AssignContact-Box-Contacts-List").prepend(response.assing_html);
							dragAssignHandle();
						} else {
							alert(response.message);
							$(".csvcontactupload .c-option-csvUpload .addperson-text").text("UPLOAD TEMPLATE");
						}
					} else {
					}
				};
				xhr.open('POST', window.location.href, true);
				xhr.send(data);

			}
			$(this).attr("value", "");
		});
	} else {

	}
});