var Gami = {
	globals: {
		wallpaper: [
		           {name:'background.png', color:'#fff'},
		           {name:'rich-bg.jpg',color:'#000'},
		           {name:'rich-bg2.jpg',color:'#341F1E'},
		           {name:'u3_gamin.jpg',color:'#000'},
		           {name:'irontlogamin.jpg',color:'#000'},
		           {name:'gami22062009.jpg',color:'#fff'},
		           {name:'blades.jpg',color:'#000'}
		           ],
		wallpaperChange: true,

		//ile ma byc wyswetlanych elementow [maxBig, maxSmall]
		newsCount:{
			news:[6,24],
			short:[7,0],
			preview:[6,24],
			review:[4,14]
		},
		rightVideosPlayIcon:'.play',
		text: {
	        developer: "W tym dziale dowiesz się, kto stoi za tworzeniem danej gry",
	        osoba_z_branży: "W tym dziale dowiesz się kto stoi za poszczególnymi projektami.",
	        producent: "W tym dziale dowiesz się, kto wydaje twoje ulubione gry.",
	        dystrybutor: "W tym dziale dowiesz się, kto dystrybuuje w Polsce największe hiciory"
		},
		forum : {
			linkTabs : false,
			frontPageLink : false,
			linkTopic : false,
			treeView : false
		}
	},


	start: function(){

		/* doklejanie informacji z selecta wyboru platformy do linków sortowania */

		$('#premiereListSelectPlatform').bind('change',function(){
			var mainLink = window.location.href;
			var temp = new Array();
			temp = mainLink.split('/')
			temp[4] = $(this).attr('value');
			window.location = temp.toString().replace(/,/g , "/");
		});


		$('.dashboard-messages').bind('click',function(e){
			Mail.showMessages('/user/msg?folder=INBOX', {width:730,height:433,text:'Poczta'});
			//$('.popup').draggable();
			e.preventDefault();
		});
		$('.report a').bind('click',function(e){
			Mail.showMessages("/report?loc="+document.location, {width:520,height:357,text:'Zgłoś swoje uwagi bądź zauważone błędy'});
			//$('.popup').draggable();
		});

		/* TODO:
		$("#developerPersonGradePanel").bind("click",function(){
			this.blur();
			Gami.switchPanel($(this));
			return false;
		});
		$(".critiqueWhyGood").bind('click',function(){
			this.blur();
			Gami.showCritiquePopup($(this));
			return false;
		})
		*/
		if(Gami.globals.wallpaperAd){
			Gami.setwallpaper(Gami.globals.wallpaperAd[0],Gami.globals.wallpaperAd[1]);
		}
		this.form.inputPrepare();
		this.switchwallpaper();
		this.forbiddenFunctions();
		this.bindSearch();

		//tylko na strone glowna
		if(Gami.globals.homePage){
			if($.cookie('gaminatorUserPreferences') == null || $.cookie('gaminatorUserPreferences') == undefined){
				$.cookie('gaminatorUserPreferences','tapeta:0,tabsy:1-0-0-0,newsynews:4,newsypreview:4,newsyreview:2',{ expires: 365});
			}
			this.preferences.start();
			this.videoTabs.bindVideoTabs();
			this.videoTabs.bindVideoScroll();
			this.videoTabs.bindScreenPages();
			this.countDown();
			this.newsCountNavigate();
			this.topicCountNavigate();
			this.newsTabs.start();
			this.playList.bind();
		}

		// na strony gdzie wystepuje pobieranie tapet
		if(Gami.globals.wallpaperDownload){
			this.wallpapers.resolution();
			this.wallpapers.download();
		}
		// na strony gdzie mozna glosowac ajaxem
		if(Gami.globals.vote){
			this.vote();
		}

		if(Gami.globals.playList){
			this.playList.bind();
		}

		if(typeof Gami.globals.rightNews == "string"){
			this.rightPaneNewsCarousel( Gami.globals.rightNews );
		}
		if(typeof Gami.globals.rightVideos == "string"){
			this.rightPaneVideoCarousel( Gami.globals.rightVideos, Gami.globals.rightVideosPlayIcon );
		}

		if(Gami.globals.gamesCom){
			this.gamesCom();
		}

		if(Gami.globals.premiere){
			this.premiereInform();
		}

		if(Gami.globals.whoiswho){
			this.whoiswho();
		}

		if(Gami.globals.premiereAjax){
			this.premiereAjax();
		}

		if(Gami.globals.updateComments){
			this.updateComments();
		}

		if(Gami.globals.adsReplacer){
			this.adsReplacer();
		}

		if(Gami.globals.updateVoting){
			this.updateVoting();
		}

		if($.browser.msie && $.browser.version =="6.0"){
			this.ie6.hoverEffect();
		}

		if(Gami.globals.headlineText){
			$('.global-search p').text(Gami.globals.text[Gami.globals.headlineText]);
		}

		if(Gami.globals.forum.tabsLink) {
			this.forum.linkTabs();
		}

		if(Gami.globals.forum.frontPageLink) {
			this.forum.frontPageLink();
		}

		if(Gami.globals.forum.linkTopic) {
			this.forum.topic.link();
		}

		if(Gami.globals.forum.treeView) {
			this.forum.topic.tree.link();
		}
		
		
		if(typeof _gameCatalogStatus != "undefined") {
			Gami.catalogInit();
		}
		else if(typeof _quazStatus != "undefined") {
			Gami.quazInit();
			$('.votingContQuaz .voting a').gamiInitVoting();
		}
		else {
			Gami.newsInit();
			$('.post-tree .voting a[rel="voting"]').gamiInitVoting();
		}
		
		
		Gami.adsContShowHide();
		
	},
	
	adsContShowHide:function(){
		var _adRect = document.getElementById("boxerNews");
		if((_adRect != null) && (_adRect != 'null') && (typeof _adRect != undefined)) {
			var _thisAdsRec = $("#boxerNews").find("#adRectangle").html();
			if((_thisAdsRec.length > 0) && ($("#boxerNews").find("#adRectangle > *").length > 0)) {	
				$("#boxerNews").show();
			}
		}
		
		var _thisAdsSky = $(".adsSkyCont #adSkyScraper").html();
		if((_thisAdsSky != null) && (_thisAdsSky != 'null')) {
			if((_thisAdsSky.length > 0) && ($(".adsSkyCont #adSkyScraper > *").length > 0)) {
				$(".adsSkyCont").show();
			}
		}
	},
	
	quazInit:function(){
		var _sectionLinks = $("#askQuaz .section-links a");
		var _showTagsAndFilesConts = $(".showTagsAndFilesConts");
		var _ask = $(".qHead a");
		var _p = $(".popUpNew");
		var _pClose = $(".closePopup");
		var _ansL = $(".actions a");
		var _sbmt = $("#askQuaz .btnsRow input");
		var _moreAns = $("#askQuaz .moreAns");
		var _quazQuastionSelect = $("select.quazQuastionSelect");
		var _inLink = $("#askQuaz").find(".action-include a");
		var _tML	= $("#askQuaz").find(".gameLinks");
		
		Gami.sortLinksBind();
		initLightbox();
		_sectionLinks.unbind().bind("click",function(){
			var _thisUrl = $(this).attr("href");
			var _this = $(this);
			$.post(
				_thisUrl,
				function(msg){
					if(msg.length > 100) {
						msg = msg.split("<div class=\"content\">");
						msg = msg[1].split("<div class=\"endofEnd\">");
						var _tp = _this.parents(".container1");
						_tp.find(".content").html(msg[0]);
						_tp.find(".section-links .selected").removeClass("selected");
						_this.parent().addClass("selected");
						Gami.sortLinksBind();
					}
				}
			);
			return false;
		});
		
		_showTagsAndFilesConts.unbind().bind("click",function(){
			$(".hiddenTag").fadeIn(300);
			$(this).hide();
			return false;
		});
		
		var _cI = false;
		var _gI = false;
		var _tI = false;
		
		$("textarea[name=content]").unbind().bind("click",function(){  if(!_cI) { $(this).attr("value",''); }  _cI = true;   });
		$("input[name=liveG]").unbind().bind("click",function(){   if(!_gI) { $(this).attr("value",''); }   _gI = true;   });
		$("input[name=title]").unbind().bind("click",function(){  if(!_tI) { $(this).attr("value",''); }   _tI = true;  });
		
		_ask.unbind().bind("click",function(){
			var _tUrl = $(this).attr("href");
			var _tPop = $(".popupBox").html();
			
			if(_tPop.length == 0) {
				$.post(
					_tUrl,
					function(msg){
						$(".popupBox").html(msg).find(".recipientsList label").unbind().bind("click",function(e){
							if($(this).hasClass("on")) {
								var _tUID = $(this).attr("for");
								$(".rL").find("."+_tUID).remove();
								$(this).removeClass("on");
							}
							else {
								if($(this).attr("for") == 'user_all') {
									$(".recipientsList input").attr("checked", false);
									$(".recipientsList label.on").removeClass("on");
									$(".chooseRec").text("wszystkim");
									$(".rL").html("");
								}
								else {
									$("#user_all").next().removeClass("on");
									var _rL = $(".rL");
									var _tUID = $(this).parent().find("input").val();
									if(_rL.find(".sRec").length < 5) {
										if(_rL.find("."+_tUID).length == 0) {
											var _tIMG = $(this).find("img").attr("src");
											var _tUN  = $(this).html().split("</span>")[1];
											
											var _nH = '<span class="sRec user_'+_tUID+'">';
											_nH+= '<a class="avatar3" href=""><img src="'+_tIMG+'" alt="avatar" /></a>';
											_nH+= '<a href="/profil/'+_tUID+','+_tUN+'.html" class="uName">'+_tUN+'</a></span>';
											
											_rL.prepend(_nH);
										}
									}
									$(".chooseRec").text("wybierz komu");
								}
								$(this).addClass("on");
							}
						});
						
						$(".popupBox .reset").unbind().bind("click",function(){
							$(".recipientsList input").attr("checked", false);
							$(".recipientsList label.on").removeClass("on");
							return false;
						});
						
						$(".popupBox .ok").unbind().bind("click",function(){
							_p.fadeOut(200);
							return false;
						});
						
						var _newLine = false;
						$(".liveS input").unbind().bind("click",function(){
							if(!_newLine) { $(this).attr("value",''); }
							_newLine = true;
						});
						
						$(".liveS input").bind("keyup",function(event){
							if((event.keyCode != 40) && (event.keyCode != 38) && (event.keyCode != 13)) {
						
								var _tUrl = $(this).parent().find("a").attr("href");//+''
								_tUrl+=$(this).val();
								$.post(
									_tUrl,
									function(msg){
										msg = eval(msg);
										var _lSc = '';
										$(msg).each(function(){
											_lSc+='<div class="sLiveSRes"><a href="'+$(this)[0]+'" rel="'+$(this)[2]+'">'+$(this)[1]+'</a></div>';
										});
										$(".liveSRes").html(_lSc).show();
										Gami.bindLiveSearchResults();
										
										
										$(".liveSRes").attr({ scrollTop: 0 });
										$(document).unbind().bind("keydown",function(event){
											if(event.keyCode == 40) { alert('a');
												if($(".liveSRes").find(".sOn").length == 0){
													$(".liveSRes").find(".sLiveSRes:first").addClass("sOn");
												}
												else {
													$(".sOn").removeClass("sOn").next().addClass("sOn");
													var _newScroll = $(".liveSRes").attr("scrollTop")-(-23);
													$(".liveSRes").attr({ scrollTop: _newScroll });
												}
											}
											if(event.keyCode == 38) {
												if($(".liveSRes").find(".sOn").length == 0){
													$(".liveSRes").find(".sLiveSRes:first").addClass("sOn");
												}
												else {
													$(".sOn").removeClass("sOn").prev().addClass("sOn");
													var _newScroll = $(".liveSRes").attr("scrollTop")-23;
													$(".liveSRes").attr({ scrollTop: _newScroll });
												}
											}
											if((event.keyCode == 13)) {
												var _t = $(".liveSRes").find(".sOn a");
												var _sResLogin 	= _t.text();
												var _sResId		= _t.attr("href");
												if(_t.attr("rel") != 'null'){
													var _sResPic	= _t.attr("rel");
												}
												else var _sResPic	= '/gfx/dummy/dummy_avatar1.gif';
												
												var _newS = '<div class="singleR">';
												_newS+= '	<input type="checkbox" name="recipients" value="'+_sResId+'" checked id="user_'+_sResId+'">';
												_newS+= '	<label for="user_'+_sResId+'" class="on">';
												_newS+= '		<span class="sAvatar3"><img src="'+_sResPic+'"></span>';
												_newS+= _sResLogin+'</label></div>';
												
												$(".liveSRes").hide();
												$(".recipientsList").prepend(_newS);
												$(".liveS input").attr("value",_sResLogin);
												
												$(".recipientsList label").unbind().bind("click",function(e){
													if($(this).hasClass("on")) {
														var _tUID = $(this).attr("for");
														$(".rL").find("."+_tUID).remove();
														$(this).removeClass("on");
													}
													else {
														if($(this).attr("for") == 'user_all') {
															$(".recipientsList input").attr("checked", false);
															$(".recipientsList label.on").removeClass("on");
															$(".chooseRec").text("wszystkim");
															$(".rL").html("");
														}
														else {
															$("#user_all").next().removeClass("on");
															var _rL = $(".rL");
															var _tUID = $(this).parent().find("input").val();
															if(_rL.find(".sRec").length < 5) {
																if(_rL.find("."+_tUID).length == 0) {
																	var _tIMG = $(this).find("img").attr("src");
																	var _tUN  = $(this).html().split("</span>")[1];
																	
																	var _nH = '<span class="sRec user_'+_tUID+'">';
																	_nH+= '<a class="avatar3" href=""><img src="'+_tIMG+'" alt="avatar" /></a>';
																	_nH+= '<a href="/profil/'+_tUID+','+_tUN+'.html" class="uName">'+_tUN+'</a></span>';
																	
																	_rL.prepend(_nH);
																}
															}
															$(".chooseRec").text("wybierz komu");
														}
														$(this).addClass("on");
													}
												});
												return false;
											}
										});
									
										
									}
								);
							}	
						});
						
						
					}
				);
			}
			_p.fadeIn(300);
			return false;
		});
		
		Gami.modApl();
		
		_pClose.unbind().bind("click",function(){
			_p.fadeOut(200);
			return false;
		});
		
		$("input[name=liveG]").bind("keyup",function(event){
			
			if((event.keyCode != 40) && (event.keyCode != 38) && (event.keyCode != 13)) {
				var _this = $(this);
				var _tUrl = $(this).parent().find("a").attr("href").split(',')[0];//+''
				_tUrl+= ','+$(this).val();
				$.post(
					_tUrl,
					function(msg){
						msg = eval(msg);
						var _lGc = '';
						$(msg).each(function(){
							_lGc+='<div class="sLiveSRes"><a href="'+$(this)[0]+'">'+$(this)[1]+'</a></div>';
						});
						$(".liveGRes").attr({ scrollTop: 0 });
						$(document).unbind().bind("keydown",function(event){
							if(event.keyCode == 40) {
								if($(".liveGRes").find(".sOn").length == 0){
									$(".liveGRes").find(".sLiveSRes:first").addClass("sOn");
								}
								else {
									$(".sOn").removeClass("sOn").next().addClass("sOn");
									var _newScroll = $(".liveGRes").attr("scrollTop")-(-23);
									$(".liveGRes").attr({ scrollTop: _newScroll });
								}
							}
							if(event.keyCode == 38) {
								if($(".liveGRes").find(".sOn").length == 0){
									$(".liveGRes").find(".sLiveSRes:first").addClass("sOn");
								}
								else {
									$(".sOn").removeClass("sOn").prev().addClass("sOn");
									var _newScroll = $(".liveGRes").attr("scrollTop")-23;
									$(".liveGRes").attr({ scrollTop: _newScroll });
								}
							}
							if((event.keyCode == 13)) {
								var _t = $(".liveGRes").find(".sOn a");
								var _tId = _t.attr("href");
								$(".gameId").attr("value",_tId);
								_this.attr("value",_t.text());
								$(".liveGRes").hide();
								return false;
							}
						});
						
						
						$(".liveGRes").html(_lGc).show();
						$(".liveGRes a").unbind().bind("click",function(){
							var _tId = $(this).attr("href");
							$(".gameId").attr("value",_tId);
							_this.attr("value",$(this).text());
							$(".liveGRes").hide();
							return false;
						});
					}
				);
			}	
		});
		
		$("input[name=searchAnsLive]").bind("keyup",function(event){
			
			if((event.keyCode != 40) && (event.keyCode != 38) && (event.keyCode != 13)) {
				var _this = $(this);
				var _tUrl = $(this).parent().attr("action").split(',')[0];//+''
				_tUrl+= ','+$(this).val();
				$.post(
					_tUrl,
					function(msg){
						msg = eval(msg);
						var _lGc = '';
						$(msg).each(function(){
							_lGc+='<div class="liveAnsRes"><a href="'+$(this)[3]+'">'+$(this)[2]+'</a></div>';
						});
						$(".liveAns").attr({ scrollTop: 0 });
						$(document).unbind().bind("keydown",function(event){
							if(event.keyCode == 40) {
								if($(".liveAns").find(".sOn").length == 0){
									$(".liveAns").find(".liveAnsRes:first").addClass("sOn");
								}
								else {
									$(".sOn").removeClass("sOn").next().addClass("sOn");
									var _newScroll = $(".liveAns").attr("scrollTop")-(-23);
									$(".liveAns").attr({ scrollTop: _newScroll });
								}
							}
							if(event.keyCode == 38) {
								if($(".liveAns").find(".sOn").length == 0){
									$(".liveAns").find(".liveAnsRes:first").addClass("sOn");
								}
								else {
									$(".sOn").removeClass("sOn").prev().addClass("sOn");
									var _newScroll = $(".liveAns").attr("scrollTop")-23;
									$(".liveAns").attr({ scrollTop: _newScroll });
								}
							}
							if((event.keyCode == 13)) {
								var _t = $(".liveAns").find(".sOn a");
								var _tUrl = _t.attr("href");
								if(_tUrl != undefined) {
									document.location = _tUrl;
								}
								return false;
							}
						});
						
						$(".liveAns").html(_lGc).show();
					}
				);
			}	
		});
		
		
		_sbmt.unbind().bind("click",function(){
			var msg = '';
			$(".qRow .error, .qRow2 .error").remove();
			
			if(($("#title").val() == 'Wpisz minimum 5 znaków') || ($("#title").val() == '')) { 
				var err1 = '<span class="error">Tytuł pytania za krótki, minimum 3 znaków</span>';
				$("#title").parents(".qRow").append(err1);
				msg = '1';
			}
			if(($("textarea[name=content]").val() == 'Tu wpisz pytanie, które chcesz zadać') || ($("textarea[name=content]").val() == '') || ($("textarea[name=content]").val().length < 50)) { 
				var err2 = '<span class="error">Treść pytania za któtka, minimum 50 znaków</span>';
				$("textarea[name=content]").parents(".qRow2").append(err2);
				msg = '1';
			}
/*			
			if((($("#game").val() == 'Tu wpisz nazwę gry') || ($("#game").val() == '')) && (($("input[name=platform]:checked").length == 0) || ($("input[name=platform]").val() == ''))) { 
				var err3 = '<span class="error">Wybierz grę lub platformę której dotyczy pytanie!</span>';
				$("#game").parents(".qRow2").append(err3);
				msg = '1'; 
			}
			if((($("input[name=platform]:checked").length == 0) || ($("input[name=platform]").val() == '')) && (($("#game").val() == 'Tu wpisz nazwę gry') || ($("#game").val() == ''))) {
				var err4 = '<span class="error">Wybierz grę lub platformę której dotyczy pytanie!</span>';
				$(".platformsList").parents(".qRow2").append(err4);
				msg = '1'; 
			}
*/			
			if(msg != '') {
//				alert("Wypełnij poprawnie wszystkie pola!");
				return false;
			}
		});
		
		$(".ansTopic").unbind().bind('click',function(){
//			if($(this).is(":visible")) { $("#post-ans").slideUp(200); }
//			else $("#post-ans").slideDown(200);
			$("#post-ans").slideDown(200);
			return false;
		});
		
		$("#post-ans form").unbind().bind("submit",function(e){
			var _tUrl 	= $(this).attr("action");
			var $this   = $(this);
            $this[0].updateBBCodeAreaFromRichTextArea();
            var _tC 	= $this.find("textarea#content").val();
            
			$.ajax( {
				type: "POST",
				url :_tUrl,
				data: "content="+_tC,
				success:function(msg){
					if(msg == 'too.short') {
						alert("Odpowiedź za krótka!");
					}
					else {
						$("ul.ansList").prepend(msg);
						$("#post-ans").slideUp(200);
						$('a[rel="voting"]').gamiInitVoting();
						Gami.modApl();
					}
				}
			});
			
			e.preventDefault();
			return false;
		});
		
		_moreAns.unbind().bind("click",function(){
			_tUrl = $(this).attr("href");
			
			$.ajax( {
				type: "POST",
				url :_tUrl,
				success:function(msg){
					var _newUrl = msg.split("<a class=\"moreAns\" href=\"");
					
					msg = msg.split("<div class=\"topic-container\">");
					msg = msg[1].split("<div class=\"cl endof\">");
					msg = msg[0];
					
					$("#askQuaz .endof").before(msg);
					if(_newUrl.length == 2) {
						_newUrl = _newUrl[1].split("\">");
						_newUrl = _newUrl[0];
						$("#askQuaz .moreAns").attr("href",_newUrl);
					}
					else $("#askQuaz .moreAns").hide();
				}
			});
			return false;
		});
		
		_quazQuastionSelect.unbind().bind("change",function(){
			var _tUrl = $(this).val();
			document.location = _tUrl; 
		});
		
		_inLink.unbind().bind("click",function(){
			var _t = $(this);
			_tML.addClass("tabAdded");
			Gami.bindSwitchingTabs()
			_t.parents("#forum-unpined-tabs").fadeOut("300");
			var qNo = _t.parents(".master-section-links").find(".selected a").text().split("(")[1].split(")")[0];
			if(_t.attr("href") == '#platforms') {
				_tML.find("#tab2").show().removeClass("selected").find("span").text(qNo);
			}
			else if(_t.attr("href") == '#others') {
				_tML.find("#tab3").show().removeClass("selected").find("span").text(qNo);
			}
			
			var newValue = _tML.find("#tab2").is(":visible")+','+_tML.find("#tab3").is(":visible");
			var date = new Date();
			date.setTime(date.getTime()+(365*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();	
			document.cookie = "openTabs"+"="+newValue+expires+"; path=/";
		});
		
		if($("#askQuaz").find(".tabAdded").length > 0) {
			var _q = $("#askQuaz");
			var qNoP = _q.find(".lastP").find(".master-section-links").find(".selected a").text().split("(")[1].split(")")[0];
			var qNoQ = _q.find(".lastQ").find(".master-section-links").find(".selected a").text().split("(")[1].split(")")[0];
			
			$(".gameLinks").find("#tab2").find("span").text(qNoP);
			$(".gameLinks").find("#tab3").find("span").text(qNoQ);
			Gami.bindSwitchingTabs();
		}
		
		$('a[rel="voting"]').gamiInitVoting();
	},
	
	bindSwitchingTabs:function(){
		var _tabAdded 		= $("#askQuaz .tabAdded");
		var _sectionLinks 	= $("#askQuaz .section-links a");
		var _exTab 			= _tabAdded.find(".action-exclude");
		var _tML	= $("#askQuaz").find(".gameLinks");
		
		_tabAdded.find("a:not(.action-exclude)").unbind().bind("click",function(){
			var _t    = $(this);
			var _tId  = _t.attr("id");
			var _tM   = $(".tabAdded");
			var _tabM = _tM.parent();
			var _this = _tabM.find("."+_tId).find(".tab_1 a");
			var _thisUrl = _this.attr("href");
			var _loader = $('<div class="loadFrame"><span>ładuję</span></div>');
			_t.parent().append(_loader);
			
			$.post(
				_thisUrl,
				function(msg){
					_tM.find(".selected").removeClass("selected");
					_t.parent().addClass("selected");
					_tabM.find(".section-links").hide();
					_tabM.find("."+_tId).show();
					
					if(msg.length > 100) {
						msg = msg.split("<div class=\"content\">");
						msg = msg[1].split("<div class=\"endofEnd\">");
						var _tp = _this.parents(".container1");
						_tp.find(".content").html(msg[0]);
						_tp.find(".section-links .selected").removeClass("selected");
						_this.parent().addClass("selected");
						Gami.sortLinksBind();
						_t.parent().find(".loadFrame").remove();
					}
				}
			);
			
			_sectionLinks.unbind().bind("click",function(){
				var _thisUrl = $(this).attr("href");
				var _this = $(this);
				$.post(
					_thisUrl,
					function(msg){
						if(msg.length > 100) {
							msg = msg.split("<div class=\"content\">");
							msg = msg[1].split("<div class=\"endofEnd\">");
							var _tp = _this.parents(".container1");
							_tp.find(".content").html(msg[0]);
							_tp.find(".section-links .selected").removeClass("selected");
							_this.parent().addClass("selected");
							Gami.sortLinksBind();
						}
					}
				);
				return false;
			});
			
			return false;
		});
		
		_exTab.unbind().bind("click",function(){
			var _tId = $(this).parent().hide().attr("id");
			
			if(_tId == 'tab2') { $("#askQuaz .lastP").fadeIn(300); }
			else if(_tId == 'tab3') { $("#askQuaz .lastQ").fadeIn(300); }
			
			if($(this).parent().hasClass("selected")){
				var _loader = $('<div class="loadFrame"><span>ładuję</span></div>');
				var _t    = $(this);
				var _tM   = $(".tabAdded");
				var _tabM = _tM.parent();
				var _this = _tabM.find(".tabAdd1").find(".tab_1 a");
				var _thisUrl = $(".tabAdd1").find(".tab_1 a").attr("href");
				var _tFirst = $(".gameLinks").find("li:first");
				
				_tFirst.append(_loader).addClass("selected");

				$.post(
					_thisUrl,
					function(msg){
						_tM.find(".selected").removeClass("selected");
						_t.parent().addClass("selected");
						_tabM.find(".section-links").hide();
						
						if(msg.length > 100) {
							msg = msg.split("<div class=\"content\">");
							msg = msg[1].split("<div class=\"endofEnd\">");
							var _tp = _this.parents(".container1");
							_tp.find(".content").html(msg[0]);
							_tp.find(".section-links .selected").removeClass("selected");
							$(".tabAdd1").show().find("li.tab_1").addClass("selected");
							_tFirst.addClass("selected");
							Gami.sortLinksBind();
							_tFirst.find(".loadFrame").remove();
						}
					}
				);
				
			}
			if(_tabAdded.find("li:visible").length == 1) {
				_tabAdded.removeClass("tabAdded");
			}
			
			var newValue = _tML.find("#tab2").is(":visible")+','+_tML.find("#tab3").is(":visible");
			var date = new Date();
			date.setTime(date.getTime()+(365*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();	
			document.cookie = "openTabs"+"="+newValue+expires+"; path=/";
			
			return false;
		});
		
		
	},
	
	modApl:function(){
		var _p = $(".popUpNew");
		$(".moderator-application").unbind().bind("click",function(e){
			var _tUrl = $(this).attr("href");
			var _off = $(this).offset().top-400;
			$.post(
				_tUrl,
				function(msg){
					$(".popUpNew").css({'top':_off+'px'})
					$(".popupBox").html(msg);
					
					$(".popupBox .submit input").unbind().bind("click",function(){
						var _tU = $(this).parents("form:first").attr("action");
						var _tC = $(".popUpNew").find(".reply-text").val();
						var _loc = window.location.href;
						$.post(
							_tU,
							{ content: _tC },
							function(msg){
								msg = msg.split("DOCTYPE");
								if(msg[0] == '<!'){ window.location.href = _loc; }
							}
						);
						return false;
					});
				}
			);
			
			_p.fadeIn(300);
			return false;
		});
	},
	
	bindLiveSearchResults:function(){
		var _sRes = $(".sLiveSRes a");
		
		_sRes.unbind().bind("click",function(){
			var _sResLogin 	= $(this).text();
			var _sResId		= $(this).attr("href");
			if($(this).attr("rel") != 'null'){
				var _sResPic	= $(this).attr("rel");
			}
			else var _sResPic	= '/gfx/dummy/dummy_avatar1.gif';
			
			var _newS = '<div class="singleR">';
			_newS+= '	<input type="checkbox" name="recipients" value="'+_sResId+'" checked id="user_'+_sResId+'">';
			_newS+= '	<label for="user_'+_sResId+'" class="on">';
			_newS+= '		<span class="sAvatar3"><img src="'+_sResPic+'"></span>';
			_newS+= _sResLogin+'</label></div>';
			
			$(".liveSRes").hide();
			$(".recipientsList").prepend(_newS);
			$(".liveS input").attr("value",_sResLogin);
			
			$(".recipientsList label").unbind().bind("click",function(e){
				if($(this).hasClass("on")) {
					var _tUID = $(this).attr("for");
					$(".rL").find("."+_tUID).remove();
					$(this).removeClass("on");
				}
				else {
					if($(this).attr("for") == 'user_all') {
						$(".recipientsList input").attr("checked", false);
						$(".recipientsList label.on").removeClass("on");
						$(".chooseRec").text("wszystkim");
						$(".rL").html("");
					}
					else {
						$("#user_all").next().removeClass("on");
						var _rL = $(".rL");
						var _tUID = $(this).parent().find("input").val();
						if(_rL.find(".sRec").length < 5) {
							if(_rL.find("."+_tUID).length == 0) {
								var _tIMG = $(this).find("img").attr("src");
								var _tUN  = $(this).html().split("</span>")[1];
								
								var _nH = '<span class="sRec user_'+_tUID+'">';
								_nH+= '<a class="avatar3" href=""><img src="'+_tIMG+'" alt="avatar" /></a>';
								_nH+= '<a href="/profil/'+_tUID+','+_tUN+'.html" class="uName">'+_tUN+'</a></span>';
								
								_rL.prepend(_nH);
							}
						}
						$(".chooseRec").text("wybierz komu");
					}
					$(this).addClass("on");
				}
			});
			return false;
		});
		
		
		
	},
	
	sortLinksBind:function(){
		var _sortLinks = $(".caption .sort-up, .caption .sort-down");
		
		_sortLinks.unbind().bind("click",function(){
			var _thisUrl = $(this).attr("href");
			var _this = $(this);
			var _thisClass = $(this).attr("class");
			
			$.post(
				_thisUrl,
				function(msg){
					if(msg.length > 0) {
						msg = msg.split("<div class=\"topic-container\">");
						msg = msg[1].split("<div class=\"endofEnd\">");
						var _tp = _this.parents(".container1");
						_tp.find(".topic-container").html(msg[0]);
						_this.parents(".row").find(".sort-down:visible").hide();
						_this.parents(".row").find(".sort-up").show();
						_this.hide();
						if(_thisClass == 'sort-up') {
							_this.parent().find(".sort-down").show();
						}
						else _this.parent().find(".sort-up").show();
					}
				}
			);
			return false;
		});
	},
	
	catalogInit:function(){
		
		$(".moreCont a").bind("click",function(){
			var _thisUrl = $(this).attr("href");
			var _this = $(this);
			$.post(
				_thisUrl,
				function(msg){
					if(msg.length > 0) {
						msg = msg.split("<div class=\"gameElemBox\">");
						msg = msg[1].split("<div class=\"lastCatElem\"></div>");
						$(".gameElemBox").append(msg[0]);
						
						var newLink = msg[1].split("<div class=\"moreCont\">");;
						newLink = newLink[1].split("\"");
						newLink = newLink[1];
						$(".moreCont a").attr("href",newLink)
					}
				}
			);
			return false;
		});
		
		$(".moreContList a").bind("click",function(){
			var _thisUrl = $(this).attr("href");
			var _this = $(this);
			$.post(
				_thisUrl,
				function(msg){
					if(msg.length > 0) {
						msg = msg.split("<td></td></tr>");
						msg = msg[1].split("</table>");
						$(".catListElemTable tbody").append(msg[0]);
						
						var newLink = msg[1].split("<div class=\"moreContList\">");;
						newLink = newLink[1].split("\"");
						newLink = newLink[1];
						$(".moreContList a").attr("href",newLink)
					}
				}
			);
			return false;
		});

		
		$(".scroll a#scroll").bind("click",function(){
			if($(this).hasClass("hCat")) {
				$("form .form").slideDown();
				$(this).removeClass("hCat");
			}
			else {
				$("form .form").slideUp();
				$(this).addClass("hCat")
			}
			return false;
		});
		
		$("#platformsOpt").bind("click",function(){
			if(!$("#platformsOld").hasClass("vis")) {
				$("#platformsOld").css({'display':'table-row'}).addClass("vis");
			}
			else $("#platformsOld").css({'display':'none'}).removeClass("vis");
			return false;
		});
		
		$(".selectAll").bind("click",function(){
			$(this).parents("tr:first").find("input[type=checkbox]").attr("checked",true);
			return false;
		});
		
		$(".deselectAll").bind("click",function(){
			$(this).parents("tr:first").find("input[type=checkbox]").attr("checked",false);
			return false;
		});
		
		$(".showhide").bind("click",function(){
			if(!$(this).hasClass("hidDiv")) {
				$(this).addClass("hidDiv").parents("tr:first").find("td > div").hide();
			}
			else $(this).removeClass("hidDiv").parents("tr:first").find("td > div").show();
			return false;
		});
		
	},
	
	newsInit:function(){
		
		if(typeof(_waitingShorts) != undefined) {
			if($(".headSubMenu .nav .waitingTab").length > 0){
				$(".headSubMenu .nav .first").removeClass("active");
				$(".headSubMenu .nav .waitingTab").addClass("active");
			}
		}
		
		$(".sortCommentsCont a").bind("click",function(){
			var _thisUrl = $(this).attr("href");
			var _this = $(this);
			$.post(
				_thisUrl,
				function(msg){
					msg = msg.split("<div class=\"comments\" id=\"comment-content\">");
					msg = msg[1].split("<div class=\"newsContEnd\"></div>");
					$("#comment-content").html(msg[0]);
					_this.parent().find("a.active").removeClass("active");
					_this.addClass("active");
					$('a[rel="voting"]').gamiInitVoting();
				}
			);
			return false;
		});
		
		$(".naviNewsTop a").bind("click",function(){
			$(".newsListContainer").addClass("loaderNews");
			
			var _thisUrl = $(this).attr("href");
			$.post(
				_thisUrl,
				function(msg){
					$(".newsListContainer").html(msg);
					Gami.newsInit();
					setTimeout(function(){
						$(".newsListContainer").removeClass("loaderNews");
						initLightbox();
					},300);
				}
			);
			return false;
		});
		
		$(".moreCont a").bind("click",function(){
			var _thisUrl = $(this).attr("href");
			
			$.post(
				_thisUrl,
				function(msg){
					msg = msg.split("<div class=\"listAjaxContainer\">");
					msg = msg[1].split("<span class=\"endOfList\">");
					var newLink = msg[1].split("<div class=\"moreCont\">");;
					newLink = newLink[1].split("\"");
					newLink = newLink[1];
					$(".moreCont a").attr("href",newLink)
					$(".listAjaxContainer").append(msg[0]);
					$('a[rel="voting"]').gamiInitVoting();
				}
			);
			return false;
			
		});
		
		$("#news .rightNewsCont form .button").bind("click",function(){
			var _thisUrl = $(this).parent().attr("action");
			var _content = $(this).parent().find("#comment");
			$(".errorMessagesCommentsAdd").text("");
			
			if($(".dashboard-user .dashboard-login a").html() == null) {
				$(".errorMessagesCommentsAdd").text("Musisz się zalogować");
			}
			else {
				if(_content.val().length < 20){
					$(".errorMessagesCommentsAdd").text("Komentarz zbyt krótki");
				}
				else {
					$.ajax({
					   type: "POST",
					   url: _thisUrl,
					   data: 'content='+ _content.val(),
					   success: function(msg){
					     $(".rightNewsCont #comment-content").prepend(msg);
					     _content.attr("value","");
					     $('a[rel="voting"]').gamiInitVoting();
					   }
					 });
				}
			}
			return false;
		});
		
		$("#shorts .rightNewsCont form .button").bind("click",function(){
			var _thisUrl = $(this).parent().attr("action");
			var _content = $(this).parent().find("#comment");
			var _shortNews = $(this).parent().find("input[name=shortNews]").val();
			$(".errorMessagesCommentsAdd").text("");
			
			if($(".dashboard-user .dashboard-login a").html() == null) {
				$(".errorMessagesCommentsAdd").text("Musisz się zalogować");
			}
			else {
				if(_content.val().length < 20){
					$(".errorMessagesCommentsAdd").text("Komentarz zbyt krótki");
				}
				else {
					$.ajax({
					   type: "POST",
					   url: _thisUrl,
					   data: 'shortNews='+_shortNews+'&content='+ _content.val(),
					   success: function(msg){
					     $(".rightNewsCont #comment-content").prepend(msg);
					     _content.attr("value","");
					     $('a[rel="voting"]').gamiInitVoting();
					     return false;
					   }
					 });
				}
			}
			return false;
		});
		
//		$(".naviNewsTop a").show();
//		$(".verNoJs").hide();
		$(".dateToReplace").css({'visibility':'visible'});
		
		$('a[rel="voting"]').gamiInitVoting();
		
		var _thisDate = $(".shortBtm .added .black").text();
		if(_thisDate.length > 0) {
			$(".shortBtm .added .black").text(calculateDate(_thisDate));
		}
		
//		var _sh = document.getElementById("shorts");
//		var _nw = document.getElementById("news");
//		
//		if(_sh != null || _nw != null) {
//			var _thisAdsSky = $(".adsSkyCont #adSkyScraper").html();
//			if(_thisAdsSky.length > 0) $(".adsSkyCont").show();
//		}
		
		$(".recommendOthers").children('ul').children('li').each(function(){
			var title = document.title;
			var link = document.location.href;//$.URLEncode(document.location.href);	
			
			var _this = $(this);
			var _thisLink = _this.children('a').attr('target', '_blank');
			switch (_this[0].className)
			{
			case 'blip':
				_thisLink.attr('href', 'http://blip.pl/dashboard?body=Polecam: '+title+' '+link);
			break;
			case 'sledzik':
				_thisLink.attr('href', 'http://nasza-klasa.pl/sledzik?shout=Polecam: '+title+' '+link);
			break;
			case 'facebook':				
				_thisLink.attr({'href' : 'http://www.facebook.com/sharer.php?u='+link+'&t='+title, 'name' : 'fb_share'});
				_thisLink.click(function(e){
					window.open(_thisLink.attr('href'),' facebookShare', 'toolbar=0, status=0, width=626, height=436');
					return false;
				});
			break;
			case 'wykop':
				_thisLink.attr('href', 'http://www.wykop.pl/dodaj?url='+link+'&title='+title);
			break;
			case 'mail':
				_this.hide();
			break;
			default:
				_this.hide();
			}
		});
		
	},
	
	
	adsReplacer: function(event) {
		//if(($('#adBillboard').length > 0) && ($('#adBillboardBottom').length > 0) && ($('#adBillboardBottom').find('object').length > 0)) {
		if(($('#adBillboard').length > 0) && ($('#adBillboardBottom').length > 0)) {
			var $newBanner = $($('#adBillboardBottom').find('script').remove().end().html());
			var $adBillboard = $('#adBillboard');
			
			if((parseInt($newBanner.find('object').attr('height'),10) > 101) || (parseInt($newBanner.find('embed').attr('height'),10) > 101) || (parseInt($newBanner.find('img').attr('height'),10) > 101)) {
				var $body = $('body');
				$body.prepend($('<div style="background: url(/css/newHome/i/masthead-bg.png) repeat-x 0 0; height: 100px;"></div>'));
				$adBillboard.css('margin', '-90px 0 0 0');
				if($body.attr('id') == 'mainPageBody') {
					$body.css('background', 'url(/gfx/site_wallpaper/dzien_gamin.jpg) no-repeat 50% 220px');
				}
			}
			$adBillboard.html($newBanner);
			$('#adBillboardBottom').remove();
		}

		if(($('#adRectangle').length > 0) && ($('#adRectangleBottom').length > 0)) {
		//if(($('#adRectangle').length > 0) && ($('#adRectangleBottom').length > 0) && ($('#adRectangleBottom').find('object').length > 0)) {
			var $newBanner = $('#adRectangleBottom').find('script').remove().end().html();
			$('#adRectangle').append($newBanner);
			$('#adRectangleBottom').remove();
		}
		
		if(($('#adSkyScraper').length > 0) && ($('#adSkyScraperBottom').length >0)) {
		//if(($('#adSkyScraper').length > 0) && ($('#adSkyScraperBottom').length >0) && ($('#adSkyScraperBottom').find('object').length > 0)) {
			var $newBanner = $('#adSkyScraperBottom').find('script').remove().end().html();
			if($('#adSkyScraper').find('.lastFeaturedPane').length > 0) $('#adSkyScraper').find('.lastFeaturedPane').append($newBanner);
			else $('#adSkyScraper').append($newBanner);
			$('#adSkyScraperBottom').remove();
		}
	},

	switchPanel: function(link){
		if($("#addEditBox").css('display') == 'none'){
			$("#addEditBox").css('display','block');
			$(".developerPersonTitle").css({'width':'500px','border-right':'solid 1px #FFF'});
			link.append("<span>zwiń</span>");

		}else{
			$("#addEditBox").css('display','none');
			$(".developerPersonTitle").css({'width':'auto','border-right':'none'});
			link.find("span").remove();
		}
	},

	hideShaddow: function(){
		$(".popupShaddow").css('display','none');
	},

	gamesCom: function(){
		var $gamesComNews = $('#gamesComNews'),
			$gamesComPreview = $('#gamesComPreview'),
			$gamesComNewsLink = $('#gamesComNewsLink'),
			$gamesComPreviewLink = $('#gamesComPreviewLink');

		$gamesComPreview.hide();

		$gamesComNewsLink.click(function(e) {
			e.preventDefault();
			$gamesComPreviewLink.removeClass('link');
			$(this).addClass('link');
			$gamesComPreview.hide();
			$gamesComNews.show();
		});

		$gamesComPreviewLink.click(function(e) {
			e.preventDefault();
			$gamesComNewsLink.removeClass('link');
			$(this).addClass('link');
			$gamesComNews.hide();
			$gamesComPreview.show();
		})

	},

	showCritiquePopup: function(link){

		var $divContainer = link.find(".critiquePopup");
		$divContainer.css('display','block');
		var $divContainerClose = $divContainer.find(".critiquePopupClose");
		$divContainerClose.bind('click',function(){
			$divContainer.hide('fast');
		})
	},
	//cookie functions
	//stringi postaci "jeden:1,dwa:2,trzy:3"
	fromStringToHash: function(str){
		var hash = {};
		if(str != null){
			str = str.split(',');
			jQuery.each(str, function(){
				var arr = this.split(':');
				hash[arr[0]] = arr[1];
			});
		}
		return hash;
	},

	//
	fromHashToString: function(hash){
		var string = '';
		jQuery.each(hash,function(i){
			string += i + ':' + this + ',';
		});
		return string
	},
	setCookieValue: function(cookieName, key, val){
		var value = $.cookie(cookieName);
		value = Gami.fromStringToHash(value);
		value[key] = val;
		value = Gami.fromHashToString(value);
		$.cookie(cookieName,value,{expires: 365});
	},
	getCookieValue: function(cookieName, key){
		var value = $.cookie(cookieName);
		value = Gami.fromStringToHash(value);
		return value[key];
	},
	//end of cookie functions

	createElem: function(data_string){
		//zabezpieczenie dla ie, ktore zawiesza sie na tworzeniu elementu jQuery z dlugiego stringa
		if($.browser.msie){
			var div = document.createElement("div");
			div.innerHTML = data_string;
			var $data = $(div).children();
		}else{
			var $data = $(data_string);
		}
		return $data;
	},

	insertElem: function(data_string, parent_id){
		//funkcja do podmiany dużych fragmentów html'a
		//dziala duzo szybciej niz zastosowanie jQuery
		//wymaga uzywania obiektow w ktorych data string tworzy jeden element DOM
		//jest on wstawiany do elementu o id = parent_id
      	var obj = document.getElementById(parent_id);
      	while(obj.firstChild!=null){
      	    obj.removeChild(obj.firstChild);
      	}
		var div = document.createElement("div");
		div.innerHTML = data_string;
		var inner = div.firstChild;
		obj.innerHTML=inner.innerHTML;
	},

	forbiddenFunctions: function(){
		$('a[rel="haveToLogIn"]').bind('click',function(e){
			var $this = $(this);
			var $loader = $('<div class="loader">Musisz się zalogować zby skorzystać z tej funkcji</div>');
			$this.css('position','relative').append($loader);
			setTimeout(function() {
				$loader.remove();
				$this.css('position','static');
			},1000);
			e.preventDefault();
		});
	},

	bindSearch: function(){
		$('#message-search input.text').bind('click', function(){
			$(this).attr('value','').removeClass('default');
		})
			.bind('blur', function(){
			if($(this).attr('value') == ''){
				$(this).attr('value','Wpisz szukaną frazę').addClass('default');
			}
		});
	},

	vote: function(){
		//onload
		$('a[rel="voting"]').gamiInitVoting();
	},

	preferences:{
		start: function(){
			this.preparePage();
			//this.bindEditActions();
		},

		preparePage: function(){
			var pref = $.cookie('gaminatorUserPreferences');
			pref = Gami.fromStringToHash(pref);

			//ustawienie tapety
			if(
					typeof (Gami.globals.wallpaperChange) != "undefined" && Gami.globals.wallpaperChange == true
					&& typeof (Gami.globals.wallpaper) == "object" && Gami.globals.wallpaper != null
					&& typeof (pref) == "object" && pref != null && typeof (pref['tapeta']) == "string"
					&& typeof (Gami.globals.wallpaper[ pref['tapeta'] ]) == "string"
			){
				var bg = Gami.globals.wallpaper[ pref['tapeta'] ];
				if( bg != ''){
					$('body').css({backgroundImage: 'url(/gfx/site_wallpaper/' + bg.name + ')',backgroundColor: bg.color});
					if(pref['tapeta'] != '0'){
						$('#main').css({backgroundColor:'#fff',padding:'10px'});
					}
					else{
						$('#main').css({backgroundColor:'transparent',padding:' 1px 10px'});
					}
					$('.skin-select option[value='+pref["tapeta"]+']').attr('selected','selected');
				}
			}

			//ustawienie news-tabsów
			if(typeof pref == "object" && pref != null && typeof pref.tabsy =='string'){
				var tabs = pref['tabsy'].split('-');
				if(tabs[1] > 0){$('#shortBox').hide();}
				if(tabs[2] > 0){$('#previewBox').hide();}
				if(tabs[3] > 0){$('#reviewBox').hide();}
				$('#text ul.master-section-links li').each(function(i){
					if( tabs[i] == 2 && i!=0){
						Gami.newsTabs.openTab($(this).find('a[target]'));
					}
					else if(tabs[i] == 0){
						$(this).addClass('hidden');
					}
				});

				//ustawienie ilosci newsow
				Gami.newsTabs.showCookieNews();

				//ukrycie dodatkowych elementow w zapowiedziach i recenzjach
				if($('#previewBox:visible').length == 0 || $('#reviewBox:visible').length == 0){
					$('#previewBox div, #reviewBox div').removeClass('hidden');
				}
				if($('#previewBox:visible, #reviewBox:visible').length == 0){
					$('#hall-of-fame').addClass('long');
				}
			}
		}


		//obecnie nieuztwane-> patrz TODO: edytowanie preferencji
		/*
		bindEditActions: function(){
			function serialize($elem){
				var str = '';
				$elem.find('input').each(function(i){
					str += $(this).attr('checked');
					if(i < $elem.find('input').length -1){		str += '-';}
				});
				return str;
			}

			$('.edit-box a.edit').bind('click',function(e){
				$(this).nextAll('div.edit-panel').show();
				e.preventDefault();
			});
			$('.edit-box a.edit img').bind('mouseover',function(e){
				var src = $(this).attr('src').split('.');
				$(this).attr('src',src[0]+'_hover.'+src[1]);
			});
			$('.edit-box a.edit img').bind('mouseleave',function(e){
				var src = $(this).attr('src').split('.');
				var a = src[0].split('_');
				src[0] = a[0];
				$(this).attr('src',src[0]+'.'+src[1]);
			});
			$('.edit-box a.skip').bind('click',function(e){
				$(this).parents('div.edit-panel').hide();
				e.preventDefault();
			});
			$('.edit-box a.accept').bind('click',function(e){
				var $parent = $(this).parents('div.edit-panel')
				var str = serialize($parent);
				Gami.setCookieValue('gaminatorUserPreferences', $parent.attr('id'), str)
				$(this).parents('div.edit-panel').hide();
				e.preventDefault();
			});
		}
		*/
	},



	videoTabs:{
		bindVideoTabs: function(){
			$('#media .section-links li a').bind('click',function(e){
				var $loader = $('<div class="loader-splash">ładuję...</div>');
				var $parent = $(this);
				$parent.css('position','relative').append($loader);
				$.ajax({
					url: $(this).attr('target'),
					type:'get',
					success: function(data) {
						$parent.parents('ul').find('li').removeClass('selected');
						$parent.parent('li').addClass('selected');

						var $data = Gami.createElem(data);

						$('.media-video').html($data.find('.media-video').html());
						$('#video-thumbs').replaceWith($data.find('#video-thumbs'));
						Gami.videoTabs.videoScrollClear();
						Gami.playList.bind();
						Gami.vote();
						$loader.remove();
						$parent.css('position','static');
						//performGemiusHit('bPblRELX0eQcjc2qqbGZWXXW7Op11t.Ss60.s9zUBl3.07');
					}
				});
				e.preventDefault();
			});
			$('#media .master-section-links li a[target]').bind('click',function(e){
				var $loader = $('<div class="loader-splash">ładuję...</div>');
				$this = $(this)
				$this.css('position','relative').append($loader);

				$.ajax({
					url: $this.attr('target'),
					type:'get',
					success: function(data) {
						Gami.insertElem(data,'media');
						$loader.remove();
						$this.css('position','static');
						Gami.videoTabs.bindVideoTabs();
						Gami.videoTabs.bindVideoScroll();
						Gami.videoTabs.bindScreenPages();
						Gami.playList.bind();
					}
				});
				e.preventDefault();
			});
		},

		bindVideoScroll: function(){
			var elemWidth = 102;
			var counter = 0, visible = 4;

			$('.media-browser li.next a').bind('click',function(e){
				$('.media-browser li.prev').removeClass('op');
				if(counter != $('#video-thumbs ul li').length - visible){
					var left = parseInt($('#video-thumbs ul').css('left').split('x')[0]);
					$('#video-thumbs ul').animate({left:(left-elemWidth)+ 'px'});

					counter  = counter + 1;
					if(counter == $('#video-thumbs ul li').length - visible){
						$(this).parent().addClass('op');
					}
				}
				e.preventDefault();
			});
			$('.media-browser li.prev a').bind('click',function(e){
				if(counter != 0){
					$('.media-browser li.next').removeClass('op');
					var left = parseInt($('#video-thumbs ul').css('left').split('x')[0]);
					$('#video-thumbs ul').animate({left:(left+elemWidth)+ 'px'});

					counter  = counter - 1;
					if(counter == 0){
						$(this).parent().addClass('op');
					}
				}

				e.preventDefault();
			});
		},

		videoScrollClear: function(){
			//resetowanie nawigacji
			$('.thumb-nav .prev').addClass('op');
			$('.thumb-nav .next').removeClass('op');
			$('.media-browser li.prev a, .media-browser li.next a').unbind();
			Gami.videoTabs.bindVideoScroll();
		},

		bindScreenPages: function(){
			$('a[rel="screenPreview"]').bind('click', function(e){
				$parent = $(this).parents('.screenBox');

				$.ajax({
					url: $(this).attr('target'),
					type:'get',
					success: function(data) {
						$parent.html($(data).find('.screenBox'));
						Gami.videoTabs.bindScreenPages();
					}
				});
				e.preventDefault();
			});
		}
	},

	newsTabs: {
		start: function(){
			this.bindTabs();
			this.addBoxToTabs();
			this.removeBoxFromTabs();
		},

		//$elem to link do danej zakladki, gdzie ajaxowy url przechowywany jest w 'target'
		openTab: function($elem){
			var $loader = $('<div class="loader-splash">ładuję...</div>');
			$elem.css('position','relative').append($loader);

			var target = $elem.attr('target');
			$.ajax({
				url: target,
				type:'get',
				success: function(data) {
					//poprzednie ustawienie zakladek
					var tabs = Gami.newsTabs.getTabsConfigure().split('-');

					//podmiana contentu(razem z zakladkami)
					Gami.insertElem(data, 'text')

					//nowe ustawienie zakladek
					var $links = $('#text .master-section-links li');
					$links.removeClass('hidden').each(function(i){
						if(tabs[i] == 0 && !$(this).hasClass('selected')){
							$(this).addClass('hidden');
						}
					});

					Gami.newsTabs.showCookieNews();

					$loader.remove();
					$elem.css('position','relative')

					//podlaczenie akcji pod przyciski w nowej zawartosci boxa
					Gami.newsTabs.removeBoxFromTabs();
					Gami.newsTabs.bindTabs();
					Gami.newsCountNavigate();

					//zapisanie zmian do cookie
					tabs = Gami.newsTabs.getTabsConfigure();
					Gami.setCookieValue('gaminatorUserPreferences', 'tabsy', tabs);
				}
			});
		},


		bindTabs: function(){
			$('#shortBox .section-links li a').bind('click',function(e){
				var $loader = $('<div class="loader-splash">ładuję...</div>');
				var $parent = $(this);
				$parent.css('position','relative').append($loader);

				$.ajax({
					url: this.href,
					type:'get',
					data:'&ieSucks=' + new Date().getTime(),
					success: function(data) {
						$parent.parents('ul').find('li').removeClass('selected');
						$parent.parent('li').addClass('selected');

						var $data = Gami.createElem(data).find('div.independent');
						$('#shortBox div.independent').html($data.html());
						//performGemiusHit('bPblRELX0eQcjc2qqbGZWXXW7Op11t.Ss60.s9zUBl3.07');
						$loader.remove();
						$parent.css('position','static');
					}
				});
				e.preventDefault();
			});
			$('#text .master-section-links li[class!="selected"] a[target]').bind('click',function(e){
				Gami.newsTabs.openTab($(this));
				e.preventDefault();
			});
		},

		getTabsConfigure: function(){
			var tabs = '';
			$('#text ul.master-section-links > li[class!="edit-box"]').each(function(i){
				if($(this).hasClass('hidden')) {							tabs += '0';	}
				else if($(this).hasClass('selected')) {						tabs += '2';	}
				else {														tabs += '1';	}
				if(i < $('#text ul.master-section-links > li[class!="edit-box"]').length - 1){	tabs += '-';	}
			});
			return tabs;
		},

		addBoxToTabs: function(){
			$('.action-include a').bind('click',function(e){
				var target = $(this).attr('target');
				//ALBO otworzenie odpowiedniej zakladki
				Gami.newsTabs.openTab($('.master-section-links a[target="'+target+'"]'));

				//ALBO tytlko dodanie do zakladek
				//$('.master-section-links a[target="'+target+'"]').parent().removeClass('hidden');
				//tabs = Gami.newsTabs.getTabsConfigure();
				//Gami.setCookieValue('gaminatorUserPreferences', 'tabsy', tabs);

				//ukrycie duzego boxu
				var $clickedBox = $(this).parents('div:first');
				$clickedBox.hide();
				var id = $clickedBox.attr('id');

				//wyswietlenie dodatkowych elementow w zapowiedziach i recenzjach
				if(id=="previewBox" || id=="reviewBox"){
					$('#previewBox div, #reviewBox div').removeClass('hidden');
				}
				if($('#previewBox:visible, #reviewBox:visible').length == 0){
					$('#hall-of-fame').addClass('long');
				}
				scroll(0, 419);
				e.preventDefault();
			})
		},
		removeBoxFromTabs: function(){
			$('a.action-exclude').bind('click',function(e){
				var target = $(this).parent().addClass('hidden').find('a:first').attr('target');
				//pokazanie duzego boxu
				var $a = $('.action-include a[target="'+target+'"]');
				$a.parents('div:first').show();
				//otworzenie zakladki news jeżeli zamykano aktywn zakladke
				if($(this).parent().hasClass('selected')){
					Gami.newsTabs.openTab($('#text .master-section-links a[target]:first'));
				}
				else{
					var tabs = Gami.newsTabs.getTabsConfigure();
					Gami.setCookieValue('gaminatorUserPreferences', 'tabsy', tabs);
				}
				//ukrycie dodatkowych elementow w zapowiedziach i recenzjach
				if($('#previewBox:visible').length > 0 && $('#reviewBox:visible').length >0){

					$('#previewBox .primary:last,#previewBox .secondary:last').addClass('hidden');
					$('#reviewBox .primary:last,#reviewBox .secondary:last, #reviewBox .tertiary:last').addClass('hidden');
				}
				if($('#previewBox:visible, #reviewBox:visible').length != 0){
					$('#hall-of-fame').removeClass('long');
				}
				$('.loader-splash').hide();
				e.preventDefault();
			});
		},

		showCookieNews: function(){
			var pref = $.cookie('gaminatorUserPreferences');
			pref = Gami.fromStringToHash(pref);
			var type = $('.news-nav').attr('id')
			if(type != undefined){
				type = type.split('-')[0];
				var maxlen = Gami.globals.newsCount[type][1];
				var nr = pref['newsy'+type];

				var top = maxlen - 3*parseInt(nr) +4;
				$('.items-platform-text-author div.item').each(function(i){
					if(i >= nr){
						$(this).addClass('hidden');
					}
					else{
						$(this).removeClass('hidden');
					}
				});
				$('#text ul.item-titles li').each(function(i){
					if(i < nr || i >= top){
						$(this).addClass('hidden');
					}
					else{
						$(this).removeClass('hidden');
					}
				});
			}
		}
	},

	setwallpaper: function(name,bg){
		$('body').css({backgroundImage: 'url(/gfx/site_wallpaper/' + name + ')',backgroundColor: bg});
		$('#main').css({backgroundColor:'#fff',padding:'10px'});
		$('.skin-select select').attr('disabled','true');
		Gami.globals.wallpaperChange = false;
	},

	switchwallpaper: function(){
		$('.skin-select select').bind('change',function(){
			var bgNr = $('.skin-select select option:selected').attr('value');
			var bgStr = Gami.globals.wallpaper[bgNr];
			$('body').css({backgroundImage: 'url(/gfx/site_wallpaper/' + bgStr.name + ')',backgroundColor: bgStr.color});
			if(bgNr != 0){
				$('#main').css({backgroundColor:'#fff',padding:'10px'});
			}
			else{
				$('#main').css({backgroundColor:'transparent',padding:' 1px 10px'});
			}
			Gami.setCookieValue('gaminatorUserPreferences', 'tapeta', bgNr);
		});

	},

	countDown: function(){
		var limit = $('.featured-contest .counter .time').text().split(' ');
		var date = limit[0].split('-');
		var time = limit[1].split(':');

		var d = new Date();

		d.setYear(date[0]);
		d.setMonth(date[1]-1);
		d.setDate(date[2]);
		d.setHours(time[0]);
		d.setMinutes(time[1]);
		d.setSeconds(time[2]);

		$('.featured-contest .counter').append('<div id="count"></div>');

		$('#count').countdown({until: d});
	},

	newsCountNavigate: function(){
		$('.news-nav a.plus').bind('click',function(e){
			var len =  $('#text .item:visible').length;
			var type = $(this).parent('.news-nav').attr('id').split('-')[0];
			var maxlen = Gami.globals.newsCount[type][0];

			if(len < maxlen){
				$('#text .item').eq(len).removeClass('hidden');
				$('#text .independent .item-titles li').eq(len).addClass('hidden');
				$('#text .independent .item-titles li:visible:last').addClass('hidden')
														.prev().addClass('hidden')
														.prev().addClass('hidden');
				Gami.setCookieValue('gaminatorUserPreferences','newsy'+type,$('.items-platform-text-author div.item:visible').length);
			}
			e.preventDefault();
		});
		$('.news-nav a.minus').bind('click',function(e){
			var len =  $('#text .item:visible').length;
			var type = $(this).parent('.news-nav').attr('id').split('-')[0];
			if(len > 1){
				$('#text .item').eq(len-1).addClass('hidden');
				$('#text .independent .item-titles li:visible:first').prev().removeClass('hidden');
				$('#text .independent .item-titles li:visible:last').next().removeClass('hidden')
													   .next().removeClass('hidden')
													   .next().removeClass('hidden');
				Gami.setCookieValue('gaminatorUserPreferences','newsy'+type,$('.items-platform-text-author div.item:visible').length);
			}
			e.preventDefault();
		});
		$('.news-nav a img').bind('mouseover',function(e){
			var src = $(this).attr('src').split('.');
			var begin = '';
			for( i=0; i<src.length-1; i++){
				if(i!=0){begin = begin + '.';}
				begin +=src[i];
			}

			$(this).attr('src',begin+'-hover.'+src[src.length -1]);
		});
		$('.news-nav a img').bind('mouseleave',function(e){
			var src = $(this).attr('src').split('.');
			var a = src[src.length-2].split('-');

			var begin = '';
			for( i=0; i<src.length-2; i++){
				if(i!=0){begin = begin + '.';}
				begin +=src[i];
			}
			if(begin != ''){
				src[0] = begin+'.'+a[0];
			}
			else{
				src[0] = a[0];
			}
			$(this).attr('src',src[0]+'.'+src[src.length-1]);
		});
	},

	topicCountNavigate: function(){
		$('.topic-nav a.plus').bind('click',function(e){
			var $parent = $(this).parents('.count-nav');

			if($parent.find('.item:visible').length < $parent.find('.item').length){
				$parent.find('.item:hidden:first').show();
			}
			e.preventDefault();
		});
		$('.topic-nav a.minus').bind('click',function(e){
			var $parent = $(this).parents('.count-nav');

			if($parent.find('.item:visible').length > 1){
				$parent.find('.item:visible:last').hide();
			}

			e.preventDefault();
		});
		$('.topic-nav a img').bind('mouseover',function(e){
			var src = $(this).attr('src').split('.');
			$(this).attr('src',src[0]+'-hover.'+src[1]);
		});
		$('.topic-nav a img').bind('mouseleave',function(e){
			var src = $(this).attr('src').split('.');
			var a = src[0].split('-');
			src[0] = a[0];
			$(this).attr('src',src[0]+'.'+src[1]);
		});
	},


	form: {
		inputPrepare: function(){
			$('#loginForm input.input1').bind('focus',function(){
				if($(this).attr('value')== 'Wpisz nick name:' || $(this).attr('value')== 'Wpisz hasło:'){
					$(this).attr('value','');
				}
			});

		}
	},

	playList:{
		bind: function(){
			$('a[rel="playlist"]').bind('click',function(e){
				var $this = $(this);
				var $loader = $('<div class="loader"></div>');
				$this.css('position','relative').append($loader);

				$.ajax({
					url: $this.attr('target'),
					type:'GET',
					success: function(data) {
						$loader.html(data);
						setTimeout(function() {
							$this.parent().find('.effect').show();
							$this.remove();
							$('.loader').remove();
						},1000);
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						alert('Error occured: ' + errorThrown);
					}
				});
				e.preventDefault();
			});
		}
	},
	rightPaneCarouselOptions: {
		zoomFactor:0.5,
		archFactor:0,
		verticalAlign:'bottom',
		showElements:3,
		stepDistance:'auto',
		loop:false,
		startIndex:2,
		reflect: {
			opacity: 0.55,
			height: 0.55
		},
		innerMargins:{
			top:3,
			left:1,
			right:1,
			bottom: 35
		},
		duration:700
	},
	rightPaneVideoCarousel: function(selector, playIconSelector){
		var cNode = $(selector);
		var playIcon = cNode.find(playIconSelector);

		cNode
		 	.removeClass('carouselLoading')
			.carouselWithCaptionAndMenu(this.rightPaneCarouselOptions)
			.bind('carouselAnimationComplete',function(e){
				if(
					typeof e.carouselCurrentElement == "object" &&
					e.carouselCurrentElement != null &&
					e.carouselCurrentElement instanceof $ &&
					e.carouselCurrentElement.find('.carousel-image-box').length == 1
				)
				{
					playIcon.appendTo( e.carouselCurrentElement.find('.carousel-image-box') ).show();
				}

			})
			.bind('carouselAnimationStart',function(e){
				playIcon.remove();
			})
			.find('.carousel-menu-box a[href$=prev]:first')
				.addClass('prev')
				.end()
			.find('.carousel-menu-box a[href$=next]:first')
				.addClass('next');

	},
	rightPaneNewsCarousel: function(selector){
		$(selector)
			.removeClass('carouselLoading')
			.carouselWithCaptionAndMenu( $.extend(true,{},this.rightPaneCarouselOptions,{innerMargins:{bottom: 80}}) )
			.find('.carousel-menu-box a[href$=prev]')
				.addClass('prev')
				.end()
			.find('.carousel-menu-box a[href$=next]')
				.addClass('next');
	},
	rightPaneNav: function(elem){
			$(elem+' li a').bind('click', function(e){
				if($(this).text() != ''){
					$(elem +' .item').hide();
					$(elem +' li a').removeClass('on');
					$(elem +' .item').eq($(this).text()-1).show();
					$(this).addClass('on');
				}
				else if($(this).hasClass('cLeft')){
					if($(elem+' .item:first:visible').length == 0){
						$(elem+' .item:visible').hide().prev().show();
						$(elem+' li a.on').removeClass('on').parent().prev().find('a').addClass('on');
					}
					else{
						$(elem+' .item:visible').hide();
						$(elem+' .item:last').show();
						$(elem+' li a.on').removeClass('on');
						$(elem+' li a:last').parent().prev().find('a').addClass('on');
					}
				}
				else if($(this).hasClass('cRight')){
					if($(elem+' .item:last:visible').length == 0){
						$(elem+' .item:visible').hide().next().show();
						$(elem+' li a.on').removeClass('on').parent().next().find('a').addClass('on');
					}
					else{
						$(elem+' .item:visible').hide();
						$(elem+' .item:first').show();
						$(elem+' li a.on').removeClass('on')
						$(elem+' li a:first').parent().next().find('a').addClass('on');
					}
				}
				e.preventDefault();
			});
	},

	wallpapers:{
		download: function(){
			$('.download a.download-submit').bind('click', function(e){
				$(this).parents('form').trigger('submit');
				e.preventDefault();
			});

		},

		resolution: function(){
			var $obj = $('.resolution option');
			var resolution = screen.width + 'x' + screen.height;
			$obj.each(function(){
				if($(this).attr('value') == resolution){
					$(this).text($(this).text()+ "[twoja]");
					$(this).attr('selected','selected');
				}
				if( $(this).attr('value') == ''){
					$(this).attr('value', resolution)
					$(this).attr('selected','selected');
				}
			});
			$('#rozdzielczosc').text(resolution);
			$('a.screen-size').bind('click', function(e){
				$(this).next().toggle();
				e.preventDefault();
			});
		}
	},

	premiereInform: function(){
		/* dodawanie/usuwanie informacji o grze do profilu użytkownika*/
		$('.premiereInform > a').bind('click',function(e){
			if(!$(this).hasClass("linkToLoginSite")){
				e.preventDefault();
				var $this = $(this);
				var $loader = $('<div class="loader"></div>');

				$this.css('position','relative').append($loader);

				if($this.attr('class') == 'linkInformAboutGame'){
					$loader.append("Śledzenie gry dodane do profilu");
				}else{
					$loader.append("Gra usunięta z profilu");
				}

				$.ajax({
					url: $this.attr('href'),
					type:'GET',
					success: function() {
						$this.parent().find('.loader').css({'left':'-40px','top':'-20px'});
						setTimeout(function() {
							$this.parent().find('.loader').show();
							$this.parent().find('a').hide();
							if($this.hasClass('linkInformAboutGame')) {
								$this.parent().find('.linkNotInformAboutGame').css('display', 'block');
							} else {
								$this.parent().find('.linkInformAboutGame').css('display', 'block');
							}
							$('.loader').remove();
						},2000);
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						alert('Error occured: ' + errorThrown);
					}
				});
			}

		});
	},

	time: {
		formatDay: function(day) {
			var temp = day + ' ';
			if (day == 1) {
				temp += 'dzień';
			} else {
				temp += 'dni';
			}
			temp += ' ';
			return temp;
		},
		formatHour: function(hour) {
			var INY = new Array(2,3,4,22,23,24);
			var temp = hour + ' ';
			if (INY.indexOf(hour) != -1) {
				temp += 'godziny';
			}else if(hour == 1){
				temp += 'godzina';
			} else {
				temp += 'godzin';
			}
			temp += ' ';
			return temp;
		},
		formatMinute: function(minute) {
			var INY = new Array(2,3,4,22,23,24);
			var temp = minute + ' ';
			if (INY.indexOf(minute) != -1) {
				temp += 'minuty';
			} else {
				temp += 'minut';
			}
			temp += ' ';
			return temp;
		},
		checkZero: function(value) {
			if (value < 10) {
				return '0' + value;
			} else {
				return value;
			}
		},
		timePeriod: function(date, supertext) {
			var span = (Gami.globals.systemTime - date) / 1000;
			// silnia
			if (span < 0) {
				span = span * (-1);
			}

			var days = Math.floor(span / 86400);
			var days_reszta = span % 86400;
			var hours = Math.floor(days_reszta / 3600);
			var hours_reszta = days_reszta % 3600;
			var minutes =  Math.floor(hours_reszta / 60);

			if (hours == 0 && minutes == 0) { // exactly now
				minutes = 1;
			}
			var period = '';
			if (days > 0 ) {
				period+=  Gami.time.formatDay(days) +' '+ supertext;
			} else {
				if(hours > 0){
					period += Gami.time.formatHour(hours) +' '+ supertext;
				}
				else{
					period+= Gami.time.formatMinute(minutes) +' '+ supertext;
				}
			}

			document.write(period);
		}
	},

	whoiswho: function() {
		var contentLeft = $('.global-content .gamelist-first'),
			contentRight = $('.global-content .gamelist-second');

		$('.developerGameBox .gamelist-first-form').bind('submit', function(e) {
			$.ajax({
				url: $(this).attr('action'),
				type:'post',
				cache: false,
				data: $(this).serialize(),
				success: function(data) {
					contentLeft.html(data);
				}
			});

			e.preventDefault();
		});

		$('.developerGameBox .gamelist-second-form').bind('submit', function(e) {
			$.ajax({
				url: $(this).attr('action'),
				type:'post',
				cache: false,
				data: $(this).serialize(),
				success: function(data) {
					contentRight.html(data);
				}
			});

			e.preventDefault();
		});

		$('.developerGameBox').each(function(i){
			$(this).find('.catalog-alphabet li a').bind('click', function(e) {



				$.ajax({
					url: $(this).attr('href'),
					type:'GET',
					cache: false,
					success: function(data) {
						if(i==0){
							contentLeft.html(data);
							enablePaging(contentLeft);
						}else{
							contentRight.html(data);
							enablePaging(contentRight);
						}
					}
				});

				e.preventDefault();
			});
		});

		function enablePaging(parent) {
			var parent = parent;

			parent.find('.page span a').unbind().bind('click', function(e) {

				$.ajax({
					url: $(this).attr('href'),
					type:'GET',
					cache: false,
					success: function(data) {
						parent.html(data);
						enablePaging(parent);
					}
				});

				e.preventDefault();
			});
		}
	},

	ie6: {
		hoverEffect: function(){
			$('#kb-picks .primary .item').bind('mouseover',function(){
				$(this).css('background-color','#DADEE0')
			});
			$('#kb-picks .primary .item').bind('mouseout',function(){
				$(this).css('background-color','white')
			});
			$('#kb-picks .secondary .item').bind('mouseover',function(){
				$(this).css('background-color','#303131')
			});
			$('#kb-picks .secondary .item').bind('mouseout',function(){
				$(this).css('background-color','black')
			});
		}
	},

	premiereAjax: function() {
		$(document).ready(function() {
			var $form = $('#sendIdsForm');
			if($form.length > 0) {
				var url = $form.attr('action'),
					$listOfElements = $("ul.premiereListContent li[id^='premiere-']"),
					data;

				if($listOfElements.length > 0) {
					$listOfElements.each(function() {
						var elemId = $(this).attr('id').split('premiere-')[1];
						if (data) {
							data = data + ', ' + elemId;
						}
						else {
							data = elemId;
						}
					});

					$.ajax({
						url: url,
						type: 'post',
						data: {
							premiereIds: data
						},
						success: function(response) {
							var $response = $(response),
								$wrapper = $('<div></div>');
							$wrapper.append($response);
							$wrapper.find('li').each(function() {
								var $responseLi = $(this),
									$responseLiId = $responseLi.attr('id');
								$('ul.premiereListContent').find('#premiere-'+$responseLiId+' .premiereInform').replaceWith($wrapper.find('li[id='+$responseLiId+']'));
							});
							Gami.premiereInform();
						}
					});
				}
			}
		});
	},

	updateComments: function() {
		$('td.button input').click(function(e) {
			var $this = $(this),
				$form = $(this).parents("form[name='addVideoComment']"),
				$url = $form.attr('action');

			if(($this.hasClass('notLoggedButton')) || ($form.find('textarea').val() == '')) {
				e.preventDefault();
				if (($this.parent().find('p').length == 0) && ($this.hasClass('notLoggedButton'))) {
					$('<p class="mustBeLogged" style="color: red; margin: 4px 40px 0 0; font-size: 12px; float: right; font-weight: bold;">Musisz być zalogowany</p>').insertAfter($this);
					$this.css('float', 'right');
				}
			}
			else if($form.find('textarea').val().length < 11) {
				e.preventDefault();
				if ($this.parent().find('p').length == 0) {
					$('<p style="color: red; margin: 4px 40px 0 0; font-size: 12px; float: right; font-weight: bold;">Komentarz zbyt krótki</p>').insertAfter($this);
					$this.css('float', 'right');
				}
			}
			else {
				e.preventDefault();
				$.ajax({
					url: $url,
					type: 'post',
					data: $form.serialize(),
					success: function(data) {
						$data = $(data);
						var $firstComment = $('#videoDetailsComments ul li.videoDetailsFirstComment:first');
						if($firstComment.length > 0) {
							$data.find('a[rel="voting"]').gamiInitVoting();
							$firstComment.before($data);
						}
						else {
							var $ul = $('<ul></ul>');
							$('#videoDetailsComments').empty().append($ul.append($data))
						}
						$form.find('textarea').val('');
						$this.parent().find('p').remove();
					}
				});
			}
		});
	},

	/*
	 * Zabawki odpowiedzialne za oskryptowanie forum.
	 * @version 1.0
	 * @author sfurgala
	 */
	forum : {
		//podpinanie akcji zarzadzajacych zakladkami forum
		linkTabs : function () {
			try {
				$('.content-footer').hide();
				$('.forum-tabs a').unbind().bind("click", function (e) {
					Gami.forum._viewTab($(this));
					e.preventDefault();
				});
				Gami.forum._setupUnpinedTabs();
				Gami.forum._firstRun();
			} catch (e) {
				//window.alert('error: ' + e);
			}
		},

		_linkMainButtons : function ($contentObj) {
			$contentObj.find('a.addTopic').unbind().bind('click', function (e) {
				e.preventDefault();
				$(document).scrollTop(0);
				var popup = new Popup({
					url: $(this).attr('rel'),
					width: 600,
					height: 430,
					text: 'Nowy temat',
					onLoad : function () {
						var validator = function (e) {
							var title = $('#forum-topic-add #title').val();
							var text = $('#forum-topic-add textarea').val();
							$('#forum-topic-add .errors').text("");
							if (title.length < 3 || text.length < 50) {
								if (title.length < 3) {
									$('#forum-topic-add .caption .errors').text('Zbyt krótka nazwa!');
								}
								if (text.length < 50) {
									$('#forum-topic-add .text .errors').text('Zbyt krótka treść wpisu!');
								}
								e.preventDefault();
							}
						}
						$('#forum-topic-add .submit-button').unbind().bind('click', function (e) { validator(e); });
						$('#forum-topic-add form').unbind().bind('submit', function (e) { validator(e); });
					}
				});
			});

			var _watcher_bindHelper = function (e, $this) {
				var contentURL = $this.parent().find('.sortByAddress').attr('href'),
					$container = $this.parent().parent().parent().find('.topic-container'),
					linkEnd = "";

				if ($this.hasClass('addWatcher')) {
					$this.removeClass('addWatcher').addClass('removeWatcher');
					linkEnd = "add";
				} else {
					$this.removeClass('removeWatcher').addClass('addWatcher');
					linkEnd = "remove";
				}
				$this.unbind('click');
				$.ajax({
					url : $this.attr('rel') + linkEnd,
					type : 'get',
					success : function (r) {
						$.ajax({
							url : contentURL,
							type : 'get',
							success : function (response) {
								var $resp = $(response);
								$container.html($resp.find('.topic-container').html());
								Gami.forum._linkMore($this.parent().parent().parent());
							}
						});
						$this.bind('click', function (e) { _watcher_bindHelper(e, $this); });
					}
				});
				e.preventDefault();
			}

			$contentObj.find('a.toggleWatcher').unbind().bind('click', function (e) { _watcher_bindHelper(e, $(this)); });
		},

		//akacja wywolujaca odpowiednia karte
		_viewTab : function ($linkObj) {
			try {
				var tabs = $('.forum-tabs li:visible');
				if (tabs.length > 0) {
					var $loader = $('<div class="loadFrame"><span>ładuję</span></div>');
					$linkObj.parent().css('position','relative').append($loader);
					$('.forum-tabs li').removeClass('selected');
					var parrentTabId = $linkObj.parent().attr('class');
					$linkObj.parent().addClass('selected');
					$.ajax({
						url : $linkObj.attr('href'),
						type : 'get',
						success : function (response) {
							var $o = $('.container1 .forum-container'),
								$resp = $(response);
							$o.html("");
							$resp.find('.sortByAddress').attr('href', $linkObj.attr('href'));
							$o.append($resp);

							Gami.forum._linkMainButtons($o);
							Gami.forum._linkSort($o);
							Gami.forum._linkObserve($o);
							$loader.fadeOut(500, function() {
								$loader.remove();
							});
							$.cookie('forum-last-viewed-card', parrentTabId);
						}
					});
				}
			} catch (e) {
				//window.alert('error: ' + e);
			}
		},

		//wywolanie ostatnio aktywnej, lub pierwszej karty
		_firstRun : function () {
			try {
				var lastTab = null;
				if ($.cookie('forum-last-viewed-card')) {
					lastTab = $.cookie('forum-last-viewed-card');
				} else {
					lastTab = 'tab_1';
					$.cookie('forum-last-viewed-card', lastTab);
				}
				var obj = $('.forum-tabs .' + lastTab + ' a');
				Gami.forum._viewTab(obj);
			} catch (e) {
				//window.alert('error: ' + e);
			}
		},

		//podpinanie konrolek pod sortowanie
		_linkSort : function ($parentObj) {
			try {
				$parentObj.find('.caption a').unbind().bind('click', function(e) {
					var type = $(this).attr('class');
					var $contentFrame = $parentObj.find('.topic-container');
					$obj = $(this);
					$parentObj.find('a.sort-down').addClass('hidden');
					$parentObj.find('a.sort-up').removeClass('hidden');
					if (type == "sort-up") {
						$obj.parent().find('a.sort-up').addClass('hidden');
						$obj.parent().find('a.sort-down').removeClass('hidden');
					} else {
						$obj.parent().find('a.sort-down').addClass('hidden');
						$obj.parent().find('a.sort-up').removeClass('hidden');
					}
					var url = $obj.attr('href');
					$parentObj.find('.sortByAddress').attr('href', url);
					$.ajax({
						url : url,
						type : 'get',
						success : function (response) {
							var $response = $(response);
							$contentFrame.html($response.find('.topic-container').html());
							Gami.forum._linkObserve($parentObj);
							//$contentFrame.slideDown(1);
						}
					});
					e.preventDefault();
				});
			} catch (e) {
				//window.alert('error: ' + e);
			}
		},

		//podpinanie kontrolek pod obserwacje
		_linkObserve : function ($parentObj) {
			try {
				var observeLinks = $parentObj.find('.topic-container .observe a').unbind();
				observeLinks.parent().unbind().bind('click', function (e) {
					$(this).parent().addClass('hidden');
					if ($(this).attr('class') == 'start-watch') {
						$obj = $(this).parent().parent().find('.stop-watch').parent().removeClass('hidden');
					} else {
						$obj = $(this).parent().parent().find('.start-watch').parent().removeClass('hidden');
					}
					$.ajax({
						url : $(this).find('a').attr('href'),
						type : 'get',
						success : function (response) { }
					});
				});

			} catch (e) {
				//window.alert('error: ' + e);
			}
		},

		//zarządzanie odpiętymi kartami
		_setupUnpinedTabs : function () {
			var tabs = $('.forum-tabs li');
			$('.forum-tabs').show(0);
			for (var i = 0; i < tabs.length; i++) {
				if ($.cookie('forum-tabs-unpined-' + $(tabs[i]).attr('class')) == "true") {
					$(tabs[i]).hide(0);
				}
			}

			//ukrywanie karty ostatnich tematów z forów pod grami
			$('.forum-tabs li.tab_999').hide(0);

			var hiddenTabs = $('.forum-tabs li:hidden');
			for (var i = 0; i < hiddenTabs.length; i++) {
				Gami.forum._addUnpinedTab($(hiddenTabs[i]).attr('class'));
			}

			$('.forum-tabs a.action-exclude').unbind().bind('click', function (e) {
				var $parent = $(this).parent();
				if ($parent.hasClass('selected')) {
					$parent.hide();
					var tabs = $('.forum-tabs li:visible');
					for (var i = 0; i < tabs.length; i++) {
						//$.cookie('forum-last-viewed-card', $(tabs[i]).attr('class'));
						Gami.forum._viewTab($(tabs[i]).find('a'));
						break;
					}
				} else {
					$parent.hide();
				}
				$parent.removeClass('selected');
				var tabId = $parent.attr('class');
				if ($.cookie('forum-tabs-unpined-' + tabId) != "true") {
					$.cookie('forum-tabs-unpined-' + tabId, "true");
				}
				Gami.forum._addUnpinedTab(tabId);
				e.preventDefault();
			});


		},

		//wstawianie odpietej karty
		_addUnpinedTab : function (tabId) {
			var $block = $('#forum-unpined-tabs .unpined-block').clone(true);
			var $sourceTab = $('.container1 .forum-tabs li.' + tabId);
			var $linkObj = $sourceTab.find('a.forum-title');

			//$block = (block);
			$block.find('a.forum-title').text($linkObj.attr('title'));
			var $container = $block.find('.forum-container');

			$block.find('.action-include a').unbind().bind('click', function (e) {
				Gami.forum._removeUnpinedTab(tabId);
				e.preventDefault();
			});

			//ukrywanie przypinarki dla ostatnich rozmów w forach pod grami
			if (tabId == "tab_999") {
				$block.find('.action-include').hide();
			}

			$.ajax({
				url : $linkObj.attr('href'),
				type : 'post',
				success : function (response) {
					var $resp = $(response);
					$container.html("");
					$resp.find('.sortByAddress').attr('href', $linkObj.attr('href'));
					$container.append($resp);
					Gami.forum._linkMainButtons($block);
					Gami.forum._linkSort($block);
					Gami.forum._linkObserve($block);
				}
			});
			$block.removeClass('hidden').removeClass('unpined-block');
			$block.attr('id', '_' + tabId);

			if ($('#forum-unpined-tabs').find('#_tab_999').length > 0) {
				$block.insertBefore('#forum-unpined-tabs #_tab_999');

			} else {
				$('#forum-unpined-tabs').append($block);
			}
			var tabs = $('.forum-tabs li:visible');
			if (tabs.length < 1) {
				$('.container1 .forum-container').html("");
			}
		},

		//kasowanie odpietej karty
		_removeUnpinedTab : function (tabId) {
			$.cookie('forum-tabs-unpined-' + tabId, "false");
			$('#forum-unpined-tabs #_' + tabId).remove();
			$('.container1 .forum-tabs li.' + tabId).show(0);
			var tabs = $('.forum-tabs li:visible');
			if (tabs.length <= 1) {
				Gami.forum._viewTab($('.forum-tabs li.' + tabId + ' a.forum-title'));
			}
		},

		//wyswietlanie wiekszej ilosci wpisow
		_linkMore : function ($parentObj) {
			$parentObj.find('#more').unbind().bind('click', function (e) {
				$obj = $(this);
				var $loader = $('<div class="loadFrame"><span>ładuję</span></div>');
				$(this).find('a').append($loader);
				$.ajax({
					url : $obj.find('a').attr('rel'),
					type : 'get',
					success : function (response) {
						$obj.remove();
						$parentObj.find('.topic-container').append(response);

						Gami.forum._linkMainButtons($parentObj);
						Gami.forum._linkObserve($parentObj);
						Gami.forum._linkMore($parentObj);
					}
				});

				e.preventDefault();
			});
		},

		//podpinanie kontrolek pod strone glowna forum
		frontPageLink : function () {
			$('.content-footer').hide();

			var $o = $('.container1 .forum-container');
			Gami.forum._linkMainButtons($o);
			Gami.forum._linkObserve($o);
			Gami.forum._linkMore($o);
		},

		/*
		 * Metody zwiazane z interakcja pojedynczego tematu.
		 * @version 1.0
		 * @author sfurgala
		 */
		topic : {

			//konstruktor uruchamiany na stronie pojedynczego tematu
			link : function () {
				$('#post .sort-up').bind('click', function () {
					$.cookie('forum-topic-default-view-type', 'tree', {expires: 365});
				});

				$('#post .sort-down').bind('click', function () {
					$.cookie('forum-topic-default-view-type', 'list', {expires: 365});
				});

				$('#post a.moderator-application').unbind().bind('click', function (e) {
					var popup = new Popup({
						url: $(this).attr('rel'),
						width: 600,
						height: 430,
						text: 'Zgłoszenie nadużycia',
						onLoad : function () {
							$(document).scrollTop(0);
							$('#forum-topic-add form').unbind().bind('submit', function (e) {
								var text = $('#forum-topic-add textarea').val(),
								 	author = $('#forum-topic-add textarea');
								if (typeof author == "undefined") {
									if (text.length < 50) {
										e.preventDefault();
										$('#forum-topic-add .text .errors').text('Zbyt krótka treść wpisu!');
									}
								} else {
									if (author.length < 1) {
										e.preventDefault();
										$('#forum-topic-add .caption .errors').text('To pole nie może być puste!');
									}
									if (text.length < 50) {
										e.preventDefault();
										$('#forum-topic-add .text .errors').text('Zbyt krótka treść wpisu!');
									}
								}
							});
						}
					});
				});

				$('#post a.add-reply').unbind().bind('click', function (e) {
					$('.post-reply').remove();

					var $replyBox = $('#topic-reply'),
						$this = $(this);

					var html = $replyBox.find('.content').html();
					if (html.length <= 0) {
						$.ajax({
							url : $this.attr('rel'),
							type : 'get',
							success : function (response) {
								var $response = $(response);
								$response.filter('.replyForm').unbind().bind('submit', function (e) {
									if ($(this).find('textarea').val().length < 40) {
										$replyBox.find('.reply-form .error').text('Podana treść jest zbyt krótka!');
									} else {
										$replyBox.find('.reply-form .error').text('');
										$.ajax({
											url : $(this).attr('action'),
											type : 'post',
											data : {content : $(this).find('.reply-text').val()},
											success : function (response) {
												//TODO
												location.href = location.href;
											}
										});
									}
									e.preventDefault();
								});
								$replyBox.show(0);
								$replyBox.find('.content').append($response);
							}
						});
					}
					e.preventDefault();
				});

				$('#post a.edit-reply').unbind().bind('click', function (e) {
					$('.post-reply').remove();

					var $replyBox = $('#topic-reply'),
						$this = $(this);

					var html = $replyBox.find('.content').html();
					if (html.length <= 0) {
						$.ajax({
							url : $this.attr('rel'),
							type : 'get',
							success : function (response) {
								var $response = $(response);
								$response.filter('.replyForm').unbind().bind('submit', function (e) {
									if ($(this).find('textarea').val().length < 40) {
										$replyBox.find('.reply-form .error').text('Podana treść jest zbyt krótka!');
									} else {
										$replyBox.find('.reply-form .error').text('');
										$.ajax({
											url : $(this).attr('action'),
											type : 'post',
											data : {
												topicContent : $(this).find('.reply-text').val(),
												token : $(this).find('.token').val()
											},
											success : function (response) {
												//TODO
												location.href = location.href;
											}
										});
									}
									e.preventDefault();
								});
								$replyBox.show(0);
								$replyBox.find('.content').append($response);
							}
						});
					}
					e.preventDefault();
				});

				$('#post a.add-post-reply').unbind().bind('click', function (e) {
					var $replyBox = $($(this).attr('href')).find('.post-reply-box'),
					$this = $(this);
					$('#post .post-reply-box').hide(0);
					var html = $replyBox.find('.content').html();
					if (html == undefined || html.length <= 0) {
						$.ajax({
							url : $this.attr('rel'),
							type : 'get',
							success : function (response) {
								var $response = $(response);
								$response.filter('.replyForm').find('textarea').val('');
								$response.filter('.replyForm').unbind().bind('submit', function (e) {
									if ($(this).find('textarea').val().length < 40) {
										$replyBox.find('.reply-form .error').text('Podana treść jest zbyt krótka!');
									} else {
										$replyBox.find('.reply-form .error').text('');
										$.ajax({
											url : $(this).attr('action'),
											type : 'post',
											beforeSend : function () {
												//$('#post .post-reply-box').hide(0);
											},
											data : {content : $(this).find('.reply-text').val()},
											success : function (response) {
												/*TODO*/ location.href = location.href;
											}
										});
									}
									e.preventDefault();
								});
								$replyBox.show(0);
								$replyBox.find('.content').append($response);
							}
						});
					} else {
						$replyBox.show(0);
					}
					e.preventDefault();
				});

				$('#post a.edit-post-reply').unbind().bind('click', function (e) {
					var $replyBox = $($(this).attr('href')).find('.post-reply-box'),
					$this = $(this);
					$('#post .post-reply-box').hide(0);
					var html = $replyBox.find('.content').html();
					if (html == undefined || html.length <= 0) {
						$.ajax({
							url : $this.attr('rel'),
							type : 'get',
							success : function (response) {
								var $response = $(response);
								//$response.filter('.replyForm').find('textarea').val('');
								$response.filter('.replyForm').unbind().bind('submit', function (e) {
									if ($(this).find('textarea').val().length < 40) {
										$replyBox.find('.reply-form .error').text('Podana treść jest zbyt krótka!');
									} else {
										$replyBox.find('.reply-form .error').text('');
										$.ajax({
											url : $(this).attr('action'),
											type : 'post',
											beforeSend : function () {
												//$('#post .post-reply-box').hide(0);
											},
											data : {
												replyContent : $(this).find('.reply-text').val(),
												token : $(this).find('.token').val()
											},
											success : function (response) {
												//TODO
												//location.href = location.href;
											}
										});
									}
									e.preventDefault();
								});
								$replyBox.show(0);
								$replyBox.find('.content').append($response);
							}
						});
					} else {
						$replyBox.show(0);
					}
					e.preventDefault();
				});

				Gami.forum.topic.linkMore();
			},

			//podpinanie kontrolki paginacji
			linkMore : function () {
				$('#post #more a.more-link').unbind().bind('click', function (e) {
					var $a = $(this);
					$.ajax({
						url : $a.attr('rel'),
						type: 'get',
						success : function (response) {
							var $response = $(response),
								$post = $('#post'),
								$a2 = $response.find('a.more-link');

							$post.find('.post-list:last').append($response.filter('ul.post-list').children());
							if (typeof $a2 != "undefined") {
								$a.attr('rel', $a2.attr('rel'));
								if (typeof $a2.attr('rel') == "undefined") {
									$post.find('#more').hide();
									$post.find('.answers-box').css('padding-bottom', '20px');
								}
							}
							Gami.forum.topic.link();
						}
					});
					e.preventDefault();
				});
			},

			/*
			 * Klassor do obslugi drzewka.
			 */
			tree : {
				//podpinanie kontrolek pod drzewko
				link : function () {
					$('.content-footer').hide(0);

					//bindowanie
					$('#post a.tree-reply').unbind().bind('click', function (e) {
						var $a = $(this);
						var $replyBox = $a.parent().parent().parent().find('.' + $a.attr('id'));
						$('#post .comment').hide(0);
						$replyBox.find('.reply-form .error').text('');
						$replyBox.find('textarea').val('');
						$replyBox.find('.comment-content').html('');
						$.ajax({
							url : $a.attr('rel'),
							type : 'get',
							success : function (response) {
								var $response = $(response);
								$response.filter('form').unbind().bind('submit', function (ee) {
									if ($(this).find('textarea').val().length < 40) {
										$replyBox.find('.reply-form .error').text('Podana treść jest zbyt krótka!');
									} else {
										$replyBox.find('.reply-form .error').text('');
										$.ajax({
											url : $(this).attr('action'),
											type : 'post',
											beforeSend : function () {
												//$('#post .post-reply-box').hide(0);
											},
											data : {content : $(this).find('.reply-text').val()},
											success : function (response) {
												/*TODO*/ location.href = location.href;
											}
										});
									}
									ee.preventDefault();
								});
								$replyBox.find('.comment-content').append($response);
								$replyBox.show(0);
							}
						});
						e.preventDefault();
					});

					$('#post a.tree-post-edit').unbind().bind('click', function (e) {
						var $a = $(this);
						var $replyBox = $a.parent().parent().parent().find('.' + $a.attr('id'));
						$('#post .comment').hide(0);
						$replyBox.find('.reply-form .error').text('');
						$replyBox.find('textarea').val('');
						$replyBox.find('.comment-content').html('');

						$.ajax({
							url : $a.attr('rel'),
							type : 'get',
							success : function (response) {
								var $response = $(response);
								$response.filter('form').unbind().bind('submit', function (ee) {
									if ($(this).find('textarea').val().length < 40) {
										$replyBox.find('.reply-form .error').text('Podana treść jest zbyt krótka!');
									} else {
										$replyBox.find('.reply-form .error').text('');
										$.ajax({
											url : $(this).attr('action'),
											type : 'post',
											beforeSend : function () {
												//$('#post .post-reply-box').hide(0);
											},
											data : {
												replyContent : $(this).find('.reply-text').val(),
												token : $(this).find('.token').val()
											},
											success : function (response) {
												//TODO zmiana wywolania na ajaxowe budowanie drzewka
												location.href = location.href;
											}
										});
									}
									ee.preventDefault();
								});
								$replyBox.find('.comment-content').append($response);
								$replyBox.show(0);
							}
						});

						e.preventDefault();
					});

					$('#post a.tree-moderator-application').unbind().bind('click', function (e) {
						var popup = new Popup({
							url: $(this).attr('rel'),
							width: 600,
							height: 430,
							text: 'Zgłoszenie nadużycia',
							onLoad : function () {
								$(document).scrollTop(0);
								$('#forum-topic-add form').unbind().bind('submit', function (e) {
									var text = $('#forum-topic-add textarea').val(),
									 	author = $('#forum-topic-add textarea');
									if (typeof author == "undefined") {
										if (text.length < 50) {
											e.preventDefault();
											$('#forum-topic-add .text .errors').text('Zbyt krótka treść wpisu!');
										}
									} else {
										if (author.length < 1) {
											e.preventDefault();
											$('#forum-topic-add .caption .errors').text('To pole nie może być puste!');
										}
										if (text.length < 50) {
											e.preventDefault();
											$('#forum-topic-add .text .errors').text('Zbyt krótka treść wpisu!');
										}
									}
								});
							}
						});
					});

					Gami.forum.topic.tree.linkMore();
				},

				//podpinanie kontrolki paginacji
				linkMore : function () {
					$('#post #more a.more-tree-link').unbind('click').bind('click', function (e) {
						var $a = $(this);
						$.ajax({
							url : $a.attr('rel'),
							type: 'get',
							success : function (response) {
								var $response = $(response),
									$post = $('#post'),
									$a2 = $response.find('a.more-tree-link');

								$post.find('.last-tree-element_draft-1').removeClass('no-border last-tree-element_draft-1');
								$post.find('.post-tree:last').append($response.filter('ul.post-tree').children());
								//alert(response);
								if (typeof $a2 != "undefined") {
									$a.attr('rel', $a2.attr('rel'));
									if (typeof $a2.attr('rel') == "undefined") {
										$post.find('#more').hide();
										$post.find('.answers-box').css('padding-bottom', '20px');
									}
								} else {
									$post.find('#more').hide();
									$post.find('.answers-box').css('padding-bottom', '20px');
								}
								Gami.forum.topic.tree.link();
							}
						});
						e.preventDefault();
					});
				}
			}
		}
	}
}

$(function() {
	jQuery('html').addClass('js');
	Gami.start();
})
