Signin  Pricing  Examples  Support

Libraries > app.js

app.js - Search Live Website Code
It's like doing CTRL+F on millions of websites' source code



NerdyData is a search engine for source code. Search the source code of 200 million websites.


JAVASCRIPT FILE http://gambit.gg/public/js/app.js

Function Explorer









Libraries on gambit.gg


core.js

dlg.js

gs.js

en.js

scroll.js

tabs.js

jquery.js

modernizr.custom.js

news-js.js

router.js

setup.js

timezone.js

viewer.js



Explore More


mobileSwitch.js

jquery.customDropDown.js

jquery.customScripts.js

html5shiv.min.js

app.js
				
/**
 * Application related functionality.
 */
var App = {
	
	xhr: null,
	
	modules: 0,
	
	modulesLoaded: 0,
	
	values: {},
	
	win: null,
	doc: null,
	
	initialize: function(win, doc)
	{
		var mt;
		App.win = $(win);
		App.doc = $(doc);
		
		$('#top-banner-big *[data-action="remove"]').on('click', function(e){ Core.preventDefault(e); Core.stopPropagation(e); $(this).parent().slideUp(300); });
		
		if(Page.dimensions.width < 769)
			$('#main-menu > div').customScroll();
		
		$('#main-menu .main-menu > li').on('mouseenter', function(e) {
			var el = $(this);
			mt = setTimeout(function() { el.addClass('active'); }, 300);
		})
		.on('mouseleave', function(e) {
			clearTimeout(mt);
			$(this).removeClass('active');
		});
		/*
		App.sideSliders(); App.listSliders(); App.initSearch(); App.sidebar(); App.initFilters(); App.initViewchanger(); App.initPager(); App.initItems(); App.initFullItem(); App.initProfile(); App.initFormValidation(); App.initShipping(); App.initDocs(); App.initCheckout(); App.initProfileActions(); App.initTouchEvents(); App.initFeedbackForm();
		*/
		App.initSearch();
		App.initProfile();
		App.initProfileActions();
		App.initTouchEvents();
		App.initFeedbackForm();
		App.initPlayerStatsSelectFilter();
		App.initMenuActions();
		
		/* E-Sports */
		App.initStreams();
		App.initMatchesBoard();
	},

	/**
	 * Dynamically load more than one sidebar module at a time.
	 *
	 * @param modules
	 */
	sidebar: function(modules) {
		var s = $('*[data-type="side-bar"]'),
			p = s.parent();
			f = $('.filter-selector', s);
		
		Page.object.on('modulesLoaded', function(e) {
			if(Page.dimensions.width < 993 && s.length > 0 && s.outerHeight(true) + s.position().top > App.win.height())
			{
				s.data('height', s.height()).data('initialHeight', s.outerHeight(true) + s.position().top).height(App.win.height() - (s.outerHeight(true) - s.height()) - s.position().top);
			}
			Page.object.off('modulesLoaded');
			
			p.data('initialHeight', p.height());
			setInterval(function() {
				if(Page.dimensions.width < 993 && (p.height() != p.data('initialHeight')))
				{
					Page.object.trigger('resize').trigger('scroll');
					p.data('initialHeight', p.height());
				}
			}, 100);
		});
		
		Page.object.resize(function(e) {
			if(s.data('initialHeight') == "undefined")
				s.data('initialHeight', s.outerHeight(true) + s.position().top);
			s.data('height', s.height());
			if(Page.dimensions.width < 993 && s.length > 0 && s.outerHeight(true) + s.position().top > App.win.height())
				s.height(App.win.height() - (s.outerHeight(true) - s.height()) - s.position().top).addClass("scrollable");
			else if(Page.dimensions.width < 993 && s.length > 0 && App.win.height() > s.data('initialHeight'))
				s.height("auto");
			else if(Page.dimensions.width < 993 && s.length > 0 && App.win.height() > s.data('height'))
				s.height(App.win.height() - (s.outerHeight(true) - s.height()) - s.position().top);
		});
		
		
		if(modules) {
			for (var i = 0; i <= (modules.length - 1); ++i) {
				App.loadModule(modules[i]);
			}
		}
		else
		{
			var modules = $('*[data-type="side-bar"] *[data-module]');
			App.modules = modules.filter('*[autoload="true"]').length;
			if(App.modules > 0)
				modules.each(function(i) {
					if($(this).attr("autoload") == "true")
						App.loadModule($(this).attr("data-module"));
				});
			else
				App.win.trigger('modulesLoaded');
		}
	},

	/**
	 * Load the content of a sidebar module through AJAX.
	 *
	 * @param key
	 */
	loadModule: function(key) {
		var module = $('#sidebar-'+ key);
		
		if (module.length > 0) {
			$.ajax({
				//url: Core.baseUrl +'/sidebar/'+ key,
				url: 'sidebar/'+ key +'.html',
				type: 'GET',
				dataType: 'html',
				cache: false,
				global: false
			})
			.done(function(data) {
				if (data)
				{
					module.html(data);
					App.modulesLoaded = App.modulesLoaded + 1;
					if(App.modulesLoaded == App.modules)
						App.win.trigger('modulesLoaded');
				}
				else
					module.remove();
			})
			.fail(function() {
				module.remove();
			});
		}
	},
	
	removeImageBlock: function(image_id) {
		$("#id_image_" + image_id).remove();
		return false;
	},
	
	sideSlider: {
		build: function(stage)
		{
			var obj = {
				w: 0,
				stage: stage,
				block: null,
				wrap: null,
				nav: null,
				left: null,
				right: null,
				step: 0,
				items: 0,
				animInProgress: false,
				readyState: 0,
				loader: null,
				steps: [],
				
				load: function()
				{
					var m = this;
					m.stage.data('slideobj', this);
					m.block = $('.side-slider-block', m.stage);
					m.wrap = $('[slider-container="wrap"]', m.stage);
					m.slides = $('*[slider-container="slide"]', m.stage);
					m.nav = $('[slider-container="nav"]', m.stage);
					m.left = $('[slider-nav="left"]', m.nav);
					m.right = $('[slider-nav="right"]', m.nav);
					m.items = m.slides.length;
					m.images = $('> img, .thumb img', m.slides);
					
					function completeSliderImgLoad() {
						var h = 0;
						m.stage.children().each(function(index) {
							if($(this).css("position") != "absolute" || $(this).css("position") != "fixed")
								h = h + parseInt($(this).outerHeight(true));
						});
						m.stage.prev(".loader").animate({height:h + parseInt(m.stage.outerHeight(true) - m.stage.height())}, 400, function() {
							$(this).remove();
							m.stage.removeClass("absolute");
							m.stage.removeClass('invisible');
						});
					};
					
					m.stage.addClass("absolute");
					m.loader = $('<div/>').addClass('loader').width(m.stage.outerWidth(true)).insertBefore(m.stage);
					
					m.slides.each(function(index) {
						var el = $(this);
						m.w = m.w + parseInt(el.outerWidth(true));
						m.step = parseInt(el.outerWidth(true));
					});
					
					m.images.each(function() {
						var el = $(this);
						el.onImageLoaded(function(e) {
							m.readyState = m.readyState + 1;
							if(m.readyState == m.images.length)
								completeSliderImgLoad();
						});
					});
					
					m.wrap.css({width:m.w});
					
					m.left.on('click', function(e) {
						e.preventDefault();
						e.stopPropagation();
						
						m.wrap.animate({marginLeft:0 - ((parseInt($('.active', m.wrap).attr('slide-index')) + 1) * m.step)}, 400, 'swing');
						m.nav.css("left", m.nav.position().left);
						m.block.css("margin-left", 30);
						m.nav.animate({left:0,right:m.step-64}, 400, 'swing');
						var n = $('.active', m.wrap).next(".slide");
						$('.active', m.wrap).removeClass("active");
						m.left.parent().removeClass("left").addClass("right");
						n.addClass("active");
					});
					
					m.right.on('click', function(e) {
						e.preventDefault();
						e.stopPropagation();
						
						m.wrap.animate({marginLeft:0 - ((parseInt($('.active', m.wrap).attr('slide-index')) - 1) * m.step)}, 400, 'swing');
						m.block.css("margin-left", 0);
						m.nav.animate({left:m.step-34,right:-30}, 400, 'swing');
						var p = $('.active', m.wrap).prev(".slide");
						$('.active', m.wrap).removeClass("active");
						m.right.parent().removeClass("right").addClass("left");
						p.addClass("active");
					});
				},
				
				refresh: function() {
					m = this;
					m.w = parseInt($(this).outerWidth(true)) * m.items;
					m.step = parseInt($(this).outerWidth(true));
					
					m.wrap.css({width:m.w});
				}
			};
			
			obj.load();
			return obj;
		}
	},
	
	sideSliders: function()
	{
		if($('*[data-type="side-slider"]').length < 1)
			return false;
		
		var ss = $('*[data-type="side-slider"]');
		ss.each(function(index) {
			App.sideSlider.build($(this));
		});
		
		Page.object.resize(function() {
			ss.each(function(index) {
				$(this).data('slideobj').refresh();
			});
		})
	},
	
	listSlider: {
		build: function(slider)
		{
			var obj = {
				w: 0,
				slider: slider,
				stage: null,
				wrap: null,
				nav: null,
				left: null,
				right: null,
				step: 0,
				items: 0,
				limit: 6,
				tail: 0,
				animInProgress: false,
				readyState: 0,
				loader: null,
				steps: [],
				current: 0,
				
				load: function()
				{
					var m = this;
					m.slider.data('listslideobj', this);
					m.stage = $('*[slider-container="stage"]', m.slider);
					m.stageWidth = m.stage.width();
					m.wrap = $('*[slider-container="wrap"]', m.slider);
					m.nav = $('*[slider-container="nav"]', m.slider);
					m.left = $('*[slider-nav="left"]', m.nav);
					m.right = $('*[slider-nav="right"]', m.nav);
					m.items = $('*[slider-container="slide"]', m.stage).length;
					m.limit = parseInt(m.slider.attr("data-slider-limit")) ? parseInt(m.slider.attr("data-slider-limit")) : Math.round(m.stage.width() / $('*[slider-container="slide"]', m.stage).outerWidth(true));
					m.tail = m.items - m.limit;
					m.needLoader = typeof m.slider.attr("slider-loader") != "undefined" ? parseInt(m.slider.attr("slider-loader")) : 1;
					
					function completeImgLoad()
					{
						var h = 0;
						m.wrap.css({width:m.w + 1});
						m.slider.children().each(function(index) {
							if($(this).css("position") != "absolute" || $(this).css("position") != "fixed")
								h = h + parseInt($(this).outerHeight(true));
						});
						if(m.needLoader)
							m.slider.prev(".loader").animate({height:h + parseInt(m.slider.outerHeight(true) - m.slider.height())}, 400, function() {
								$(this).remove();
								m.slider.removeClass("absolute");
								m.slider.removeClass('invisible');
							});
						
						if(m.w > m.stageWidth)
						{
							m.left.on('click', function(e) {
								e.preventDefault();
								e.stopPropagation();
								
								if(!m.animInProgress && m.current > 0)
								{
									m.animInProgress = true;
									var ml = 0 - m.getMarged(m.current) + m.steps[m.current - 1];
									m.wrap.animate({marginLeft:ml}, 300, function() { m.current = m.current - 1; m.animInProgress = false; });
									m.tail = m.tail + 1;
								}
							});
							
							m.right.on('click', function(e) {
								e.preventDefault();
								e.stopPropagation();
								
								if(!m.animInProgress && m.stageWidth + m.getMarged(m.current) < m.w)
								{
									m.animInProgress = true;
									console.log(0 - m.getMarged(m.current));
									console.log(m.getMarged(m.current) + m.steps[m.current] + m.stageWidth);
									console.log(m.getMarged(m.current) + m.steps[m.current] + m.stageWidth - m.w);
									if(m.getMarged(m.current) + m.steps[m.current] + m.stageWidth > m.w)
										var ml = 0 - m.getMarged(m.current) - m.steps[m.current] + (m.getMarged(m.current) + m.steps[m.current] + m.stageWidth - m.w);
									else
										var ml = 0 - m.getMarged(m.current) - m.steps[m.current];
									m.wrap.animate({marginLeft:ml}, 300, function() { m.current = m.current + 1; m.animInProgress = false; });
									m.tail = m.tail - 1;
								}
							});
						}
						else
						{
							m.left.hide();
							m.right.hide();
						}
					};
					
					if(m.items > 0 && m.needLoader)
					{
						m.slider.addClass("absolute");
						m.loader = $('<div/>').addClass('loader').width(m.slider.outerWidth(true)).insertBefore(m.slider);
					}
					
					$('*[slider-container="slide"]', m.stage).each(function(index) {
						var el = $(this);
						$('[slider-image]', el).onImageLoaded(function(e) {
							m.w = m.w + parseInt(el.outerWidth(true));
							m.step = m.step == 0 ? parseInt(el.outerWidth(true)) : m.step;
							m.steps[index] = parseInt(el.outerWidth(true));
							m.readyState = m.readyState + 1;
							if(m.readyState == m.items)
								completeImgLoad();
						});
					});
				},
				
				refresh: function() {
					m = this;
					m.limit = parseInt(m.slider.attr("data-slider-limit")) ? parseInt(m.slider.attr("data-slider-limit")) : Math.round(m.stage.width() / $('*[slider-container="slide"]', m.stage).outerWidth(true));
					m.w = parseInt($(this).outerWidth(true)) * m.items;
					m.step = parseInt($(this).outerWidth(true));
					
					m.wrap.css({width:m.w});
				},
				
				getVisible: function()
				{
					var m = this,
						length = 0;
					for(var i = m.current; i < m.steps.length; i++)
					{
						if(length > m.stageWidth)
							break;
						length = length + m.steps[i];
					}
					return length;
				},
				
				getMarged: function(index)
				{
					var m = this,
						margin = 0;
					for(var i = 0; i < index; i++)
						margin = margin + m.steps[i];
					return margin;
				}
			};
			
			obj.load();
			return obj;
		}
	},
	
	listSliders: function()
	{
		var ss = $('*[data-type="list-slider"]');
		if(ss.length < 1)
			return false;
		
		ss.each(function(index) {
			App.listSlider.build($(this));
		});
		
		Page.object.resize(function() {
			ss.each(function(index) {
				$(this).data('listslideobj').refresh();
			});
		});
	},
	
	matchesBoard: {
		build: function(slider)
		{
			var obj = {
				w: 0,
				slider: slider,
				stage: null,
				wrap: null,
				nav: null,
				left: null,
				right: null,
				step: 0,
				items: 0,
				limit: 6,
				tail: 0,
				overal: 11,
				animInProgress: false,
				readyState: 0,
				loader: null,
				steps: [],
				current: 0,
				closest: null,
				
				load: function()
				{
					var m = this;
					m.slider.data('listslideobj', this);
					m.stage = $('*[slider-container="stage"]', m.slider);
					m.stageWidth = m.stage.width();
					m.wrap = $('*[slider-container="wrap"]', m.slider);
					m.nav = $('*[slider-container="nav"]', m.slider);
					m.left = $('*[slider-nav="left"]', m.nav);
					m.right = $('*[slider-nav="right"]', m.nav);
					m.items = $('*[slider-container="slide"]', m.stage).length;
					m.closest = $('[slider-container="slide"].closest', m.stage);
					m.limit = parseInt(m.slider.attr("data-slider-limit")) ? parseInt(m.slider.attr("data-slider-limit")) : Math.round(m.stage.width() / $('*[slider-container="slide"]', m.stage).outerWidth(true));
					m.tail = m.items - m.limit;
					m.needLoader = typeof m.slider.attr("slider-loader") != "undefined" ? parseInt(m.slider.attr("slider-loader")) : 1;
					
					function completeImgLoad()
					{
						var h = 0;
						m.wrap.width(m.w + 10);
						m.slider.children().each(function(index) {
							if($(this).css("position") != "absolute" || $(this).css("position") != "fixed")
								h = h + parseInt($(this).outerHeight(true));
						});
						if(m.needLoader)
							m.slider.prev(".loader").animate({height:h + parseInt(m.slider.outerHeight(true) - m.slider.height())}, 400, function() {
								$(this).remove();
								m.slider.removeClass("absolute");
								m.slider.removeClass('invisible');
							});
						
						if(m.closest.length)
						{
							var offset = Math.floor((m.stageWidth / 2) - (m.closest.position().left + parseInt(m.closest.css("marginLeft")) + (m.closest.width() / 2)));
							var rightOffset = Math.floor((m.w - (m.closest.position().left + parseInt(m.closest.css("marginLeft")) + (m.closest.width() / 2))) - (m.stageWidth / 2));
							//m.wrap.css({marginLeft:offset});
							m.wrap.css({marginLeft:m.stageWidth - m.w - 10});
							m.current = m.closest.index();
							var partial = parseInt(m.closest.css("marginLeft")) + (m.closest.width() / 2);
						}
						
						m.left.on('click', function(e) {
							e.preventDefault();
							e.stopPropagation();
							
							var wml = parseInt(m.wrap.css("marginLeft"));
							if(!m.animInProgress && (wml + m.step) < 0)
							{
								m.animInProgress = true;
								var ml = wml + m.steps[m.current - 1];
								m.wrap.animate({marginLeft:ml}, 300, function() { m.current = m.current - 1; m.animInProgress = false; });
								m.tail = m.tail + 1;
							}
							else if(!m.animInProgress && wml != 0)
							{
								m.animInProgress = true;
								m.wrap.animate({marginLeft:0}, 300, function() { m.current = m.current - 1; m.animInProgress = false; });
							}
						});
						
						m.right.on('click', function(e) {
							e.preventDefault();
							e.stopPropagation();
							
							var wml = parseInt(m.wrap.css("marginLeft"));
							if(!m.animInProgress && wml - m.step < m.stageWidth - m.w)
							{
								m.animInProgress = true;
								m.wrap.animate({marginLeft:(m.stageWidth - m.w - 10)}, 300, function() { m.current = m.current + 1; m.animInProgress = false; });
							}
							else if(!m.animInProgress)
							{
								m.animInProgress = true;
								var ml = wml - m.steps[m.current];
								m.wrap.animate({marginLeft:ml}, 300, function() { m.current = m.current + 1; m.animInProgress = false; });
								m.tail = m.tail - 1;
							}
						});
					};
					
					if(m.items > 0 && m.needLoader)
					{
						m.slider.addClass("absolute");
						m.loader = $('<div/>').addClass('loader').width(m.slider.outerWidth(true)).insertBefore(m.slider);
					}
					
					$('*[slider-container="slide"]', m.stage).each(function(index) {
						var el = $(this);
						m.w = m.w + parseInt(el.outerWidth(true));
						m.step = m.step == 0 ? parseInt(el.outerWidth(true)) : m.step;
						m.steps[index] = parseInt(el.outerWidth(true));
						m.readyState = m.readyState + 1;
						if(m.readyState == m.items)
							completeImgLoad();
					});
				},
				
				refresh: function() {
					m = this;
					m.limit = parseInt(m.slider.attr("data-slider-limit")) ? parseInt(m.slider.attr("data-slider-limit")) : Math.round(m.stage.width() / $('*[slider-container="slide"]', m.stage).outerWidth(true));
					m.w = parseInt($(this).outerWidth(true)) * m.items;
					m.step = parseInt($(this).outerWidth(true));
					
					m.wrap.css({width:m.w});
				},
				
				getVisible: function()
				{
					var m = this,
						length = 0;
					for(var i = m.current; i < m.steps.length; i++)
					{
						if(length > m.stageWidth)
							break;
						length = length + m.steps[i];
					}
					return length;
				},
				
				getMarged: function(index)
				{
					var m = this,
						margin = 0;
					for(var i = 0; i < index; i++)
						margin = margin + m.steps[i];
					return margin;
				}
			};
			
			obj.load();
			return obj;
		}
	},
	
	initMatchesBoard: function()
	{
		var mb = $('*[data-type="matches-board"]');
		if(mb.length < 1)
			return false;
		
		App.matchesBoard.build(mb);
		Page.object.resize(function() {
			mb.each(function(index) {
				$(this).data('listslideobj').refresh();
			});
		});
	},
	
	initViewchanger: function() {
		var btns = $('[data-action="change-view"]'),
			c = $('.elements-collection');
		
		btns.on('click', function(e) {
			e.stopPropagation();
			e.preventDefault();
			
			var el = $(this);
			if(el.attr("data-value") == "th")
			{
				c.removeClass("list").addClass("thumbs");
				btns.removeClass("active");
				el.addClass("active");
				Cookie.create("viewchanger", "th", {"expires":356, "path":"/"});
			}
			else if(el.attr("data-value") == "list")
			{
				c.removeClass("thumbs").addClass("list");
				btns.removeClass("active");
				el.addClass("active");
				Cookie.create("viewchanger", "list", {"expires":356, "path":"/"});
			}
		});
	},
	
	initPager: function() {
		var btns = $('[data-action="page-select"]'),
			csc = $('[data-action="change-show-count"]'),
			url = URLs.page;
		
		btns.on('click', function(e) {
			e.stopPropagation();
			e.preventDefault();
			
			var el = $(this);
			if(el.hasClass("active"))
			{
				el.removeClass("active");
				el.removeTooltip();
			}
			else
			{
				el.addClass("active");
				var t = $('<div/>').addClass("with-padding input-group round-corners go-to-page");
				var i = $('<input/>').addClass("input").attr("type","text").attr("name","page").appendTo(t);
				var s = $('<button/>').addClass("button").html(Msg.ui.go).appendTo(t).on('click', function(e) {
					e.stopPropagation();
					e.preventDefault();
					
					if(i.val()!="")
					{
						pattern = new RegExp(/page\/[0-9-_~^%*#()]+/g),
						url = i.val()=="1"?window.location.href.replace(pattern, ""):/\/\?/.test(window.location.href)?window.location.href.replace(/\/\?/, "/page/"+ i.val() +"?"):/\?/.test(window.location.href)?window.location.href.replace(/\?/, "/page/"+ i.val() +"?"):pattern.test(window.location.href)?window.location.href.replace(pattern, "/page/"+ i.val()):/\/$/.test(window.location.href)?window.location.href + "page/"+ i.val():window.location.href + "/page/"+ i.val();
						window.location = url;
					}
				});
				el.tooltip(t);
			}
		});
	},
	
	initSearch: function() {
		var wrap = $('*[data-type="search-form"]'),
			form = $('form', wrap),
			input = $('#search-query', form),
			c = $('*[data-container="search-query-type"]', form);
		
		input.on('focus', function(e) {
			c.slideDown();
		});
		
		c.on('dblclick', function(e) {
			c.slideUp();
		});
		
		$('input', c).on('change', function() {
			c.slideUp();
		});

		window.displayBoxIndex = -1;
		var Navigate = function(diff)
		{
			displayBoxIndex += diff;
			var oBoxCollection = $("div#live-search-container").children();
			if (displayBoxIndex >= oBoxCollection.length)
				displayBoxIndex = 0;
			if (displayBoxIndex < 0)
				displayBoxIndex = oBoxCollection.length - 1;
			var cssClass = "hovered";
			oBoxCollection.removeClass(cssClass).eq(displayBoxIndex).addClass(cssClass);
		}

		$('input[name=q]').on("keydown", function (e) {
			var code = e.keyCode || e.which;
			if (code === 40) // Down arrow
				Navigate(1);
			else if (code === 38) // Up arrow
				Navigate(-1);
		
			var hovered = $('div#live-search-container a.hovered').length;
			if (code == 13 && hovered != 0)
			{
				window.location = $('div#live-search-container a.hovered').attr('href');
				return false;
			}
		});
		
		$('input[name=q]').on("keyup", function(e) {
			if ($(this).val().length == 0) $('div#live-search-container').hide();
			var code = e.keyCode || e.which;
			if (code != 40 && code != 38) doSearch();
		});
		
		$('input[name=q]').on("focus", function() {
			doSearch();
		});
		
		$('html').on("click", function() {
			$('div#live-search-container').empty().hide();
		});
		
		$('div#live-search-container, input[name=q]').on("click", function(e) {
			e.stopPropagation();
		});
		
		function doSearch()
		{
			var query = $('input#search-query').val();
			if (query.length > 2)
			{
				$.ajax({
					url: '/search/live',
					data: 'q=' + query,
					dataType: 'json'
				})
				.done(function(data) {
					$('div#search-query-type').hide();
					if (data.length > 0) { $('div#live-search-container').show(); }
					else { $('div#live-search-container').hide(); }
					$('div#live-search-container').empty();
					$.each(data, function(k, v) {
						var title = v.title.replace(new RegExp(query,'gi'), "<b>$&</b>");
						$('div#live-search-container').append('<a class="live-search-link" href="'+v.url+'" style="display:block;padding:10px;color:black;text-decoration:none;">'+title+'</a>');
					});
				});
			}
		}
	},
	
	initProfile: function()
	{
		var avatar = $('*[data-profile-action="remove-avatar"]'),
			o = $('*[data-action="open-panel"]');
		
		avatar.on('click', function(e) {});
		o.on('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			
			var el = $(this);
			if(el.parent().hasClass("opened"))
				el.parent().removeClass("opened");
			else
				el.parent().addClass("opened");
		});
	},
	
	initPrettyLinks: function(parent)
	{
		return false;
		parent = $(parent);
		
		if(parent.length)
		{
			$.ajax({
				url: Core.baseUrl +"/teams/get",
				data: "f=name,short_name,alias",
				dataType: 'json'
			})
			.done(function(response) {
				if(response.status === 0)
				{
					var matchArr = [];
					for(var i in response.data)
						matchArr.push(response.data[i].teams_name +"|"+ response.data[i].teams_short_name);
					var html = parent.html();
					var pattern = new RegExp(matchArr.join("|"), "gi");
					console.log(html.match(pattern));
				}
			});
		}
	},
	
	initFilters: function() {
		var fl = $('[data-type="filter"]'),
			sr = $('[data-type="sort"] [data-value]'),
			sf = $('[data-type="slider-filter"]'),
			fPattern = new RegExp('filter\/[A-Za-z0-9-_~,<>\=\%\:\;\!]+\/|filter\/[A-Za-z0-9-_~,<>\=\%\:\;\!]+$', 'g'),
			d = new Array();
		
		sf.each(function(i) {
			var wrap = $(this),
				m = $('[filter-action="filter"]', wrap),
				c = $('[filter-action="clear"]', wrap),
				sf = $('[slider-filter]', wrap),
				name = sf.attr("id"),
				sel = $('#'+ name +'-start', wrap),
				eel = $('#'+ name +'-end', wrap),
				filter = wrap.attr("data-content"),
				pattern = new RegExp(filter+'=([A-Za-z0-9-_~,<>\=\%\:\!]+\;)'),
				pagepattern = new RegExp('\/page\/([0-9-_~,<>\=\%\:\!]+)'),
				match = window.location.href.match(pattern),
				matches = !match?[]:match[1].split(':'),
				slider = sf.data('slider');
			
			if(matches.length > 1)
			{
				slider.setValue(matches[0], matches[1]);
				c.show();
			}
				
			m.off().on('click', function(e) {
				e.preventDefault();
				e.stopPropagation();
				
				if(pagepattern.test(window.location.href))
					var url = window.location.href.replace(pagepattern, "");
				else
					var url = window.location.href;
				
				if(sel.val()==""&&eel.val()=="")
					url = url.replace(fPattern, "");
				else if(/\/$|\;$/.test(url))
				{
					var test = fPattern.test(url);
					if(test&&pattern.test(url))
						url = url.replace(pattern, filter +"="+ sel.val() +":"+ eel.val() +";");
					else if(test&&!pattern.test(url))
						url = url + filter +"="+ sel.val() +":"+ eel.val() +";";
					else
						url = url +"filter/"+ filter +"="+ sel.val() +":"+ eel.val() +";";
				}
				else if(pattern.test(url))
					url = url.replace(pattern, filter +"="+ sel.val() +":"+ eel.val() +";");
				else
					url = url +"/filter/"+ filter +"="+ sel.val() +":"+ eel.val() +";";
				
				url.replace(/\/$/, "").replace(/\;$/, "");
				window.location = url;
			});
			
			c.on('click', function(e) {
				url = window.location.href.replace(pattern, "");
				if(/filter\/$/.test(url))
					url = url.replace(/filter\/$/, "").replace(/\/$/, "").replace(/\;$/, "");
				window.location = url;
			});
		});
		
		fl.each(function(i) {
            var wrap = $(this),
				f = $('[filter]', wrap),
				c = $('[filter-action="clear"]', wrap),
				ca = $('[filter-action="clear-all"]'),
				m = $('[filter-action="more"]', wrap),
				b = $('[filter-container="more"]', wrap),
				bc = $('[filter-action="remove"]', b),
				fg = $('.filter-wrapper [filter-group]', b),
				fwg = $('.filter-group-wrapper', b),
				fgs = $('[filter-group]', fwg),
				sc = $('.slider-cursor', f);
			
			wrap.removeData();
			c.on('click', function(e) {
				d = new Array();
				clearFilters(wrap);
				makeRequest(wrap);
				c.hide();
			});
			
			ca.off().on('click', function(e) {
				url = window.location.href.replace(fPattern, "");
				if(/filter\/$/.test(url))
					url = url.replace(/filter\/$/, "").replace(/\/$/, "").replace(/\;$/, "");
				window.location = url;
			});
			
			m.on('click', function(e) {
				e.preventDefault();
				e.stopPropagation();
				var el = $(this),
					sb = el.closest(".side-bar");
				b.fadeIn(400, function() { sb.refreshScroll(); });
			});
			
			bc.on('click', function(e) {
				var el = $(this),
					sb = el.closest(".side-bar");
				b.fadeOut(200, function() { sb.customScroll(); });
			});
			
			fg.on('click', function(e) {
				fg.removeClass("selected");
				$(this).addClass("selected");
				var g = $(this).attr("filter-group");
				var target = $('*[filter-group="'+ g +'"]', fwg);
				var h = 0;
				target.nextUntil("*[filter-group]").each(function() {
					h += $(this).outerHeight(true);
				});
				
				if (target.length != 1)
					return;
				
				var win = fwg,
					winTop = win.scrollTop(),
					winBottom = winTop + win.height(),
					top = target.position().top
					bottom = top + target.outerHeight(true) + h;
				
				if (top >= winTop && bottom <= winBottom)
					return;
				
				fwg.animate({
					scrollTop: (top < winTop ? top : bottom - win.height())
				}, 200);
			});
			
			f.each(function(index) {
				var el = $(this);
				var filter = wrap.attr("data-content");
				var filterValue = el.attr("filter-id");
				var curPattern = new RegExp(filter+'=([A-Za-z0-9-_~,<>\=\:\!]+)');
				var match = window.location.href.match(curPattern);
				var matches = !match?[]:match[1].split(',');
				wrap.data("filter", matches);
				if($.inArray(filterValue, matches)>=0)
				{
					if(el.data("replacement"))
						el.data("replacement").trigger("click");
					else
						el.trigger("change");
					
					c.show();
				}
				
				attachEvents(el, wrap, c);
            });
        });
		
		sr.on('click', function(e) {
			var el = $(this),
				val = el.attr("data-value"),
				content = $("#"+ el.attr("filter-content")),
				pattern = new RegExp('sort\/[A-Za-z0-9-_~,<>\=\%\:\!\;]+\/|sort\/[A-Za-z0-9-_~,<>\=\%\:\!\;]+$', 'g'),
				url = val==""?window.location.href.replace(pattern, ""):pattern.test(window.location.href)?window.location.href.replace(pattern, "sort\/"+ val):/\/$/.test(window.location.href)?window.location.href +"sort\/"+ val:window.location.href +"/sort\/"+ val;
				window.location = url.replace(/\/$/, "").replace(/\;$/, "");
		});
		
		function attachEvents(el, wrap, c)
		{
			if(el.is('input[type="checkbox"]'))
			{
				el.on('change', function(e) {
					var d = wrap.data("filter") ? wrap.data("filter") : new Array();
					if(el.prop("checked"))
					{
						if(d.indexOf(el.attr("filter-id")) < 0)
						{
							d.push(el.attr("filter-id"));
							wrap.data("filter", d);
							if(d.length > 0)
								c.show();
						}
						else
						{
							d.push(el.attr("filter-id"));
							wrap.data("filter", d);
						}
					}
					else
					{
						if(d.indexOf(el.attr("filter-id")) >= 0)
						{
							var key = d.indexOf(el.attr("filter-id"));
							d.splice(key, 1);
							wrap.data("filter", d);
							if(d.length <= 0)
								c.hide();
						}
					}
					
					makeRequest(wrap);
				});
			}
			else if(el.is('input[type="radio"]'))
			{
				console.log("radio");
			}
			else if(el.is("div, a, span, p, li"))
			{
				console.log(el.contents());
			}
		};
		
		function makeRequest(el)
		{
			this.xhr ? this.xhr.abort() : null;
			var c = $('.elements-collection');
			var overlay = $('<div/>').addClass("overlay").appendTo(c);
			
			var str = el.data("filter") ? el.data("filter").join(",") : "";
			var filter = el.attr("data-content");
            
			var pattern = new RegExp(filter+'=([A-Za-z0-9-_~,<>\=\%\:\!]+\;)');
			var pagepattern = new RegExp('\/page\/([0-9-_~,<>\=\%\:\!]+)');
			
			if(pagepattern.test(window.location.href))
				var url = window.location.href.replace(pagepattern, "");
			else
				var url = window.location.href;
                

			if(!str && !el.hasClass("active-filter"))
			{
				url = url.replace(fPattern, "");
				if(/filter\/$/.test(url))
					url = url.replace(/filter\/$/, "").replace(/\/$/, "").replace(/\;$/, "");
			}
			else if(!str && el.hasClass("active-filter"))
			{
				url = url.replace(pattern, "");
				if(/filter\/$/.test(url))
					url = url.replace(/filter\/$/, "").replace(/\/$/, "").replace(/\;$/, "");
			}
			else if(/\/$|\;$/.test(url))
			{
				var test = fPattern.test(url);
				if(test&&pattern.test(url))
					url = url.replace(pattern, filter +"="+ str +";");
				else if(test&&!pattern.test(url))
					url = url + filter +"="+ str +";";
				else
					url = url +"filter/"+ filter +"="+ str +";";
			}
			else if(pattern.test(url))
				url = url.replace(pattern, filter +"="+ str +";");
			else
				url = url +"/filter/"+ filter +"="+ str +";";
			
			url.replace(/\/$/, "").replace(/\;$/, "");


            // Fix from sort filters by gobit
            var arr = url.split("/filter/");
            if(arr.length>=2)
            {
                var filters =  arr[1].split(";");
                if(filters.length>=2)
                {
                    filters.sort();
                    var filterForUrl = [];
                    filters.forEach(function(e) {
                            if(e.length)
                            {
                                // sort values
                                var filter = e.split("=");
                                var sorted = filter[1].split(",").sort();
                                filterForUrl.push(filter[0] + "=" + sorted);
                            }
                                
                        });
                    url = arr[0] + "/filter/" + filterForUrl.join(";") + ";";
                }
            }
            // END Fix from sort filters

			window.location = url;
		};
		
		function clearFilters(el)
		{
			var f = $('[filter]', el);
			/*f.each(function(index) {
				var el = $(this);
				
                if(el.is('input[type="checkbox"]'))
				{
					if(el.prop("checked"))
					{
						if(el.parent().hasClass("replacement"))
							el.parent().trigger('click');
						else
							el.trigger('change');
					}
				}
				else if(el.is('input[type="radio"]'))
				{
					console.log("radio");
				}
				else if(el.is("div, a, span, p, li"))
				{
					console.log(el.contents());
				}
            });*/
			el.removeData();
		};
		
		function resortList(el)
		{
			var a = el.attr('id').split("-"),
				id = el.attr('id'),
				tmpId,
				wrap = el.closest('*[data-type="filter"]'),
				c = $('*[filter-action="clear"]', wrap);
			
			if(a[a.length - 1] == "listed")
			{
				tmpId = id.substr(0,id.lastIndexOf("-"));
				if($('#'+ tmpId, fl).parent().hasClass("replacement"))
					$('#'+ tmpId, fl).parent().trigger('click');
				else
					$('#'+ tmpId, fl).trigger('change');
			}
			else
			{
				if($('#'+ id +'-listed', fl).length > 0)
				{
					if($('#'+ id +'-listed', fl).parent().hasClass("replacement"))
						$('#'+ id +'-listed', fl).parent().trigger('click');
					else
						$('#'+ id +'-listed', fl).trigger('change');
				}
				else
				{
					var newEl = $('<li/>').appendTo(".listed-filters", wrap).hide();
					var input = $('<input/>').attr("type", el.attr('type')).attr("value", el.attr('value')).attr("filter-id", el.attr('filter-id')).attr("filter", el.attr('filter')).addClass("checkbox").attr("id", id +'-listed').attr("name", el.attr('name')).appendTo(newEl);
					var label = $('<label/>').attr('for', id +'-listed').html($('*[for="'+ id +'"]', wrap).html()).appendTo(newEl);
					newEl.slideDown();
					
					if(input.parent().hasClass("replacement"))
						input.parent().trigger('click');
					else
						input.trigger('change');
					
					attachEvents(input, wrap, c);
				}
			}
		};
	},
	
	initPlayerStatsSelectFilter: function()
	{
		var filters = $('*[data-type="select-filter"]');
		
		filters.each(function(i) {
			var el = $(this),
				filter = el.attr("data-filter"),
				open = $('[data-action="filter-open"]', el),
				filter = $('[data-type="filter-button"]', el),
				selected = $('[data-container="selected-value"]', el),
				dropDown = $('.drop-down', el),
				target = el.attr("data-target"),
				requestType = el.attr("data-request-type"),
				container = $('[data-container="'+ target +'"]'),
				itemId = el.attr("data-id"),
				alias = el.attr("data-route-alias"),
				width = 0,
				xhr = null;
			
			open.off("click").on("click", function(e) {
				e.preventDefault();
				e.stopPropagation();
				
				if(el.hasClass("opened"))
					el.removeClass("opened");
				else
					el.addClass("opened");
			});
			
			filter.off("click").on("click", function(e) {
				e.preventDefault();
				e.stopPropagation();
				
				var fel = $(this),
					value = fel.attr("data-filter-value"),
					href = fel.attr("data-filter-href");
				
				var pattern = new RegExp(Core.baseUrl +"\/([A-Za-z0-9-_~,<>\=\%\:\!\;]+)\/"+ alias +"\/([A-Za-z0-9-_~,<>\=\%\:\!\;]+)");
				var result = window.location.href.match(pattern);
				
				if(result && value != "")
					var url = window.location.href.replace(result[1], value);
				else if(!result && value != "")
				{
					var emptyPattern = new RegExp(Core.baseUrl +"\/"+ alias +"\/([A-Za-z0-9-_~,<>\=\%\:\!\;]+)");
					var result = window.location.href.match(emptyPattern);
					var url = window.location.href.replace(emptyPattern, Core.baseUrl +"/"+ value +"/"+ alias +"/"+ result[1]);
				}
				else if(result && value == "")
					var url = window.location.href.replace(pattern, Core.baseUrl +"/"+ alias +"/"+ result[2]);
				else
					var url = window.location.href;
				
				if(requestType == "json")
				{
					container.html('<div class="loader"></div>');
					if(xhr) { xhr.abort(); }
					xhr = $.ajax({
						url: Core.baseUrl +"/"+ alias +"/get-stats",
						type: "GET",
						dataType: 'html',
						data: "c="+ value +"&id="+ itemId
					})
					.done(function(response) {
						container.html(response);
						history.replaceState({alias: value}, alias, url);
						selected.html(fel.html());
					})
					.fail(function() {
						container.html(Msg.ui.requestError);
					})
					.always(function() {
						xhr = null;
					});
				}
				else
					window.location = url;
				
				el.removeClass("opened");
			});
		});
		
		App.doc.off("click.closeSelectFilters").on("click.closeSelectFilters", function(e) {
			if(!$(e.target).closest('[data-type="select-filter"]').length)
				$('[data-type="select-filter"]').removeClass("opened");
		});
	},
	
	initFormValidation: function(form)
	{
		var forms = $('*[data-type="validation-form"]');
		
		if(typeof form != "undefined")
			forms = $(form);
		
		forms.each(function(i) {
			$('.errors', $(this)).each(function() {
				var el = $(this);
				if(el.text() != "")
				{
					el.siblings("input").addClass("error");
					el.show();
				}
			});
			
			if(this.validator)
				return false;
			
			var v = Validator.create(this),
				form = $(this),
				elms = $('*[validators]', form);
			
			elms.each(function() {
				var el = $(this),
					vals = el.attr("validators").split(","),
					errorStr = "";
					
				for(var itr = 0; itr < vals.length; itr++)
				{
					var str = vals[itr].search("=") ? $.trim(vals[itr]).substr(0, $.trim(vals[itr]).search("=")) : $.trim(vals[itr]);
					switch(str)
					{
						case "req":
						case "required":
							errorStr = Msg.formErrors.required.replace('{field}', (el.siblings("label").length > 0 ? el.siblings("label").html() : el.attr("placeholder")));
							break;
						case "maxlength":
						case "maxlen":
							var epos = vals[itr].search("=");
							if (epos >= 0)
								cmdvalue = vals[itr].substr(epos + 1);
							else
								break;
							errorStr = Msg.formErrors.notGreaterThan.replace('{field}', (el.siblings("label").length > 0 ? el.siblings("label").html() : el.attr("placeholder"))).replace('{value}', cmdvalue);
							break;
						case "minlength":
						case "minlen":
							var epos = vals[itr].search("=");
							if (epos >= 0)
								cmdvalue = vals[itr].substr(epos + 1);
							else
								break;
							errorStr = Msg.formErrors.notLessThan.replace('{field}', (el.siblings("label").length > 0 ? el.siblings("label").html() : el.attr("placeholder"))).replace('{value}', cmdvalue);
							break;
						case "alnum":
						case "alphanumeric":
							errorStr = Msg.formErrors.alnumOnly;
							break;
						case "alnum_s":
						case "alphanumeric_space":
							errorStr = Msg.formErrors.alnumspaceOnly;
							break;
						case "num":
						case "numeric":
						case "dec": 
						case "decimal":
							errorStr = Msg.formErrors.numOnly;
							break;
						case "num_s":
						case "numeric_s":
						case "dec_s":
						case "decimal_s":
							errorStr = Msg.formErrors.numspaceOnly;
							break;
						case "alphabetic":
						case "alpha":
							errorStr = Msg.formErrors.alphaOnly;
							break;
						case "alphabetic_space":
						case "alpha_s":
							errorStr = Msg.formErrors.alphaspaceOnly;
							break;
						case "email":
							errorStr = Msg.formErrors.email;
							break;
						case "lt":
						case "lessthan":
							var epos = vals[itr].search("=");
							if (epos >= 0)
								cmdvalue = vals[itr].substr(epos + 1);
							else
								break;
							errorStr = Msg.formErrors.lessThan.replace('{field}', (el.siblings("label").length > 0 ? el.siblings("label").html() : el.attr("placeholder"))).replace('{value}', cmdvalue);
							break;
						case "gt":
						case "greaterthan":
							var epos = vals[itr].search("=");
							if (epos >= 0)
								cmdvalue = vals[itr].substr(epos + 1);
							else
								break;
							errorStr = Msg.formErrors.greaterThan.replace('{field}', (el.siblings("label").length > 0 ? el.siblings("label").html() : el.attr("placeholder"))).replace('{value}', cmdvalue);
							break;
						case "regexp":
							errorStr = Msg.formErrors.doesntMachPattern.replace('{field}', (el.siblings("label").length > 0 ? el.siblings("label").html() : el.attr("placeholder")));
							break;
						case "dontselect":
							errorStr = Msg.formErrors.cannotSelect;
							break;
						case "dontselectchk":
							errorStr = Msg.formErrors.cannotCheck;
							break;
						case "shouldselchk":
							errorStr =  Msg.formErrors.shouldbeCheck;
							break;
						case "selmin":
							errorStr = "";
							break;
						case "selmax":
							errorStr = "";
							break;
						case "selone_radio":
						case "selone":
							errorStr = "";
							break;
						case "dontselectradio":
							errorStr = Msg.formErrors.cannotSelect;
							break;
						case "selectradio":
							errorStr = Msg.formErrors.shouldbeSelect;
							break;
							//Comparisons
						case "eqelmnt":
							errorStr = Msg.formErrors.doesntMach;
							break;
						case "ltelmnt":
						case "leelmnt":
						case "gtelmnt":
						case "geelmnt":
						case "neelmnt":
							errorStr = "";
							break;
						case "req_file":
							errorStr = "";
							break;
						case "file_extn":
							errorStr = "";
							break;
					}
					
					v.addValidation(el.attr("name"), $.trim(vals[itr]), errorStr);
				}
				
				el.on('change', function(e) {
					if(this.validationset)
					{
						var elm = this;
						setTimeout(function() {
							elm.validatorobj.clearErrorMsg();
							elm.validationset.validate();
							elm.validatorobj.showFinalErrorMsg();
						},
						200);
					}
				});
			});
		});
	},
	
	initProfileActions: function() {
		var a = $('[data-type="login"]'),
			b = $('[data-type="register"]'),
			u = $('[data-type="user-menu"]');
		
		a.on('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			
			if(window.location.pathname == "/login" || window.location.pathname == "/register" || window.location.pathname == "/restore" || window.location.pathname.match("\/activation"))
				window.location = "/login";
			var innerHTML = '<div class="form-container">'+
				'<form action="/login" method="POST" data-type="validation-form" name="login">'+
					'<fieldset class="column">'+
						'<div class="col">'+
							'<label for="email">'+ Msg.ui.Email +'</label>'+
							'<input type="text" id="email" name="email" value="" class="input" validators="req, email" />'+
						'</div>'+
						'<div class="col">'+
							'<label for="password">'+ Msg.ui.Password +' <span>*</span></label>'+
							'<input type="password" id="password" name="password" value="" class="input" validators="req" />'+
						'</div>'+
					'</fieldset>'+
					'<div class="cl"></div>'+
					'<input type="hidden" name="timestamp" value="'+ new Date().getTime() +'" />'+
				'</form>'+
				'<div class="vr"></div>'+
				'<div class="social-signup">'+
					'<h5 class="">'+ Msg.ui.notRegisteredYet +'</h5>'+
					'<a class="fb" href="https://www.facebook.com/dialog/oauth?client_id='+ Core.fbAppId +'&amp;scope=email,user_about_me,user_photos&amp;redirect_uri='+ Core.projectUrl +'/facebook-auth" title="'+ Msg.ui.fbSignin +'"></a>'+
					'<a class="vk" href="http://api.vkontakte.ru/oauth/authorize?client_id='+ Core.vkAppId +'&amp;scope=photos&amp;redirect_uri='+ Core.projectUrl +'/vk-auth&amp;response_type=code" title="'+ Msg.ui.vkSignin +'"></a>'+
					'<a class="tw" href="'+ Core.projectUrl +'/twitter-auth?type=tw" title="'+ Msg.ui.twSignin +'"></a>'+
					'<a class="plain-text" href="/register">'+ Msg.ui.register +'</a>'+
				'</div>'+
				'<div class="cl"></div>'+
			'</div>';
			
			var d = DLG.init({key:"login", moveable:true, shader:false, scroll:true, close:true, ctrl:true, btn:false, remove:true, title:Msg.ui.Login})
				.addElement({type:'div', attr:{className:'auth small-form styled-form', innerHTML:innerHTML}})
				.addControl({type:"button", busy:true, attr:{id:"log-in", className:'button blue-gradient', innerHTML:Msg.ui.Login}, onClick:function() { $('form', DLG.modals["login"].containers.content).submit(); App.makeBusy($(this), false); }})
				.addControl({type:"button", busy:false, attr:{className:'button', innerHTML:Msg.ui.forgotPass}, onClick:function() { window.location = "/restore"; }})
				.addControl({type:"button", busy:false, attr:{className:'button', innerHTML:Msg.ui.cancel}, onClick:function() { DLG.modals["login"].hide(); }})
				.onShow(function() { App.initFormValidation(); })
				.show()
				.placeCenter();
			
			$('input', DLG.modals["login"].containers.content).on("keyup", function(e) {
				if(e.keyCode == 13)
				{
					$('form', DLG.modals["login"].containers.content).submit();
					App.makeBusy($('#log-in'), false);
				}
			});
		});
		
		b.on('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			
			var innerHTML = '<form action="/register" method="POST" data-type="validation-form" name="register">'+
				'<fieldset class="column">'+
					'<div class="col">'+
						'<label for="email">'+ Msg.ui.Email +'</label>'+
						'<input type="text" id="mail" name="email" value="" class="input" validators="req, email" />'+
					'</div>'+
					'<div class="col">'+
						'<label for="pass">'+ Msg.ui.Password +' <span>*</span></label>'+
						'<input type="password" id="pass" name="newPass" value="" class="input" validators="req" />'+
					'</div>'+
					'<div class="col">'+
						'<label for="conf_pass">'+ Msg.ui.Confirm_password +' <span>*</span></label>'+
						'<input type="password" id="conf_pass" name="newPassConf" value="" class="input" validators="req, eqelmnt=pass" />'+
					'</div>'+
				'</fieldset>'+
				'<div class="cl"></div>'+
				'<input type="hidden" name="timestamp" value="'+ new Date().getTime() +'" />'+
			'</form>';
			
			var d = DLG.init({key:"register",moveable:true,shader:false,scroll:true,close:true,ctrl:true,btn:false,remove:true,title:Msg.ui.Register})
				.addElement({type:'div', attr:{className:'styled-form', innerHTML:innerHTML}})
				.addControl({type:"button", busy:true, attr:{id:"log-in", className:'button blue-gradient', innerHTML:Msg.ui.Register}, onClick:function() { $('form', DLG.modals["register"].containers.content).submit(); App.makeBusy($(this), false); }})
				.addControl({type:"button", busy:false, attr:{className:'button light-yellow-gradient', innerHTML:Msg.ui.cancel}, onClick:function() { DLG.modals["register"].hide(); }})
				.onShow(function() { App.initFormValidation(); })
				.show()
				.placeCenter();
		});
		
		if(Modernizr.touch)
		{
			b.on('click', function(e) {
				e.preventDefault();
				e.stopPropagation();
				
				var el = $(this);
				if(el.hasClass("active"))
					el.removeClass("active");
				else
					add.hasClass("active");
			});
		}
	},
	
	initTouchEvents: function()
	{
		if(Page.dimensions.width < 1024)
			$('#header .nav-container nav [data-action="mian-menu-toggle"]').on('click', function(e) {
				e.preventDefault();
				e.stopPropagation();
				
				if($(this).parent().find(" > ul").hasClass("opened"))
					$(this).parent().find(" > ul").removeClass('opened');
				else
					$(this).parent().find(" > ul").addClass('opened');
			});
		
		if(Page.dimensions.width < 768)
			$('.section-title [data-action="theme-filter"]').on('click', function(e) {
				e.preventDefault();
				e.stopPropagation();
				
				var el = $(this),
					drop = el.siblings('[data-container="themes-dropdown"]');
				
				if(drop.hasClass("opened"))
					drop.removeClass('opened');
				else
					drop.addClass('opened');
			});
	},
	
	initTimers: function()
	{
		var t = $('[data-type="timer"]');
		t.each(function(i) {
			var el = $(this),
				time = el.attr("data-start");
			
			Timer.init(el, time);
		});
	},
	
	initStreams: function()
	{
		$.ajax({
			type: 'GET',
			url: Core.baseUrl +"/streams/get",
			dataType: 'json'
		})
		.done(function(response) {
			var menuItem = $('#header .nav-container [href="/streams"]');
			var counter = $('.count', menuItem.parent());
			
			if(response.status === 0)
			{
				if(response.data.total > 0)
				{
					if(counter.length > 0)
						counter.html(response.data.total);
					else
						menuItem.parent().append('<span class="count">'+ response.data.total +'</span>');
				}
				else if(counter.length > 0)
					counter.remove();
			}
			else
			{
				if(counter.length > 0)
					counter.remove();
			}
		});
		
		var t = setTimeout(App.initStreams, 60000);
	},
	
	initMenuActions: function()
	{
		var a = $('[data-menu-action="show-submenu"]'),
			sub = a.siblings('.sub-menu');
		
		a.on('mouseenter', function(e) {
			var el = $(this),
				s = sub.clone().addClass("showed-submenu").appendTo("body");
			
			s.css({left:el.offset().left - 1, top:el.offset().top + parseInt(el.outerHeight() - 2)}).show().on('mouseleave.hideSubmenu', function(e) {
				var rt = $(e.relatedTarget);
				if(rt != el)
					$('.showed-submenu').off('mouseleave.hideSubmenu').remove();
			});
		});
		
		a.on('mouseleave', function(e) {
			var rt = $(e.relatedTarget);
			if(!rt.closest('.showed-submenu').length)
				$('.showed-submenu').off('mouseleave.hideSubmenu').remove();
		});
	},
	
	initFeedbackForm: function() {
		var a = $('*[data-type="feedback"]');
		
		a.on('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			
			var d = new Date();
			var feedbackInfo = '<input name="ccid" id="ccid" value="'+ (Profile.user.user_id ? Profile.user.user_id : 'guest') +'" type="hidden">'
			+'<input name="time1" value="'+ d.getTime() +'" type="hidden">'
			+'<input name="referer" value="'+ window.location.pathname +'" type="hidden">';
			
			DLG.init({key:'feedback',moveable:true,shader:false,scroll:true,close:true,ctrl:true,btn:false,remove:true,title:Msg.feedback.leave_feedback})
				.addClass('feedback')
				.addElement({type:'form', attr:{className:'form', id:"feedback-form", innerHTML:feedbackInfo}})
				.addElement({type:'table', attr:{className:'table', id:"feedback-form-table"}, target:"#feedback-form"})
				.addElement({type:'tr', attr:{className:'top-table-header'}, target:"#feedback-form-table"})
				.addElement({type:'td', attr:{className:'left-table-cell', innerHTML:'<div class="header">'+ Msg.feedback.feedback_give +'</div>'}, target:".top-table-header"})
				.addElement({type:'td', attr:{className:'right-table-cell', innerHTML:'<div class="header">'+ Msg.feedback.feedback_rate_exp +'</div>'}, target:".top-table-header"})
				.addElement({type:'tr', attr:{className:'top-table-row'}, target:"#feedback-form-table"})
				
				.addElement({type:'td', attr:{className:'left-table-cell', id:'CommentCard'}, target:".top-table-row"})
				.addElement({type:'div', attr:{className:'row card-options button-height'}, target:"#CommentCard"})
				.addElement({type:'select', attr:{className:'select expandable-list topic-selection full-width', name:'topic_selection', innerHTML:'<option value="0">'+ Msg.feedback.topic +'</option><option value="problem">'+ Msg.feedback.problem +'</option><option value="suggestion">'+ Msg.feedback.suggestion +'</option><option value="compliment">'+ Msg.feedback.compliment +'</option><option value="criticism">'+ Msg.feedback.criticism +'</option>'}, target:"#CommentCard .card-options"})
				
				.addElement({type:'div', attr:{className:'row card-message'}, target:"#CommentCard"})
				.addElement({type:'textarea', attr:{className:'input', rows:"6", name:'card_message', innerHTML:Msg.feedback.card_message, onfocus:"$(this).val('')"}, target:"#CommentCard .card-message"})
				
				.addElement({type:'div', attr:{className:'row customer-service', innerHTML:Msg.feedback.customer_message}, target:"#CommentCard"})
				
				.addElement({type:'td', attr:{className:'right-table-cell', id:'OveralRateCard'}, target:".top-table-row"})
				.addElement({type:'div', attr:{className:'row card-design-options'}, target:"#OveralRateCard"})
				.addElement({type:'div', attr:{className:'options-label fl', innerHTML:Msg.feedback.design}, target:"#OveralRateCard .card-design-options"})
				.addElement({type:'div', attr:{className:'design-options options fr'}, target:"#OveralRateCard .card-design-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'d1', name:'design', value:1}, target:"#OveralRateCard .design-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'d1', innerHTML:"--"}, target:"#OveralRateCard .design-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'d2', name:'design', value:2}, target:"#OveralRateCard .design-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'d2', innerHTML:"-"}, target:"#OveralRateCard .design-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'d3', name:'design', value:3}, target:"#OveralRateCard .design-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'d3', innerHTML:"+-"}, target:"#OveralRateCard .design-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'d4', name:'design', value:4}, target:"#OveralRateCard .design-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'d4', innerHTML:"+"}, target:"#OveralRateCard .design-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'d5', name:'design', value:5}, target:"#OveralRateCard .design-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'d5', innerHTML:"++"}, target:"#OveralRateCard .design-options"})
				
				.addElement({type:'div', attr:{className:'row card-usability-options'}, target:"#OveralRateCard"})
				.addElement({type:'div', attr:{className:'options-label fl', innerHTML:Msg.feedback.usability}, target:"#OveralRateCard .card-usability-options"})
				.addElement({type:'div', attr:{className:'usability-options options fr'}, target:"#OveralRateCard .card-usability-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'u1', name:'usability', value:1}, target:"#OveralRateCard .usability-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'u1', innerHTML:"--"}, target:"#OveralRateCard .usability-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'u2', name:'usability', value:2}, target:"#OveralRateCard .usability-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'u2', innerHTML:"-"}, target:"#OveralRateCard .usability-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'u3', name:'usability', value:3}, target:"#OveralRateCard .usability-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'u3', innerHTML:"+-"}, target:"#OveralRateCard .usability-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'u4', name:'usability', value:4}, target:"#OveralRateCard .usability-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'u4', innerHTML:"+"}, target:"#OveralRateCard .usability-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'u5', name:'usability', value:5}, target:"#OveralRateCard .usability-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'u5', innerHTML:"++"}, target:"#OveralRateCard .usability-options"})
				
				.addElement({type:'div', attr:{className:'row card-overall-options'}, target:"#OveralRateCard"})
				.addElement({type:'div', attr:{className:'options-label fl', innerHTML:Msg.feedback.overall}, target:"#OveralRateCard .card-overall-options"})
				.addElement({type:'div', attr:{className:'overall-options options fr'}, target:"#OveralRateCard .card-overall-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'o1', name:'overall', value:1}, target:"#OveralRateCard .overall-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'o1', innerHTML:"--"}, target:"#OveralRateCard .overall-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'o2', name:'overall', value:2}, target:"#OveralRateCard .overall-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'o2', innerHTML:"-"}, target:"#OveralRateCard .overall-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'o3', name:'overall', value:3}, target:"#OveralRateCard .overall-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'o3', innerHTML:"+-"}, target:"#OveralRateCard .overall-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'o4', name:'overall', value:4}, target:"#OveralRateCard .overall-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'o4', innerHTML:"+"}, target:"#OveralRateCard .overall-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'o5', name:'overall', value:5}, target:"#OveralRateCard .overall-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'o5', innerHTML:"++"}, target:"#OveralRateCard .overall-options"})
				
				.addElement({type:'tr', attr:{className:'bottom-table-header'}, target:"#feedback-form-table"})
				.addElement({type:'td', attr:{className:'table-cell', colspan:2, innerHTML:'<div class="header">'+ Msg.feedback.questions +'</div>'}, target:".bottom-table-header"})
				.addElement({type:'tr', attr:{className:'bottom-table-row'}, target:"#feedback-form-table"})
				.addElement({type:'td', attr:{className:'table-cell', colspan:2, id:'questions'}, target:".bottom-table-row"})
				
				.addElement({type:'div', attr:{className:'row nav'}, target:"#questions"})
				.addElement({type:'div', attr:{className:'options-label fl', innerHTML:Msg.feedback.nav}, target:"#questions .nav"})
				.addElement({type:'div', attr:{className:'nav-options options fr'}, target:"#questions .nav"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'n1', name:'nav', value:1}, target:"#questions .nav-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'n1', innerHTML:"--"}, target:"#questions .nav-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'n2', name:'nav', value:2}, target:"#questions .nav-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'n2', innerHTML:"-"}, target:"#questions .nav-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'n3', name:'nav', value:3}, target:"#questions .nav-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'n3', innerHTML:"+-"}, target:"#questions .nav-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'n4', name:'nav', value:4}, target:"#questions .nav-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'n4', innerHTML:"+"}, target:"#questions .nav-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'n5', name:'nav', value:5}, target:"#questions .nav-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'n5', innerHTML:"++"}, target:"#questions .nav-options"})
				
				.addElement({type:'div', attr:{className:'row recomend'}, target:"#questions"})
				.addElement({type:'div', attr:{className:'options-label fl', innerHTML:Msg.feedback.recomend}, target:"#questions .recomend"})
				.addElement({type:'div', attr:{className:'recomend-options options fr'}, target:"#questions .recomend"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'r1', name:'recomend', value:1}, target:"#questions .recomend-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'r1', innerHTML:"--"}, target:"#questions .recomend-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'r2', name:'recomend', value:2}, target:"#questions .recomend-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'r2', innerHTML:"-"}, target:"#questions .recomend-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'r3', name:'recomend', value:3}, target:"#questions .recomend-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'r3', innerHTML:"+-"}, target:"#questions .recomend-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'r4', name:'recomend', value:4}, target:"#questions .recomend-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'r4', innerHTML:"+"}, target:"#questions .recomend-options"})
				.addElement({type:'input', attr:{type:'radio', className:'radio', id:'r5', name:'recomend', value:5}, target:"#questions .recomend-options"})
				.addElement({type:'label', attr:{className:'label', forItem:'r5', innerHTML:"++"}, target:"#questions .recomend-options"})
				
				.addControl({attr:{id:"cancel", value:Msg.ui.cancel, className:'button white-gradient'}, onClick:function(){ DLG.modals['feedback'].hide(); }})
				.addControl({type:'button', busy:true, attr:{id:"send", className:'button blue-gradient', innerHTML:Msg.ui.send}, onClick:function() {
					$.ajax({
						type: 'POST',
						url: Core.baseUrl +'/feedback/add',
						dataType: 'json',
						data: $('#feedback-form').serialize()
					})
					.done(function(result) {
						if(result.error == 1)
							DLG.modals['feedback'].containers.content.html(result.error_msg).resize();
						else
							DLG.modals['feedback'].hide();
					})
					.fail(function(result) {
						Core.showMsg.show(Msg.ui.request_error);
					});
				}})
				.show()
				.placeCenter();
		});
	},
	
	/**
	 * Create an element from given parameters
	 *
	 * @param type 		string
	 * @param attr 		object
	 * @param parent 	string
	 * @param pos 		string
	 * return jquery node instance
	 */
	ce: function(type, attr, node, pos) {
		var s = '<'+ type;
		
		for(name in attr) {
			var val = attr[name];
			
			if(name == 'className')
				name = 'class';
			if(name == 'forItem')
				name = 'for';
			
			if(name == 'innerHTML' || (name == 'value' && type == 'button') || val == false || val == null)
				continue;
			
			s += ' '+ name +'="'+ val +'"';
		}
		
		if(type == 'input')
			s += '/>';
		else if(attr.value && type == 'button')
			s += '>'+ attr.value +'</'+ type +'>';
		else if(attr.innerHTML)
			s += '>'+ attr.innerHTML +'</'+ type +'>';
		else
			s += '></'+ type +'>';
		
		if(node) {
			if(pos == "after")
				return $(s).insertAfter(node);
			else if(pos == "before")
				return $(s).insertBefore(node);
			else if(pos == "first")
				return $(s).prependTo(node);
			else
				return $(s).appendTo(node);
		}
		else
			return $(s).appendTo("body");
	},
	
	/**
	 * Create a busy button
	 *
	 * @param attr 		object
	 * @param parent 	string
	 * @param pos 		string
	 * return jquery node instance
	 */
	cbb: function(attr, node, pos) {
		var defaults = {
			busyLabel: '',
			label: ''
		};
		
		var attr = $.extend({}, defaults, attr);
		
		if(!attr.id)
			return false;
		
		var s = '';
		
		if(attr.baseClass)
			s = '<span id="'+ attr.id +'" class="controlHolder '+ attr.baseClass +'"><span class="ctrlLabel"';
		else
			s = '<span id="'+ attr.id +'" class="controlHolder"><span class="ctrlIsSteady"';
		
		s += '>'+ attr.label +'</span></span>';
		
		if(node)
		{
			if(pos == "after")
				var btn = $(s).insertAfter(node);
			else if(pos == "before")
				var btn = $(s).insertBefore(node);
			else if(pos == "first")
				var btn = $(s).prependTo(node);
			else
				var btn = $(s).appendTo(node);
		}
		else
			var btn = $(s).appendTo("body");
		
		btn[0].onClickCallback = attr.onClick;
		btn.click(function(e) {
			Core.preventDefault(e);
			Core.stopPropagation(e);
			App.makeBusy($(this), attr.busyLabel, true);
			
			if(this.onClickCallback)
				this.onClickCallback();
		});
		
		return btn;
	},
	
	makeBusy: function(btn, label, b) {
		if(typeof label == "boolean")
		{
			b = label;
			label = "";
		}
		else if(typeof b == "undefined")
			b = false;
		
		if(b) {
			$('.ctrlLabel', btn).hide();
			($('.ctrlBusyIcon', btn).length > 0) ? $('.ctrlBusyIcon', btn).show() : $('<span/>').addClass("ctrlBusyIcon").appendTo(btn).show();
			($('.ctrlBusyLabel', btn).length > 0) ? $('.ctrlBusyLabel', btn).show() : $('<span/>').addClass("ctrlBusyLabel").html(label).appendTo(btn).show();
		}
		else {
			$('.ctrlLabel', btn).show();
			$('.ctrlBusyIcon', btn).hide().remove();
			$('.ctrlBusyLabel', btn).hide().remove();
		}
	},
	
	submitForm: function(options){
		var defaults = {
			url:"#",
			data: null
		};
	
		var options = $.extend({}, defaults, options);
		
		var _ajax = $.post(
			options.url,
			$(options.formId).serialize(),
			function(response) {
				options.callBack(response);
			},
			"json"
		)
		.fail(function() {
			Core.showMsg.show(Msg.global.requestError);
		});
	},
	
	countClick: function(id, type) {
		switch(type) {
			case 0:
				url = Core.baseUrl +"/video/set-click?id=" + id;
				break;
			case 1:
				url = Core.baseUrl +"/set-click?id="+ id +"&type=1";
				break;
			default:
				url = Core.baseUrl +"/set-click?id=" + id;
		}
		
		var xhr = $.ajax({
			type: "GET",
			url: url,
			dataType: "json"
		});
	},
	
	loader: null,
	addLoader: function(node)
	{
		$('<span class="busy-loader-body"><span class="busy-loader"></span></span>').appendTo(node);
	},
	
	removeLoader: function(node)
	{
		$('.busy-loader-body', $(node)).remove();
	}
};

var Validator = {
	
	create: function(fname)
	{
		if(typeof fname == 'string')
		{
			_fobj = document.forms[fname];
			_fname = fname;
		}
		else if(typeof fname.nodeName == 'undefined')
		{
			_fobj = fname[0];
			_fname = fname[0].name;
		}
		else
		{
			_fobj = fname;
			_fname = fname.name;
		}
		
		var validatorObj = {
			_formobj: _fobj,
			_formname: _fname,
			_elements: new Array(),
			_onsubmit: null,
			_old_onsubmit: null,
			_set_focus_onerror: true,
			_set_class_onerror: true,
			_show_errors_together: false,
			
			enableShowMsgsTogether: function()
			{
				this._show_errors_together = true;
			},
			
			disableShowMsgsTogether: function()
			{
				this._show_errors_together = false;
			},
			
			setFocus: function(objInput)
			{
				if (this._set_focus_onerror)
				{
					if (!objInput.disabled && objInput.type != 'hidden')
						objInput.focus();
				}
			},
			
			setError: function(objInput)
			{
				if (this._set_class_onerror)
				{
					if (!objInput.disabled && objInput.type != 'hidden')
					{
						$(objInput).addClass("error");
					}
				}
			},
			
			clearError: function(objInput)
			{
				if (this._set_class_onerror)
				{
					if($(objInput).hasClass("error"))
						$(objInput).removeClass("error");
				}
			},
			
			disableValidations: function()
			{
				if (this._old_onsubmit)
					this._onsubmit = this._old_onsubmit;
				else
					this._onsubmit = null;
			},
			
			formSubmitHandler: function()
			{
				var bRet = true;
				for (var i = 0; i < this._elements.length; i++)
				{
					if (this._elements[i].validationset && !this._elements[i].validationset.validate())
					{
						bRet = false;
					}
					if (!bRet && !this._show_errors_together)
					{
						break;
					}
				}
				
				if (!bRet)
				{
					this.errors.finalShowMsg();
					return false;
				}
				return true;
			},
			
			addValidation: function(itemname, descriptor, errstr)
			{
				var condition = null;
				if (arguments.length > 3)
					condition = arguments[3];
				
				if (!this._formobj)
				{
					console.log("[Validator] Error: The form object is not set properly");
					return;
				}
				
				var itemobj = this._formobj[itemname];
			
				if (itemobj.length && isNaN(itemobj.selectedIndex))
					itemobj = itemobj[0];
				
				if (!itemobj)
				{
					console.log("[Validator] Error: Couldnot get the input object named: " + itemname);
					return;
				}
				
				if (!itemobj.validationset)
				{
					itemobj.validationset = new validatorObj.ValidationSet(itemobj, this._show_errors_together);
				}
				itemobj.validationset.add(descriptor, errstr, condition);
				itemobj.validatorobj = this;
				
				if($.inArray(itemobj, this._elements) < 0)
					this._elements.push(itemobj);
			},
			
			ValidationDesc: function(inputitem, desc, error, condition)
			{
				this.desc = desc;
				this.error = error;
				this.itemobj = inputitem;
				this.condition = condition;
				this.validate = validatorObj.vdescValidate;
			},
			
			vdescValidate: function()
			{
				if (this.condition != null)
				{
					if (!eval(this.condition))
						return true;
				}
				
				if (!validatorObj.validateInput(this.desc, this.itemobj, this.error))
				{
					this.itemobj.validatorobj.focus_disable_validations = true;
					validatorObj.setFocus(this.itemobj);
					validatorObj.setError(this.itemobj);
					return false;
				}
				else
					validatorObj.clearError(this.itemobj);
			
				return true;
			},
			
			ValidationSet: function(inputitem, msgs_together)
			{
				this.vSet = new Array();
				this.add = validatorObj.addValidationDesc;
				this.validate = validatorObj.vsetValidate;
				this.itemobj = inputitem;
				this.msgs_together = msgs_together;
			},
			
			addValidationDesc: function(desc, error, condition)
			{
				this.vSet[this.vSet.length] = new validatorObj.ValidationDesc(this.itemobj, desc, error, condition);
			},
			
			vsetValidate: function()
			{
				var bRet = true;
				for (var itr = 0; itr < this.vSet.length; itr++)
				{
					bRet = bRet && this.vSet[itr].validate();
					if (!bRet && !this.msgs_together)
					{
						break;
					}
				}
				
				return bRet;
			},
			
			showErrorMsg: function(msg, input_elmt)
			{
				this.errors.showMsg(msg, input_elmt);
			},
			
			showFinalErrorMsg: function()
			{
				this.errors.finalShowMsg();
			},
			
			clearErrorMsg: function()
			{
				this.errors.clearMsgs();
			},
			
			errorDisplayHandler: function()
			{
				this.msgdisplay = new validatorObj.MsgDisplayer();
				this.showMsg = validatorObj.edhShowMsg;
				this.finalShowMsg = validatorObj.edhFinalShowMsg;
				this.all_msgs = new Array();
				this.clearMsgs = validatorObj.edhClearMsgs;
			},
			
			edhClearMsgs: function()
			{
				this.msgdisplay.clearMsg(this.all_msgs);
				this.all_msgs = new Array();
			},
			
			edhShowMsg: function(msg, input_element)
			{
				var objmsg = new Array();
				objmsg["input_element"] = input_element;
				objmsg["msg"] = msg;
				this.all_msgs.push(objmsg);
			},
			
			edhFinalShowMsg: function()
			{
				if (this.all_msgs.length == 0)
					return;
				
				this.msgdisplay.showMsg(this.all_msgs);
			},
			
			/*
			 *  Massage Displayer
			 */
			MsgDisplayer: function()
			{
				this.showMsg = validatorObj.showmsg;
				this.clearMsg = validatorObj.clearmsg;
			},
			
			clearmsg: function(msgs)
			{
				for (var m in msgs)
				{
					var div = validatorObj.element(msgs[m]["input_element"]);
					validatorObj.displaymsg(div, "");
				}
			},
			
			element: function(input_element)
			{
				var div = $(input_element).data("replacement") ? $(input_element).data("replacement").siblings('.errors') : $(input_element).siblings('.errors');
				if(div.length < 1)
					var div = $('<div class="errors"></div>').appendTo($(input_element).data("replacement") ? $(input_element).data("replacement").parent() : $(input_element).parent());
			
				return div;
			},
			
			showmsg: function(msgs)
			{
				var whole_msg;
				var first_elmnt = null;
				for (var m in msgs)
				{
					if (null == first_elmnt)
					{
						first_elmnt = msgs[m]["input_element"];
					}
					var div = validatorObj.element(msgs[m]["input_element"]);
					validatorObj.displaymsg(div, msgs[m]["msg"]);
				}
				if (null != first_elmnt)
				{
					validatorObj.setFocus(first_elmnt);
					validatorObj.setError(first_elmnt);
				}
			},
			
			displaymsg: function(div, msgstring)
			{
				if (!div) return false;
				if(msgstring != "")
					div.html(msgstring).show();
				else
					div.html(msgstring).hide();
			},
			
			/*
			 *   validators
			 */
			validateEmail: function(email)
			{
				var splitted = email.match("^(.+)@(.+)$");
				if (splitted == null) return false;
				if (splitted[1] != null)
				{
					var regexp_user = /^\"?[\w-_\.]*\"?$/;
					if (splitted[1].match(regexp_user) == null) return false;
				}
				if (splitted[2] != null)
				{
					var regexp_domain = /^[\w-\.]*\.[A-Za-z]{2,4}$/;
					if (splitted[2].match(regexp_domain) == null)
					{
						var regexp_ip = /^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
						if (splitted[2].match(regexp_ip) == null) return false;
					} // if
					return true;
				}
				return false;
			},
			
			ssListItemSelected: function(listname, value)
			{
				for (var i = 0; i < listname.options.length; i++)
				{
					if (listname.options[i].selected == true && listname.options[i].value == value)
					{
						return true;
					}
				}
				return false;
			},
			
			isChecked: function(objcheck, value)
			{
				if (objcheck.length)
				{
					for (var c = 0; c < objcheck.length; c++)
					{
						if (objcheck[c].checked == "1" && objcheck[c].value == value)
						{
							return true;
						}
					}
				}
				else
				{
					if (objcheck.checked == "1")
					{
						return true;
					}
				}
				return false;
			},
			
			strTrim: function(strIn)
			{
				return strIn.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
			},
			
			isEmpty: function(value)
			{
				value = this.strTrim(value);
				return (value.length) == 0 ? true : false;
			},
			
			TestComparison: function(objValue, strCompareElement, strvalidator, strError)
			{
				var bRet = true;
				var objCompare = null;
				if (!objValue.form)
				{
					this.showErrorMsg("Error: No Form object!", objValue);
					return false;
				}
				objCompare = objValue.form.elements[strCompareElement];
				if (!objCompare)
				{
					this.showErrorMsg("Error: Element with name" + strCompareElement + " not found !", objValue);
					return false;
				}
			
				var objval_value = objValue.value;
				var objcomp_value = objCompare.value;
			
				if (strvalidator != "eqelmnt" && strvalidator != "neelmnt")
				{
					objval_value = objval_value.replace(/\,/g, "");
					objcomp_value = objcomp_value.replace(/\,/g, "");
			
					if(isNaN(objval_value))
					{
						this.showErrorMsg(objValue.name + ": Should be a number ", objValue);
						return false;
					}
					if(isNaN(objcomp_value))
					{
						this.showErrorMsg(objCompare.name + ": Should be a number ", objCompare);
						return false;
					}
				}
				
				var cmpstr = "";
				switch (strvalidator)
				{
					case "eqelmnt":
						if (objval_value != objcomp_value)
						{
							cmpstr = Msg.formErrors.shoudbeEqual;
							bRet = false;
						}
						break;
					case "ltelmnt":
						if (eval(objval_value) >= eval(objcomp_value))
						{
							cmpstr = Msg.formErrors.shoudbeLess;
							bRet = false;
						}
						break;
					case "leelmnt":
						if (eval(objval_value) > eval(objcomp_value))
						{
							cmpstr = Msg.formErrors.shoudbeLessEqual;
							bRet = false;
						}
						break;
					case "gtelmnt":
						if (eval(objval_value) <= eval(objcomp_value))
						{
							cmpstr = Msg.formErrors.shoudbeGreater;
							bRet = false;
						}
						break;
					case "geelmnt":
						if (eval(objval_value) < eval(objcomp_value))
						{
							cmpstr = Msg.formErrors.shoudbeGreaterEqual;
							bRet = false;
						}
						break;
					case "neelmnt":
						if (objval_value.length > 0 && objcomp_value.length > 0 && objval_value == objcomp_value)
						{
							cmpstr = Msg.formErrors.shoudbeDifferent;
							bRet = false;
						}
						break;
				}
				
				if (bRet == false)
				{
					if (!strError || strError.length == 0)
						strError = objValue.name + cmpstr + objCompare.name;
					this.showErrorMsg(strError, objValue);
				}
				return bRet;
			},
			
			TestSelMin: function(objValue, strMinSel, strError)
			{
				var bret = true;
				var objcheck = objValue.form._elements[objValue.name];
				var chkcount = 0;
				if (objcheck.length)
				{
					for (var c = 0; c < objcheck.length; c++)
					{
						if (objcheck[c].checked == "1")
							chkcount++;
					}
				}
				else
					chkcount = (objcheck.checked == "1") ? 1 : 0;
				
				var minsel = eval(strMinSel);
				if (chkcount < minsel)
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.checkAtleast.replace('{field}', objValue.name).replace('{value}', minsel);
					}                                                         
					this.showErrorMsg(strError, objValue);
					bret = false;
				}
				return bret;
			},
			
			TestSelMax: function(objValue, strMaxSel, strError)
			{
				var bret = true;
				var objcheck = objValue.form._elements[objValue.name];
				var chkcount = 0;
				if (objcheck.length)
				{
					for (var c = 0; c < objcheck.length; c++)
					{
						if (objcheck[c].checked == "1")
							chkcount++;
					}
				}
				else
					chkcount = (objcheck.checked == "1") ? 1 : 0;
					
				var maxsel = eval(strMaxSel);
				if (chkcount > maxsel)
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.checkAtmost.replace('{field}', objValue.name).replace('{value}', maxsel);
					}
					this.showErrorMsg(strError, objValue);
					bret = false;
				}
				return bret;
			},
			
			IsCheckSelected: function(objValue, chkValue)
			{
				var selected = false;
				var objcheck = objValue.form._elements[objValue.name];
				if (objcheck.length)
				{
					var idxchk = -1;
					for (var c = 0; c < objcheck.length; c++)
					{
						if (objcheck[c].value == chkValue)
						{
							idxchk = c;
							break;
						}
					}
					if (idxchk >= 0)
					{
						if (objcheck[idxchk].checked == "1")
							selected = true;
					}
				}
				else
				{
					if (objValue.checked == "1")
						selected = true;
				}
				return selected;
			},
			
			TestDontSelectChk: function(objValue, chkValue, strError)
			{
				var pass = true;
				pass = this.IsCheckSelected(objValue, chkValue) ? false : true;
			
				if (pass == false)
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.cantProcced.replace('{field}', objValue.name);
					}
					this.showErrorMsg(strError, objValue);
			
				}
				return pass;
			},
			
			TestShouldSelectChk: function(objValue, chkValue, strError)
			{
				var pass = true;
			
				pass = this.IsCheckSelected(objValue, chkValue) ? true : false;
			
				if (pass == false)
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.shouldSelect.replace('{field}', objValue.name);
					}
					this.showErrorMsg(strError, objValue);
			
				}
				return pass;
			},
			
			TestRequiredInput: function(objValue, strError)
			{
				var ret = true;
				if (this.isEmpty(objValue.value))
					ret = false;
				else if(objValue.getcal && !objValue.getcal())
					ret = false;
				
				if (!ret)
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.requiredField;
					}
					this.showErrorMsg(strError, objValue);
				}
				return ret;
			},
			
			TestFileExtension: function(objValue, cmdvalue, strError)
			{
				var ret = false;
				var found = false;
			
				if (objValue.value.length <= 0)
					return true;
			
				var extns = cmdvalue.split(";");
				for (var i = 0; i < extns.length; i++)
				{
					ext = objValue.value.substr(objValue.value.length - extns[i].length, extns[i].length);
					ext = ext.toLowerCase();
					if (ext == extns[i])
					{
						found = true;
						break;
					}
				}
				if (!found)
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.allowedExt.replace('{field}', objValue.name).replace('{value}', cmdvalue);
					}
					this.showErrorMsg(strError, objValue);
					ret = false;
				}
				else
					ret = true;
				
				return ret;
			},
			
			TestMaxLen: function(objValue, strMaxLen, strError)
			{
				var ret = true;
				if (eval(objValue.value.length) > eval(strMaxLen))
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.maxChars.replace('{field}', objValue.name).replace('{value}', strMaxLen);
					}
					this.showErrorMsg(strError, objValue);
					ret = false;
				}
				return ret;
			},
			
			TestMinLen: function(objValue, strMinLen, strError)
			{
				var ret = true;
				if (eval(objValue.value.length) < eval(strMinLen))
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.minChars.replace('{field}', objValue.name).replace('{value}', strMinLen);
					}
					this.showErrorMsg(strError, objValue);
					ret = false;
				}
				return ret;
			},
			
			TestInputType: function(objValue, strRegExp, strError, strDefaultError)
			{
				var ret = true;
			
				var charpos = objValue.value.search(strRegExp);
				if (objValue.value.length > 0 && charpos >= 0)
				{
					if (!strError || strError.length == 0)
					{
						strError = strDefaultError;
					}
					this.showErrorMsg(strError, objValue);
					ret = false;
				}
				return ret;
			},
			
			TestEmail: function(objValue, strError)
			{
				var ret = true;
				if (objValue.value.length > 0 && !this.validateEmail(objValue.value))
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.validEmail.replace('{field}', objValue.name);
					}
					this.showErrorMsg(strError, objValue);
					ret = false;
				}
				return ret;
			},
			
			TestLessThan: function(objValue, strLessThan, strError)
			{
				var ret = true;
				var obj_value = objValue.value.replace(/\,/g, "");
				strLessThan = strLessThan.replace(/\,/g, "");
			
				if (isNaN(obj_value))
				{
					this.showErrorMsg(Msg.formErrors.shoulbeNumber.replace('{field}', objValue.name), objValue);
					ret = false;
				}
				else if (eval(obj_value) >= eval(strLessThan))
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.lessThan.replace('{field}', objValue.name).replace('{value}', strLessThan);
					}
					this.showErrorMsg(strError, objValue);
					ret = false;
				}
				return ret;
			},
			
			TestGreaterThan: function(objValue, strGreaterThan, strError)
			{
				var ret = true;
				var obj_value = objValue.value.replace(/\,/g, "");
				strGreaterThan = strGreaterThan.replace(/\,/g, "");
			
				if (isNaN(obj_value))
				{
					this.showErrorMsg(Msg.formErrors.shoulbeNumber.replace('{field}', objValue.name), objValue);
					ret = false;
				}
				else if (eval(obj_value) <= eval(strGreaterThan))
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.greaterThan.replace('{field}', objValue.name).replace('{value}', strGreaterThan);
					}
					this.showErrorMsg(strError, objValue);
					ret = false;
				}
				return ret;
			},
			
			TestRegExp: function(objValue, strRegExp, strError)
			{
				var ret = true;
				if (objValue.value.length > 0 && !objValue.value.match(strRegExp))
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.invalidChars.replace('{field}', objValue.name);
					}
					this.showErrorMsg(strError, objValue);
					ret = false;
				}
				return ret;
			},
			
			TestDontSelect: function(objValue, dont_sel_value, strError)
			{
				var ret = true;
				if (objValue.value == null)
				{
					this.showErrorMsg(Msg.formErrors.dontselComm, objValue);
					ret = false;
				}
				else if (objValue.value == dont_sel_value)
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.selectOne.replace('{field}', objValue.name);
					}
					this.showErrorMsg(strError, objValue);
					ret = false;
				}
				return ret;
			},
			
			TestSelectOneRadio: function(objValue, strError)
			{
				var objradio = objValue.form._elements[objValue.name];
				var one_selected = false;
				for (var r = 0; r < objradio.length; r++)
				{
					if (objradio[r].checked == "1")
					{
						one_selected = true;
						break;
					}
				}
				if (false == one_selected)
				{
					if (!strError || strError.length == 0)
					{
						strError = Msg.formErrors.selectOneFrom.replace('{field}', objValue.name);
					}
					this.showErrorMsg(strError, objValue);
				}
				return one_selected;
			},
			
			TestSelectRadio: function(objValue, cmdvalue, strError, testselect)
			{
				var objradio = objValue.form._elements[objValue.name];
				var selected = false;
			
				for (var r = 0; r < objradio.length; r++)
				{
					if (objradio[r].value == cmdvalue && objradio[r].checked == "1")
					{
						selected = true;
						break;
					}
				}
				if (testselect == true && false == selected || testselect == false && true == selected)
				{
					this.showErrorMsg(strError, objValue);
					return false;
				}
				return true;
			},
			
			validateInput: function(strValidateStr, objValue, strError)
			{
				var ret = true;
				var epos = strValidateStr.search("=");
				var command = "";
				var cmdvalue = "";
				if (epos >= 0)
				{
					command = strValidateStr.substring(0, epos);
					cmdvalue = strValidateStr.substr(epos + 1);
				}
				else
					command = strValidateStr;
				
				switch (command)
				{
				case "req":
				case "required":
					{
						ret = this.TestRequiredInput(objValue, strError)
						break;
					}
				case "maxlength":
				case "maxlen":
					{
						ret = this.TestMaxLen(objValue, cmdvalue, strError)
						break;
					}
				case "minlength":
				case "minlen":
					{
						ret = this.TestMinLen(objValue, cmdvalue, strError)
						break;
					}
				case "alnum":
				case "alphanumeric":
					{
						ret = this.TestInputType(objValue, "[^A-Za-zА-Яа-я0-9]", strError, Msg.formErrors.alnumOnly);
						break;
					}
				case "alnum_s":
				case "alphanumeric_space":
					{
						ret = this.TestInputType(objValue, "[^A-Za-zА-Яа-я0-9,\.\\s]", strError, Msg.formErrors.alnumspaceOnly);
						break;
					}
				case "num":
				case "numeric":
				case "dec": 
				case "decimal": 
					{
						if (objValue.value.length > 0 && !objValue.value.match(/^[\-\+]?[\d\,]*\.?[\d]*$/))
						{
							this.showErrorMsg(strError, objValue);
							ret = false;
						}
						break;
					}
				case "num_s":
				case "numeric_s":
				case "dec_s": 
				case "decimal_s": 
					{
						if (objValue.value.length > 0 && !objValue.value.match(/^[\-\+\s]?[\d\,\s]*\.?[\d\s]*$/))
						{
							this.showErrorMsg(strError, objValue);
							ret = false;
						}
						break;
					}
				case "alphabetic":
				case "alpha":
					{
						ret = this.TestInputType(objValue, "[^A-Za-zА-Яа-я]", strError, Msg.formErrors.alphaOnly);
						break;
					}
				case "alphabetic_space":
				case "alpha_s":
					{
						ret = this.TestInputType(objValue, "[^A-Za-zА-Яа-я,\.\\s]", strError, Msg.formErrors.alphaspaceOnly);
						break;
					}
				case "email":
					{
						ret = this.TestEmail(objValue, strError);
						break;
					}
				case "lt":
				case "lessthan":
					{
						ret = this.TestLessThan(objValue, cmdvalue, strError);
						break;
					}
				case "gt":
				case "greaterthan":
					{
						ret = this.TestGreaterThan(objValue, cmdvalue, strError);
						break;
					}
				case "regexp":
					{
						ret = this.TestRegExp(objValue, cmdvalue, strError);
						break;
					}
				case "dontselect":
					{
						ret = this.TestDontSelect(objValue, cmdvalue, strError)
						break;
					}
				case "dontselectchk":
					{
						ret = this.TestDontSelectChk(objValue, cmdvalue, strError)
						break;
					}
				case "shouldselchk":
					{
						ret = this.TestShouldSelectChk(objValue, cmdvalue, strError)
						break;
					}
				case "selmin":
					{
						ret = this.TestSelMin(objValue, cmdvalue, strError);
						break;
					}
				case "selmax":
					{
						ret = this.TestSelMax(objValue, cmdvalue, strError);
						break;
					}
				case "selone_radio":
				case "selone":
					{
						ret = this.TestSelectOneRadio(objValue, strError);
						break;
					}
				case "dontselectradio":
					{
						ret = this.TestSelectRadio(objValue, cmdvalue, strError, false);
						break;
					}
				case "selectradio":
					{
						ret = this.TestSelectRadio(objValue, cmdvalue, strError, true);
						break;
					}
					//Comparisons
				case "eqelmnt":
				case "ltelmnt":
				case "leelmnt":
				case "gtelmnt":
				case "geelmnt":
				case "neelmnt":
					{
						return this.TestComparison(objValue, cmdvalue, command, strError);
						break;
					}
				case "req_file":
					{
						ret = this.TestRequiredInput(objValue, strError);
						break;
					}
				case "file_extn":
					{
						ret = this.TestFileExtension(objValue, cmdvalue, strError);
						break;
					}
			
				}
				return ret;
			}
		}
		
		validatorObj.errors = new validatorObj.errorDisplayHandler();
		validatorObj._formobj.validator = validatorObj;
		validatorObj._formobj.onsubmit = function() {
			return validatorObj.formSubmitHandler();
		}
		return validatorObj;
	}
};

$(function() {
	App.initialize(window, document);
});


A B C D E F G H I J K L M N O P Q R S T U V W X Y Z