$().ready(function() {
    $(document).pngFix();
    
	loading = function (status) {
		if (status) {			 
		  $("#loader").css({ opacity: 1, display: "block" }).stop().animate({ opacity: 1 }, 200, "swing");
		  $("#mainContent").stop().animate({ opacity: 0 }, 200, "swing");      						
		} else {
		   $("#mainContent").stop().animate({ opacity: 1 }, 200, "swing");
			 $("#loader").stop().animate({ opacity: 0 }, 200, "swing", function () {
			   $(this).css({ opacity: 0, display: "none" });
   		 });			
		}
	}
		
	StateManager = EXANIMO.managers.StateManager;
	
	setRemoteLinks = function () {
		$('a.remote').each(function (i) {			
			$(this).click(function() {
				StateManager.setState($(this).attr('href').replace(window.url,''));
				return false;
			});
	    });		        

		$('form.remote').each(function (i) {
			$(this).submit(function() {
				if ($("#dayCheck").length > 0 && $("#dayCheck").val() == 0) {
					alert(window.daycheckError);
					return false;
				}
				
				window.formpars = $(this).prepend("<input type='hidden' name='ajax' value='true' />").serializeArray();
				StateManager.setState($(this).attr('action').replace(window.url,''));
				return false;
			});
	    });
	        
	}
	
	StateManager.onstatechange = function(e) {		
	    if (e.id!="") {
    		if ((window.url != window.location.toString().split("#")[0]) && !window.formpars) {
    			window.location = window.url + "#" + e.id.split("?")[0];			
    		} else {
    			if (!window.lock) {
    			  loading(1);
    				window.lock = 1;

    				var pars = (window.formpars?window.formpars:{ ajax: 'true' });
    				window.formpars = false;
    				$("#mainContent").load(window.url+e.id, pars, function (){
    					setRemoteLinks();
    					window.lock = 0;
    					loading(0);
    					$(document).pngFix();
    				});
    			}
    		}		
	    }
	}	
	
	initWbPage = function () {		
		window.lock = 0;
		setRemoteLinks();			
		StateManager.initialize();
	}			
	
	checkIE6 = function () {
	    return ($.browser.msie && parseInt($.browser.version)<7);
	}
	
	addTag = function (str) {
		var selection = "";
		var value = $("#commentText").val();
		var range = $("#commentText").getSelection();
		var before = value.substring(0, range.start);
		var after = value.substring(range.end, value.length);
		
		if ((range.text.length > 0) || (str != "img" && str != "url")) {
			if ((str == "url" || str == "img") && range.text.substr(0,7) != "http://" ) {
				range.text = "http://" + range.text;
			}
			var trailing = "";					    			
			if (range.text[range.length-1] == " ") {
				range.text = range.text.substring(0, range.length-1);
				trailing = " ";
			}
    		var selection = "["+str+"]" + range.text + "[/"+str+"]";
			$("#commentText").val(before + selection + trailing + after);
		} else if (str == "url") {
			if (selection = prompt("Adja meg az urlt!","http://")) {
				$("#commentText").val(before + "[url]" + selection + "[/url] " + after);
			}				
		} else if (str == "img") {
			if (selection = prompt("Adja meg az kép url-t!","http://")) {
				$("#commentText").val(before + "[img]" + selection + "[/img] " + after);
			}				
		}
	};	
	
	htmlToBBCode = function (s) {
		s = $.trim(s);

		function rep(re, str) {
			s = s.replace(re, str);
		};
		
		rep(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi,"[url=$1]$2[/url]");
		rep(/<font.*?color=\"(.*?)\".*?class=\"codeStyle\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]");
		rep(/<font.*?color=\"(.*?)\".*?class=\"quoteStyle\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]");
		rep(/<font.*?class=\"codeStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]");
		rep(/<font.*?class=\"quoteStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]");
		rep(/<font.*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[color=$1]$2[/color]");
		rep(/<font>(.*?)<\/font>/gi,"$1");
		rep(/<img.*?src=\"(.*?)\".*?>/gi,"[img]$1[/img]");
		rep(/<img.*?src=\"(.*?)\".*?\/>/gi,"[img]$1[/img]");
		rep(/<span class=\"codeStyle\">(.*?)<\/span>/gi,"[code]$1[/code]");
		rep(/<span class=\"quoteStyle\">(.*?)<\/span>/gi,"[quote]$1[/quote]");
		rep(/<strong class=\"codeStyle\">(.*?)<\/strong>/gi,"[code][b]$1[/b][/code]");
		rep(/<strong class=\"quoteStyle\">(.*?)<\/strong>/gi,"[quote][b]$1[/b][/quote]");
		rep(/<em class=\"codeStyle\">(.*?)<\/em>/gi,"[code][i]$1[/i][/code]");
		rep(/<em class=\"quoteStyle\">(.*?)<\/em>/gi,"[quote][i]$1[/i][/quote]");
		rep(/<u class=\"codeStyle\">(.*?)<\/u>/gi,"[code][u]$1[/u][/code]");
		rep(/<u class=\"quoteStyle\">(.*?)<\/u>/gi,"[quote][u]$1[/u][/quote]");
		rep(/<\/(strong|b)>/gi,"[/b]");
		rep(/<(strong|b)>/gi,"[b]");
		rep(/<\/(em|i)>/gi,"[/i]");
		rep(/<(em|i)>/gi,"[i]");
		rep(/<\/u>/gi,"[/u]");
		rep(/<u>/gi,"[u]");
		rep(/<br \/>/gi,"\n");
		rep(/<br\/>/gi,"\n");
		rep(/<br>/gi,"\n");
		rep(/<p>/gi,"");
		rep(/<\/p>/gi,"\n");
		rep(/&nbsp;/gi," ");
		rep(/&quot;/gi,"\"");
		rep(/&lt;/gi,"<");
		rep(/&gt;/gi,">");
		rep(/&amp;/gi,"&");
		rep(/&undefined;/gi,"'"); // quickfix
		return s; 		
	}		
	
	initGallery = function () {
		var contentOffset = $("#mainContent").offset();		
				
		window.defLeft  = contentOffset.left + 360;
		window.defTop 	= contentOffset.top + 310;
		window.contentLeft = contentOffset.left;
		window.contentTop = contentOffset.top;
		window.gLoading = 0;
		
		$(".gallery_image img").css({ opacity: 1 });
		$(".gallery_image > div").css({ zIndex: 10, display: "block", opacity: 0 });
		$(".gallery_image > a").click(function() {
			return false;
		});
					
		$(".gallery_image > div").mouseover(function () {
				$(this).stop().animate({ opacity: 0.5 }, 100, "swing", function () {
					$(this).animate({opacity: 0 }, 200);
				});
		});
				
		
		$(".gallery_image").click(function () {
		    if (!window.gLoading) {
		      window.gLoading = 1;
		      $(this).children("div").before('<div id="galleryLoader">&nbsp;</div>');		    
			  galleryLoad($(this));
		    }
		});
		
		resizeImg = function (img, MaxWidth, MaxHeight)	{
            var widthRatio = img.width / MaxWidth;
            var heightRatio = img.height / MaxHeight;
            var ratio = Math.max(widthRatio, heightRatio);
            img.width = Math.floor(img.width / ratio);
           	img.height = Math.floor(img.height / ratio);
            return img;
		}	
		
		galleryShow = function () {
			galleryLoader();
			$("#galleryTable").css({ opacity: 0, display: "block" }).stop().animate({ opacity: 1 });
		}
		
		galleryClose = function (el) {		    		    		    
		    $(".gallery_image img").css({ opacity: 1 });
		    $("#galleryOverlay").remove();
		    $("#galleryPrev").remove();
		    $("#galleryNext").remove();
		    $("#galleryLoader").remove();
		    $("#galleryClose").stop().animate({ opacity: 0 }, 100, function() {
                $("#galleryClose").remove();
		    });
		    $("#galleryImageContainer").stop().animate({ opacity: 0 }, 400, "linear", function() {
		        $("#galleryImageContainer").remove();
		        if (el == "next" || el == "prev") {		            
		           galleryLoadPage(el);
		        } else if (el) {
        	       window.gLoading = 1;
                   $(el).children("div").before('<div id="galleryLoader">&nbsp;</div>');		    
        	       galleryLoad($(el));				            
		        }
		    });
		    
		}	
		
		galleryLoadPage = function (str) {		    
		    var el = (str=="next")?$("#paginationNext"):$("#paginationPrev");		    
		    var href = el.attr('href').replace(window.url,'');
			if (!window.lock) {
			  	loading(1);
				window.lock = 1;
				$("#mainContent").load(window.url+href+"?ajax=true", function (){
					setRemoteLinks();
					window.lock = 0;
					loading(0);
					$(document).pngFix();
					(str=="next")?galleryLoad($(".gallery_image:first")):galleryLoad($(".gallery_image:last"));
				});
			}		    
		}
		
		galleryLoad = function (el) {	
			offsets = el.offset();		   
			
            var left = offsets.left;
            var top = offsets.top;
            var image = window.url+"public/upload/gallery/" + el.children("a").attr("rel") + "/large/" + el.children("a").attr("title");
            var imageOri = window.url+"public/upload/gallery/" + el.children("a").attr("rel") + "/" + el.children("a").attr("title");
            var title = el.children("a").children("img").attr("alt");
		    
			img = new Image();		    
		        
		    img.onload=function (){
		      window.gLoading = 0;
		      $("#galleryLoader").remove();
		      var width = 0;
		      var height = 0;
		      width = img.width;
		      height = img.height;    		      
			  img = resizeImg(img,150,150);			 

			  if (img.width < 150) {
			  	left += Math.floor((150-img.width)/2);
			  }			  
			  
    		  if (img.height < 150) {
    		  	top += Math.floor((150-img.height)/2);
    		  }
    		      	
    		  
    		  $(".gallery_image img").css({ opacity: 0.4 });
    		  

		      $("body").prepend("<div id='galleryImageContainer' style='position: absolute; display: none; left: "+left+"px; top: "+top+"px;'><img id='galleryImage' style='width: "+img.width+"px; height: "+img.height+"px' src='"+image+"' alt='' /><div id='galleryDesc'>"+(title?title:"")+"<br /><a id='galleryFullImage' href='"+imageOri+"' target='_blank'></a></div></div>");		      
		      $("body").prepend("<div id='galleryOverlay' style='position: absolute; left: "+window.contentLeft+"px; top: "+window.contentTop+"px; width: 900px; height: "+$("#mainContent").height()+"px; z-index: 99; background-color: transparent;'>&nbsp;</div>");              
		      
              $("#galleryImageContainer").css({ display: "block", opacity: 0 });
              
		      var targetLeft = window.defLeft - Math.floor(width/2);
		      var targetTop  = window.defTop - Math.floor(height/2);		      
		      
		      jQuery.easing.def = "easeInOutQuart";
		      
		      $("#galleryImageContainer").animate({ opacity: 1, left: targetLeft, top: targetTop },500,"swing");
		      $("#galleryImage").animate({ width: width, height: height },500,"swing", function () {
		      	jQuery.easing.def = "easeOutQuad";
		      	
		        $("#galleryDesc").css({ width: width+"px", display: "block", opacity: 0 }).animate({ opacity: 1 });	
		        		        
		        $("body").prepend("<div id='galleryClose' style='left: "+(targetLeft-10)+"px; top: "+(targetTop-10)+"px'>&nbsp;</div>");
		        $("body").prepend("<div id='galleryPrev'  style='left: "+targetLeft+"px; top: "+targetTop+"px; width: "+Math.floor(width/2)+"px; height: "+height+"px;'>&nbsp;</div>");
		        $("body").prepend("<div id='galleryNext'  style='left: "+(targetLeft+Math.floor(width/2)+5)+"px; top: "+targetTop+"px; width: "+Math.floor(width/2)+"px; height: "+height+"px;'>&nbsp;</div>");
		        
		        $("#galleryPrev, #galleryNext").css({ display: "block", opacity: 0 });
		          
		        if (el.prev(".gallery_image").length || $("#paginationPrev").length ) {
		            $("#galleryPrev").css({ display: "block", opacity: 0, cursor: "pointer" });
    		        $("#galleryPrev").hover(
    		          function(){    		              
    		              $(this).stop().animate({ opacity: 1 });    		              
    		          },
    		          function(){
    		              $(this).stop().animate({ opacity: 0 });
    		          }
    		        );
    		          
    		        $("#galleryPrev").click(function(){
    		              if (el.prev(".gallery_image").length) {
    		                  galleryClose(el.prev(".gallery_image"));
    		              } else {
    		                  galleryClose("prev");
    		              } 		              
    		        });		            		           
		        }
		        
		        if (el.next(".gallery_image").length || $("#paginationNext").length) {
		            $("#galleryNext").css({ display: "block", opacity: 0, cursor: "pointer" });
    		        $("#galleryNext").hover(
    		          function(){
    		              $(this).stop().animate({ opacity: 1 });
    		          },
    		          function(){
    		              $(this).stop().animate({ opacity: 0 });
    		          }
    		        );	
    		          
    		        $("#galleryNext").click(function(){
    		              if (el.next(".gallery_image").length) {
    		                  galleryClose(el.next(".gallery_image"));
    		              } else {
    		                  galleryClose("next");
    		              }
    		        });		           
		        }
		        
		        
		        
		        $("#galleryClose").css({ display: "block", opacity: 0 }).animate({ opacity: 1 });
		        $("#galleryClose, #galleryOverlay").click(function(){		              
		          galleryClose();
		        });
		        
		        $(document).pngFix();
		      });		      		     
		    }
		    img.src = image;					
		}				
	}
	
	
	initWbPage();
});	


