

// jQuery Mask Plugin v0.9.0
// github.com/igorescobar/jQuery-Mask-Plugin
(function(k){var p=function(n,f,h){var g=this,a=k(n),m={byPassKeys:[8,9,37,38,39,40],maskChars:{":":":","-":"-",".":"\\.","(":"\\(",")":"\\)","/":"/",",":",",_:"_"," ":"\\s","+":"\\+"},translationNumbers:{0:"\\d",1:"\\d",2:"\\d",3:"\\d",4:"\\d",5:"\\d",6:"\\d",7:"\\d",8:"\\d",9:"\\d"},translation:{A:"[a-zA-Z0-9]",S:"[a-zA-Z]"}};g.init=function(){g.settings={};h=h||{};m.translation=k.extend({},m.translation,m.translationNumbers);g.settings=k.extend(!0,{},m,h);g.settings.specialChars=k.extend({},g.settings.maskChars,
g.settings.translation);a.each(function(){f=d.resolveMask();f=d.fixRangeMask(f);a.attr("maxlength",f.length);a.attr("autocomplete","off");d.destroyEvents();d.setOnKeyUp();d.setOnPaste()})};var d={onPasteMethod:function(){setTimeout(function(){a.trigger("keyup")},100)},setOnPaste:function(){d.hasOnSupport()?a.on("paste",d.onPasteMethod):a.get(0).addEventListener("paste",d.onPasteMethod,!1)},setOnKeyUp:function(){a.keyup(d.maskBehaviour).trigger("keyup")},hasOnSupport:function(){return k.isFunction(k().on)},
destroyEvents:function(){a.unbind("keyup").unbind("onpaste")},resolveMask:function(){return"function"==typeof f?f(d.getVal(),void 0,h):f},setVal:function(b){"input"===a.get(0).tagName.toLowerCase()?a.val(b):a.html(b);return a},getVal:function(){return"input"===a.get(0).tagName.toLowerCase()?a.val():a.text()},specialChar:function(b,c){return g.settings.specialChars[b.charAt(c)]},maskChar:function(b,c){return g.settings.maskChars[b.charAt(c)]},maskBehaviour:function(b){b=b||window.event;if(-1<k.inArray(b.keyCode||
b.which,g.settings.byPassKeys))return!0;var c=d.applyMask(f);c!==d.getVal()&&d.setVal(c).trigger("change");return d.seekCallbacks(b,c)},applyMask:function(b){if(""!==d.getVal()){var c=function(b,c){for(;c<b.length;){if(void 0!==b[c])return!0;c++}return!1},l=function(c){c="string"===typeof c?c:c.join("");c=c.match(RegExp(d.maskToRegex(b)))||[];c.shift();return c},e=d.getVal();b=d.getMask(e,b);for(var e=h.reverse?d.removeMaskChars(e):e,a=l(e);a.join("").length<d.removeMaskChars(e).length;)a=a.join("").split(""),
e=d.removeMaskChars(a.join("")+e.substring(a.length+1)),b=d.getMask(e,b),a=l(e);for(e=0;e<a.length;e++)if(l=d.specialChar(b,e),d.maskChar(b,e)&&c(a,e))a[e]=b.charAt(e);else if(l)if(void 0!==a[e]){if(null===a[e].match(RegExp(l)))break}else if(null==="".match(RegExp(l))){a=a.slice(0,e);break}return a.join("")}},getMask:function(b){if(h.reverse){b=d.removeMaskChars(b);for(var c=0,a=0,e=0,c=f.length,a=c=1<=c?c:c-1;e<b.length;){for(;d.maskChar(f,a-1);)a--;a--;e++}a=1<=f.length?a:a-1;b=f.substring(c,a)}else b=
f;return b},maskToRegex:function(b){for(var c,a=0,e="";a<b.length;a++)(c=d.specialChar(b,a))&&(e+="("+c+")?");return e},fixRangeMask:function(a){return a.replace(/([A-Z0-9])\{(\d+)?,([(\d+)])\}/g,function(){var a=arguments,b=[],e=g.settings.translationNumbers[a[1]]?String.fromCharCode(parseInt("6"+a[1],16)):a[1].toLowerCase();b[0]=a[1];b[1]=Array(a[2]-1+1).join(a[1]);b[2]=Array(a[3]-a[2]+1).join(e).toLowerCase();g.settings.specialChars[e]=d.specialChar(a[1])+"?";return b.join("")})},removeMaskChars:function(a){k.each(g.settings.maskChars,
function(c,d){a=a.replace(RegExp("("+g.settings.maskChars[c]+")?","g"),"")});return a},seekCallbacks:function(b,c){if(h.onKeyPress&&void 0===b.isTrigger&&"function"==typeof h.onKeyPress)h.onKeyPress(c,b,a,h);if(h.onComplete&&void 0===b.isTrigger&&c.length===f.length&&"function"==typeof h.onComplete)h.onComplete(c,b,a,h)}};"boolean"===typeof QUNIT&&(g.__p=d);g.remove=function(){d.destroyEvents();d.setVal(d.removeMaskChars(d.getVal()));a.removeAttr("maxlength")};g.init()};k.fn.mask=function(n,f){return this.each(function(){k(this).data("mask",
new p(this,n,f))})}})(window.jQuery||window.Zepto);

// Vote block scripts
(function($) {

	$(document).ready(function() {

		var form = $('.vote-block_cnt'),
			radio = $('.vote-block_radio-inp', form),
			lbl = $('.vote-block_radio-lbl', form),
			otherRadio = $('.vote-block_answer__other .vote-block_radio-inp'),
			otherTxt = $('.vote-block_answer__other .vote-block_text-input__other');

			if (otherRadio.prop('checked')) {
				otherTxt.prop("disabled", false);
			}else{
				otherTxt.prop("disabled", true);				
			}


		$('.vote-block_radio-inp').on('change', function() {
			$('.vote-block_radio-lbl').removeClass('vote-block_radio-lbl__checked');
			if (otherTxt.hasClass('vote-block_text-input__invalid')) {
				otherTxt.removeClass('vote-block_text-input__invalid');
				otherTxt.val('');
			};
			lbl.removeClass('vote-block_radio-lbl__checked');
			if ($(this).is(':checked')) {
				$(this).siblings('.vote-block_radio-lbl').addClass('vote-block_radio-lbl__checked');
			} else {
				$(this).siblings('.vote-block_radio-lbl').removeClass('vote-block_radio-lbl__checked');
			}

			if (otherRadio.prop('checked')) {
				otherTxt.prop("disabled", false);
			}else{
				otherTxt.prop("disabled", true);				
			}

		});

		

		$(document).on('click', '.js-sendCodeAgain', function() {
			$('body').append('<form id="myspecialform" method="POST"> <input type="hidden" name="link_action" value="resend" /> </form>');	    
		    $('#myspecialform').submit();
			return false;
		});

		$(document).on('click', '.js-cancelChoice', function() {
			$('body').append('<form id="myspecialform" method="POST"> <input type="hidden" name="link_action" value="clear" /> </form>');	    
		    $('#myspecialform').submit();
			return false;
		});

		// Mask on phone
		$('.js-sendPhoneBlock .vote-block_text-input')
			.mask('+7 (000) 000-00-00', {
				translation: {'+7': "+7"}
			});

		// Submit form event
		form.on('submit', function() {
			if (checkForm()) {
				return false;
			}
		});

		// true - don't send
		// false - send
		function checkForm() {

			// Any radio is checked?
			if (radio.filter(':checked').length === 0) {
				return true;
			}

			// Other variant check
			if (otherRadio.filter(':checked').length > 0 && otherTxt.val() === '') {
				otherTxt
					.addClass('vote-block_text-input__invalid')
					.val('Введите свой вариант');

				$('.vote-block_text-input__invalid').off('focus.form');
				$('.vote-block_text-input__invalid').on('focus.form', function() {
					$(this)
						.removeClass('vote-block_text-input__invalid')
						.val('')
						.off('focus.form');
				});

				return true;
			}

			// Phone check
			var phoneInp = $('.js-sendPhoneBlock .vote-block_text-input');
			if ((phoneInp.length > 0 && phoneInp.val().length < 18) || phoneInp.val()=='Введите номер телефона') {
				phoneInp
					.addClass('vote-block_text-input__invalid')
					.val('Введите номер телефона');

				phoneInp.off('focus.form');
				phoneInp.on('focus.form', function() {
					$(this)
						.removeClass('vote-block_text-input__invalid')
						.val('+7 ')
						.off('focus.form');
				});

				return true;
			}

			// Code check
			var codeInp = $('.js-confirmBlock .vote-block_text-input');
			if (codeInp.length > 0 && codeInp.val().length === 0) {
				codeInp
					.addClass('vote-block_text-input__invalid')
					.val('Введите код подтверждения');

				codeInp.off('focus.form');
				codeInp.on('focus.form', function() {
					$(this)
						.removeClass('vote-block_text-input__invalid')
						.val('')
						.off('focus.form');
				});

				return true;
			}

			if(otherTxt.hasClass('vote-block_text-input__invalid')){
					if (otherRadio.prop('checked')) {
						return true;
					}
				}

			if(codeInp.hasClass('vote-block_text-input__invalid')){
				return true;
				}


			return false;
		};




		function createCookie(name,value,days) {
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else var expires = "";
			document.cookie = name+"="+value+expires+"; path=/";
		}

		function readCookie(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		}

		function eraseCookie(name) {
			createCookie(name,"",-1);
		}



		function updateQueryString(key, value, url) {
		    if (!url) url = window.location.href;
		    var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi");

		    if (re.test(url)) {
		        if (typeof value !== 'undefined' && value !== null)
		            return url.replace(re, '$1' + key + "=" + value + '$2$3');
		        else {
		            return url.replace(re, '$1$3').replace(/(&|\?)$/, '');
		        }
		    }
		    else {
		        if (typeof value !== 'undefined' && value !== null) {
		            var separator = url.indexOf('?') !== -1 ? '&' : '?',
		                hash = url.split('#');
		            url = hash[0] + separator + key + '=' + value;
		            if (hash[1]) url += '#' + hash[1];
		            return url;
		        }
		        else
		            return url;
		    }
		}


	});

})(jQuery);