//(postMessage)
;(function($){var g,d,j=1,a,b=this,f=!1,h="postMessage",e="addEventListener",c,i=b[h]&&!$.browser.opera;$[h]=function(k,l,m){if(!l){return}k=typeof k==="string"?k:$.param(k);m=m||parent;if(i){m[h](k,l.replace(/([^:]+:\/\/[^\/]+).*/,"$1"))}else{if(l){m.location=l.replace(/#.*$/,"")+"#"+(+new Date)+(j++)+"&"+k}}};$.receiveMessage=c=function(l,m,k){if(i){if(l){a&&c();a=function(n){if((typeof m==="string"&&n.origin!==m)||($.isFunction(m)&&m(n.origin)===f)){return f}l(n)}}if(b[e]){b[l?e:"removeEventListener"]("message",a,f)}else{b[l?"attachEvent":"detachEvent"]("onmessage",a)}}else{g&&clearInterval(g);g=null;if(l){k=typeof m==="number"?m:typeof k==="number"?k:100;g=setInterval(function(){var o=document.location.hash,n=/^#?\d+&/;if(o!==d&&n.test(o)){d=o;l({data:o.replace(n,"")})}},k)}}}})(jQuery);

;(function($){

	if (!window.Intelli) window.Intelli = {};

    Intelli.openWindow = function (url, w, h)
    {
        var x = screen.width/2 - w/2;
        var y = screen.height/2 - h/2;
        return window.open(url, '','height=' + h +', width=' + w + ', left=' + x + ', top=' + y);
    }
	
	jQuery.fn.serializeObject = function()
	{
	    var o = {};
	    var a = this.serializeArray();
	    $.each(a, function() {
	        if (o[this.name] !== undefined) {
	            if (!o[this.name].push) {
	                o[this.name] = [o[this.name]];
	            }
	            o[this.name].push(this.value || '');
	        } else {
	            o[this.name] = this.value || '';
	        }
	    });
	    return o;
	};
	
	jQuery.fn.charsLeft = function(customOptions){
		var selector = customOptions.selector;
		
		var options = customOptions; 
		return this.each(function(i){
			var $this = $(this);
			
			var charsLeft = function(){
				var messageLength = $this.attr("value").length;
				
				if (messageLength > options.maxChars) {
					var message = $this.attr("value");
					message = message.substr(0, options.maxChars);
					$this.attr("value", message);
					messageLength = options.maxChars;
				}
				
				var messageCharsLeft = options.maxChars - messageLength;
				$(selector).text(messageCharsLeft);
				
				if (messageCharsLeft) {
					$(selector).text(messageCharsLeft);
				} else {
					$(selector).text(messageCharsLeft);
				}
				
			}
			charsLeft();
			$this.bind("keyup.charsLeft", charsLeft );
		});
	}
	
    Intelli.parseQueryParams = function(queryString) {
        var params = {},
            e,
            a = /\+/g,  // Regex for replacing addition symbol with a space
            r = /([^&=]+)=?([^&]*)/g,
            d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
            q = queryString;

        while (e = r.exec(q))
            params[d(e[1])] = d(e[2]);

        return params;
    }
	
	Intelli.getQueryParameterByName = function(key, queryString) {
	    if (!this.queryStringParams) {
	        this.queryStringParams = Intelli.parseQueryParams(queryString);
	    }
	    return this.queryStringParams[key];
	}	
	
	Intelli.extend = function(target, source, overwrite) {
		  for (var key in source) {
		    if (overwrite || typeof target[key] === 'undefined') {
		      target[key] = source[key];
		    }
		  }
		  return target;
		};
		
	Intelli.User = {
		uri    : null,
		key    : null,
		config : null,
		skin   : null,

        isAuthenticated : null,
        sessionId       : null,

		init : function(config){

			this.uri    = config.uri;
			this.key    = config.key;
			this.config = config;
			
			if (config.skin !== undefined) {
				this.skin = config.skin;
			}

            /* линк авторизации */
            $('.auth-link').die().live('click', function() {
                if ($(this).hasClass('popup')) {
                    Intelli.openWindow($(this).attr('href'), 500, 300);
                    return false;
                }
                return true;
            });

            Intelli.User.Forms.SocialAuthEvents();

            $(document).trigger('auth-init');

		},
		//получаем значение конфига
		getConfig : function(key){
			return this.config[key];
		},

        setIsAuthenticated : function(val){
            this.isAuthenticated = val;
        },

        getIsAuthenticated : function(){
            return this.isAuthenticated;
        },

        setSessionId: function(val) {
            this.sessionId = val;
        },

        getSessionId: function() {
            return this.sessionId;
        },

		getUri : function(path){
			if (path) {
				return Intelli.User.uri + path;
			} else {
				return Intelli.User.uri;
			}
		},
		
		prepareData : function(data)
		{
			data.key  = this.key;
			data.skin = this.skin;
			data.mode = 'json';
			return data;
		},

        getKey : function(){
            return this.key;
        },
		
		getGreetingWidgetUri : function(){
			return 	this.getUri('/widget/greeting');
		},
		getRegistrationWidgetUri : function(){
			return 	this.getUri('/widget/register');
		},		
		getRecoveryPasswordWidgetUri : function(){
			return 	this.getUri('/widget/recovery-password');
		},
		getChangePasswordWidgetUri : function(){
			return 	this.getUri('/widget/change-password');
		},
		getProfilePublicWidgetUri : function(){
			return 	this.getUri('/widget/profile-public');
		},
		getProfileWidgetUri : function(){
			return 	this.getUri('/widget/profile');
		},
		getProfileUploadPhotoAction : function(){
			return 	this.getUri('/widget/upload-photo');
		},
		getProfileUpdateAction : function(){
			return 	this.getUri('/widget/update-user');
		},		
		getAuthWidgetUri : function(){
			return this.getUri('/widget/login');	
		},
		getCommentsWidgetUri : function(){
			return this.getUri('/widget/comments');	
		},
		getConfirmationWidgetUri : function(){
			return this.getUri('/widget/confirm');	
		},
        getUnsubscribeWidgetUri : function(){
            return this.getUri('/widget/unsubscribe');
        },

		getVocabularyItemsUri : function(){
			return this.getUri('/widget/vocabulary-items');
		}
	}
	
	/* отправка аджакс запроса через JSONP */
	Intelli.User.ajax = function(options){
	
		options.url = Intelli.User.addCallbackToUri(options.url);
		
		options.data = Intelli.User.prepareData(options.data);

		$.ajax(options);
	}


    Intelli.User.parseUrl = function(url, result) {
        var parts = url.split('/');
        var action_url = [];

        if (parts[0] == 'http:') {
            action_url.push(parts.shift());
            action_url.push(parts.shift());
            action_url.push(parts.shift());
        }

        var controller = parts.shift();
        var action = parts.shift();

        action_url.push(controller);
        action_url.push(action);

        var i = 0;
        while (i < parts.length){
            result[parts[i]] = decodeURIComponent(parts[i+1]);
            i+=2;
        }

        result.action_url = action_url.join('/');

        return result
    }
	
	Intelli.User.addCallbackToUri = function(uri)
	{
		return uri += '?callback=?';
	}
	
	/* Загрузка виджета */
	Intelli.User.Widget = {
		load: function(containerId, uri, data, successCallback) {
			
			if (typeof(data) !== 'object') {
				var data = {};
			}
			
			data = Intelli.User.prepareData(data);
			
			uri = Intelli.User.addCallbackToUri(uri);
			
			$.getJSON(uri, data, function(result){
				if (!Intelli.User.CheckRedirect(result)) {
					$('#'+containerId).html(result.data);
					if (successCallback) {
						successCallback();
					}
				}
			});
		}
	}
	
	/* отображение публичного профиля */
	Intelli.User.Profile = function(containerId){
		this.containerId = containerId;
		var url = window.location.href;
		
		Intelli.User.Widget.load(containerId, Intelli.User.getProfilePublicWidgetUri(), {location: url});

        Intelli.User.Forms.CommentsEvents(containerId);

	}
	
	Intelli.User.Forms = {}

	Intelli.User.Forms.setSelectOptions = function(selector, data, clearEmpty, addEmpty){
		
		if (clearEmpty !== undefined) {
			$(selector).find('option[value!=""]').remove();
		} else {
			$(selector).find('option').remove();
		}
		
		if (addEmpty) {
		    $(selector).append(
		    		$('<option></option>').val('').html(addEmpty)
		    );
		}
		
		$.each(data, function(val, text) {
		    $(selector).append(
		            $('<option></option>').val(val).html(text)
		    );
		});
		
		$(selector).trigger('onchange');
	}
	
	/* виджет формы регистрации */
	Intelli.User.Forms.Register = function(containerId){
		this.containerId = containerId;
		Intelli.User.Widget.load(containerId, Intelli.User.getRegistrationWidgetUri());
		Intelli.User.Forms.submit('#user-register-form', '#' + containerId);	
	}
	
	/* виджет формы восстановления пароля */
	Intelli.User.Forms.RecoveryPassword = function(containerId){
		this.containerId = containerId;
		
		var code = window.location.search.substring(1);
		var data = {};
		
		if (code) {
			data.code = code;
		}
		
		if (code) {
			var uri = Intelli.User.getChangePasswordWidgetUri()
		} else {
			var uri = Intelli.User.getRecoveryPasswordWidgetUri()
		}
		
		Intelli.User.Widget.load(containerId, uri, data);
		Intelli.User.Forms.submit('#user-recovery-password-form', '#' + containerId, data);	
		Intelli.User.Forms.submit('#user-change-password-form', '#' + containerId, data);
	}

    Intelli.User.Forms.SocialAuthEvents = function() {
        $('.social .auth').die().live('click', function() {

            var id = $(this).attr('href');
            id = id.substr(1);

            var key = Intelli.User.getKey();

            var url = Intelli.User.getUri('/social/auth/key/' + key + '/id/' + id);

            if ($(this).hasClass('popup')) {
                url += '?returnUrl=' + encodeURIComponent(document.location.href);
            }

            var map = {
                'Odnoklassniki': {w:750, h:400},
                'default': {w:500, h:300}
            }

            if (map[id]) {
                var current = map[id];
            } else {
                var current = map['default'];
            }

            if ($(this).hasClass('popup')) {
                Intelli.openWindow(url, current.w, current.h);
            } else {
                window.resizeTo(current.w, current.h);
                window.location.href = url;
            }

            return false;
        });
    }

    //TODO: move it to private
    Intelli.User.Forms.CommentsEvents = function(containerId) {

        //TODO: добавить loading индикатор
        $('#comments-paging a').die().live('click', function(){
            var formdata = {mode: 'json'};

            formdata.location = window.location.href;

            var resultData = null;
            var animationFinished = false;
            var destination = $(".b-comments-total").offset().top - 20;

            $("html, body").animate({ scrollTop: destination}, 500, null, function(){
                animationFinished = true;
                if (resultData) {
                    $('#' + containerId).html(resultData);
                }
            } );



            Intelli.User.parseUrl($(this).attr('href'), formdata);

            var url = formdata['action_url'];
            delete formdata.action_url;

            Intelli.User.ajax({
                url      : url,
                data     : formdata,
                dataType : 'json',
                type     : 'POST',
                success  : function(result){
                    if (result.success) {
                        resultData = result.data;
                        if (animationFinished) {
                            $('#' + containerId).html(result.data);
                        }
                    }
                }
            });

            return false;
        });

        var commentAnswerLevelCls = '';

        // ответить
        $('#user-comments .answer a').die().live('click', function(){

            var id = $(this).attr('attr:id');
            $('#user-add-comment-answer').show();
            $('#user-add-comment-answer').insertAfter( $(this).closest('.comment') );
            $('#user-add-comment-answer .messages').hide();

            // устанавливаем Parent_Id
            $('[name="comment[parent_id]"]', $('#user-add-comment-answer-form')).val(id);

            var level = $(this).closest('.comment').attr('attr:level');
            var cls = 'level-' + level;

            var formBody = $('#user-add-comment-answer-form-body', $('#user-add-comment-answer-form'));

            if (commentAnswerLevelCls) {
                $(formBody).removeClass(commentAnswerLevelCls);
            }

            commentAnswerLevelCls = cls;
            $(formBody).addClass(cls);

            return true;
        });

        var editingComment = null;

        $('#user-comments .edit').die().live('click', function(){
            //$(this).closest('.comment').addClass('comment-answer');

            if (editingComment){
                editingComment.show();
            }

            editingComment = $(this).closest('.comment');
            var text = $('.comment-text', editingComment).text();
            editingComment.hide();

            var id = $(this).attr('attr:id');
            $('#user-edit-comment').show();
            $('#user-edit-comment').insertAfter( $(this).closest('.comment') );
            $('textarea', $('#user-edit-comment')).val(text);
            $('#user-edit-comment .messages').hide();

            // устанавливаем Parent_Id
            $('[name="comment[edit_id]"]', $('#user-edit-comment-form')).val(id);

            var level = $(this).closest('.comment').attr('attr:level');
            var cls = 'level-' + level;

            var formBody = $('#user-edit-comment-form-body', $('#user-edit-comment-form'));

            if (commentAnswerLevelCls) {
                $(formBody).removeClass(commentAnswerLevelCls);
            }

            commentAnswerLevelCls = cls;
            $(formBody).addClass(cls);

            return true;
        });

        $('#user-comments .like-dislike a').die().live('click', function(){

            var self = this;

            Intelli.User.ajax({
                url      : $(this).attr('href'),
                data     : {},
                dataType : 'json',
                type     : 'POST',
                success  : function(result){
                    if (result.success) {
                        $(self).closest('.like-dislike').replaceWith(result.data);
                    }
                }
            });
            return false;
        });

        $('#user-comments .abuse').die().live('click', function(){

            var self = this;

            Intelli.User.ajax({
                url      : $(this).attr('href'),
                data     : {},
                dataType : 'json',
                type     : 'POST',
                success  : function(result){
                    if (result.success) {
                        $(self).closest('.abuse').replaceWith(result.data);
                    }
                }
            });
            return false;
        });

        $('#user-comments .admin').die().live('click', function(){
            var self = this;
            Intelli.User.ajax({
                url      : $(this).attr('href'),
                data     : {},
                dataType : 'json',
                type     : 'POST',
                success  : function(result){
                    if (result.success) {
                        $(self).closest('.comment').replaceWith(result.data);
                    }
                }
            });
            return false;
        });
    }
	
	/* виджет комментариев */
	Intelli.User.Forms.Comments = function(containerId, options){
		
		this.containerId = containerId;
		var data = options;

        //data.location = window.location.href;
        data.page = 1;

		Intelli.User.Widget.load( containerId, Intelli.User.getCommentsWidgetUri(), data, 
			function(){
				$('#user-add-comment textarea[name="comment[comment]"]').charsLeft({
					maxChars: 300,
					selector: '#user-add-comment .comment-length-left'
				});
				
				$('#user-add-comment-answer textarea[name="comment[comment]"]').charsLeft({
					maxChars: 300,
					selector: '#user-add-comment-answer .comment-length-left'
				});

                $('#user-edit-comment textarea[name="comment[comment]"]').charsLeft({
                    maxChars: 300,
                    selector: '#user-edit-comment .comment-length-left'
                });

                $('#' + containerId + ' .logout').attr('href', $('#' + containerId + ' .logout').attr('href') + '?returnUrl=' + encodeURIComponent(document.location.href));
            }
		);

        Intelli.User.Forms.CommentsEvents(containerId);
		
		var validate = function(form){
			var agreeBox = $('input[name="comment[agree]"]', form);
			if (agreeBox) {
				var checked = agreeBox.attr('checked');
				if (checked != 'checked') {
					alert('Чтобы добавить комментарий необходимо принять условия комментирования');
					return false;
				}
			}
			return true;
		}
		
		Intelli.User.Forms.submit('#user-add-comment', '#' + containerId, options, validate);
        Intelli.User.Forms.submit('#user-edit-comment-form', '#' + containerId, options, validate, null, {noScroll : true});
		Intelli.User.Forms.submit('#user-add-comment-answer-form', '#' + containerId, options, validate);
	}
	
	/* виджет формы профайла */
	Intelli.User.Forms.Profile = function(containerId){
		this.containerId = containerId;
		
		var afterLoad = function() {
			// атачим кнопку выбора
			$('#user-profile-form .change-photo').after('<input class="change-photo-file" name="photo" type="file" style="display:none">');
			// срабатывает на выбор файла
			$("#user-profile-form .change-photo-file").change(function(){
				var form = $("#user-profile-form");
				$(form).attr('target', 'upload_frame');
				var action = Intelli.User.getProfileUploadPhotoAction();
				$(form).attr('action', action);
				$('#user-profile-form .change-photo').addClass('loading');
				//TODO: FIX FOR IE
				$(form).die().submit();
			});			
		};
		
		Intelli.User.Widget.load(containerId, Intelli.User.getProfileWidgetUri(), {}, afterLoad);
		
		$("#user-profile-form .change-photo").die().live('click', function(){
			$('.change-photo-file').trigger('click');
			return false;
		});
		
		$("#user-profile-form .submit-form").die().live('click', function(){
			var form = $("#user-profile-form");
			Intelli.User.Forms.submit('#user-profile-form', '#' + containerId, {}, null, afterLoad);
			var action = Intelli.User.getProfileUpdateAction();
			$(form).attr('action', action);
		});
	}
	
	/* виджет формы аутентификации */
	Intelli.User.Forms.Auth = function(containerId, options){
        var referrer = document.referrer;

        if ('referrer' in options) {
            referrer = options.referrer;
            delete options.referrer;
        }

		this.containerId = containerId;

		Intelli.User.Widget.load(containerId, Intelli.User.getAuthWidgetUri(), { referrer: referrer, options: options });
		Intelli.User.Forms.submit('#user-auth-form', '#' + containerId, null);
	}
	
	/* виджет формы подтверждения кода */
	Intelli.User.Forms.Confirmation = function(containerId){
		this.containerId = containerId;
		var code = window.location.search.substring(1);
		
		Intelli.User.Forms.submit('#user-confirm-form', '#' + containerId);
		
		if (code)
		{
			$('#' + containerId).html('Активация аккаунта...');
			
			var formdata = {mode: 'json'};
				formdata.code = code;
			
			Intelli.User.ajax({
				url      : Intelli.User.getConfirmationWidgetUri(),
				data     : formdata,
				dataType : 'json',
				type     : 'POST',
				success  : function(result){
					if (result.success) {
						$('#' + containerId).html(result.data);
					}
				}
			});
		} else {
			Intelli.User.Widget.load(containerId, Intelli.User.getConfirmationWidgetUri());
		}
	}

    /* виджет формы подтверждения кода */
    Intelli.User.Forms.Unsubscribe = function(containerId){
        this.containerId = containerId;
        var url = window.location.href;

        $('#' + containerId).html('Отключение отслеживания комментариев...');

        var formdata = {mode: 'json'};
        formdata.url = url;

        Intelli.User.ajax({
            url      : Intelli.User.getUnsubscribeWidgetUri(),
            data     : formdata,
            dataType : 'json',
            type     : 'POST',
            success  : function(result){
                if (result.success) {
                    $('#' + containerId).html(result.data);
                }
            }
        });
    }
	
	/* отправка форм */
	Intelli.User.Forms.submit = function(containerId, selector, data, validateCallback, successCallback, options){

        var scroll = !options || !options.noScroll;

		$(containerId).die().live('submit', function(){
			var form = this;

			var validationResult = true;
			
			if (validateCallback) {
				validationResult = validateCallback(form);
			}
			
			if (!validationResult) {
				return false;
			}
			
			//добавить индикатор
			$('.g-button[type=submit]', form).addClass('loading');
			
			var formdata = $(form).serializeObject();
				formdata.mode = 'json';
				
				if (data) {
					for (key in data){
						formdata[key] = data[key];
					}
				}
			
				Intelli.User.ajax({
					url      : $(form).attr('action'),
					data     : formdata,
					dataType : 'json',
					type     : 'POST',
					success  : function(result){
						if (result.success) {
							if (!Intelli.User.CheckRedirect(result)) {
								$(selector).html(result.data);
								
								//если есть сообщения в форме, то делаем прокрутку
								if ($('.form-messages').length && scroll){
									var destination = $(".form-messages").offset().top - 20;
									$("html, body").animate({ scrollTop: destination}, 500, null, function(){});
								}
								
								if (successCallback) {
									successCallback();
								}
							}
						}
					}
				});
			return false;
		});
	}
	
	/* вызов редиректа */
	Intelli.User.Redirect = function(url){
		window.location = url;
	}
	
	/* проверка на редирект в AJAX ответе */
	Intelli.User.CheckRedirect = function(result){
		if (typeof(result.data) === 'object' && result.data.redirect) {
			Intelli.User.Redirect(result.data.redirect);
			return true;
		}
		return false;
	}
	
	/* вызов виджета приветсвия */
	Intelli.User.Greeting = function(selector){
		var data = {}; 
		data = Intelli.User.prepareData(data);
		
		var uri = Intelli.User.getGreetingWidgetUri();
		uri = Intelli.User.addCallbackToUri(uri);
		
		$.getJSON(uri, data, function(result){
            if (result.success) {
                $(selector).html(result.data);

                var referrer  = document.location.href,
                    loginRef  = $(selector).find('#user-login-link'),
                    logoutRef = $(selector).find('#user-logout-link');

                loginRef.attr ('href', loginRef.attr('href')  + "?returnUrl=" + encodeURIComponent(referrer));
                logoutRef.attr('href', logoutRef.attr('href') + "?returnUrl=" + encodeURIComponent(referrer));

                Intelli.User.setSessionId(result.session_id);
                Intelli.User.setIsAuthenticated(result.is_authenticated);
            }
		});		
	}
	
	/* вызывается при смене фото */
	Intelli.User.ProfilePhotoChanged = function(params){
		if (params.error) {
			alert(params.error);
		} else {
			var src   = params.src + '?' + Math.random();
			var value = params.value;
			
			$('#user-profile-form .profile-photo').attr('src', src );
			$('#user-profile-form input[name="user[photo]"]').val(value);
			
			$('#user-profile-form .no-photo').hide();
			$('#user-profile-form .photo').show();
		}
		$('#user-profile-form .change-photo').removeClass('loading');
	}
	
	Intelli.User.Integration = {};
/**************8
	Intelli.User.Integration.Facebook = {};
	Intelli.User.Integration.Facebook.Init = function()
	{
		var appId = Intelli.User.getConfig('facebook_app_id');
		
		if (!appId) {
			alert('Facebook App Id not defined (Key: facebook_app_id');
		}
		
	    window.fbAsyncInit = function() {
	        FB.init({
	          appId      : appId,
	          status     : true, 
	          cookie     : true,
	          xfbml      : true,
	          oauth      : true,
	        });
	      };
          
	      (function(d){
	         var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
	         js = d.createElement('script'); js.id = id; js.async = true;
	         js.src = "//connect.facebook.net/en_US/all.js";
	         d.getElementsByTagName('head')[0].appendChild(js);
	       }(document));		
	}
	
	Intelli.User.Integration.Facebook.Login = function()
	{
			FB.login(function(response) {
			   if (response.authResponse) {
				   Intelli.User.Redirect( Intelli.User.getSocialLoginUri('facebook') );
			   } else {
				   //TODO
				   alert('User cancelled login or did not fully authorize.');
			   }
			});
	}	
***/
	Intelli.User.Vocabulary = {};
	Intelli.User.Vocabulary.load = function(element, selector){
		
		var uri = Intelli.User.getVocabularyItemsUri();
		
		var formdata = {mode: 'json', id: element.value};
		Intelli.User.ajax({
			url      : uri,
			data     : formdata,
			dataType : 'json',
			type     : 'POST',
			success  : function(result){
				if (result.success) {
					Intelli.User.Forms.setSelectOptions(selector, result.data, '-- Выберите из списка --');
				}
			}
		});
	}
	
	$(document).ready( function(){
		$.receiveMessage(
			function(e){
				var params = Intelli.parseQueryParams(e.data);
				if (params.action == 'ProfilePhotoChanged') {
					Intelli.User.ProfilePhotoChanged(params);
				}
			},
			Intelli.User.getUri()
		);
	});
	
})(jQuery);Intelli.User.init({"uri":"http:\/\/a.vesti-ukr.com","key":"vesti"});