function externalLinks() {
    if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName("a");
    for (var i=0; i<anchors.length; i++) {
        var anchor = anchors[i];
        var relBlank = anchor.getAttribute("rel");   
        var relArray = new Array(); 
        if(relBlank != null)  
          relArray = relBlank.split(' '); 
        if (anchor.getAttribute("href") && relArray.indexOf("blank") >= 0)
            anchor.target = "_blank";
    }
}

function publicationGallery (){
	
	$("a.SelectedPublication").click(function() {
		
		$(this).parent().find("div.mContent").remove();
		$(this).parent().append($("<div>").addClass("mContent"));
		var mContent = $(this).parent().find("div.mContent");
		$(mContent).hide();

		$.ajax({
	        method: 'get',
	    	url:  '/Warski/scr/getMagazineImages.php',
	    	data: 'pid=' + $(this).attr("rel"),
	    	async: false,
    		success: function(rez) {
				$(mContent).html(rez);
				$(mContent).find("a").lightBox({overlayBgColor:'#000000'});
				var el = $(mContent).find("a:first");
				$(el).click();
    		}
    	});	
		
		return false;
	});
	
}


window.onload = externalLinks;

var autoStartGallery = 0;

String.prototype.startsWith = function(prefix) {
	    return this.indexOf(prefix) === 0;
	}
	 
	String.prototype.endsWith = function(suffix) {
	    return this.match(suffix + "$") == suffix;
	}
	
//player
	function playerShow(trackID, servURL, play) {
		
		if (play == true) {
			var isPlay = 1;
		} else {
			var isPlay = 0;
		}
		var soAudioPlayer = new SWFObject("/swf/www/playerAudio4.swf?isPlay="+isPlay+"&amp;trackUrl=/upl/audio/" + trackID , "audioPlayerMv", "35", "20", "9", "#ffffff");
		soAudioPlayer.addParam("quality", "best");
		soAudioPlayer.addParam("wmode", "transparent");
		soAudioPlayer.addParam("menu", "false");
		soAudioPlayer.write("audioPlayer");
	} 
	
	function showVideoProductDetails (videoUrl){
		var showVideoProductDetails = new SWFObject("/swf/www/videoPlayerProductDetails.swf?videoUrl=/upl/products_category/video/" + videoUrl , "product_desc_video", "591", "397", "9", "#ffffff");
		showVideoProductDetails.addParam("quality", "best");
		showVideoProductDetails.addParam("wmode", "window");
		showVideoProductDetails.addParam("menu", "true");
		showVideoProductDetails.addParam("allowScriptAccess", "sameDomain");
		showVideoProductDetails.addParam("allowFullScreen", "true");
		showVideoProductDetails.addParam("play", "true");
		showVideoProductDetails.addParam("autoPlay", "true");
		showVideoProductDetails.write("product_desc_video");
	}
	
	function showVideoNewsDetails (videoUrl){
		var showVideoProductDetails = new SWFObject("/swf/www/videoPlayerProductDetails.swf?videoUrl=/upl/articles/video/" + videoUrl , "news_desc_video", "591", "397", "9", "#ffffff");
		showVideoProductDetails.addParam("quality", "best");
		showVideoProductDetails.addParam("wmode", "window");
		showVideoProductDetails.addParam("menu", "true");
		showVideoProductDetails.addParam("allowScriptAccess", "sameDomain");
		showVideoProductDetails.addParam("allowFullScreen", "true");
		showVideoProductDetails.addParam("play", "true");
		showVideoProductDetails.write("news_desc_video");
		
	}
	
	function showHorizontalSlider(servURL) {
		var soHorizontalSlider = new SWFObject("/swf/www/sliderHorizontal5.swf?xmlUrl=/Warski/scr/" + servURL , "sliderHorizontalMovie", "1024", "300", "9", "#ffffff");
		soHorizontalSlider.addParam("prodAlign", "center");
		soHorizontalSlider.addParam("quality", "best");
		soHorizontalSlider.addParam("wmode", "window");
		soHorizontalSlider.addParam("menu", "false");
		soHorizontalSlider.addParam("allowScriptAccess", "sameDomain");
		soHorizontalSlider.addParam("allowFullScreen", "false");
		soHorizontalSlider.write("sliderHorizontal");
	}
	
	function getDocHeight() {
        var D = document;
        return Math.max(
            Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
            Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
            Math.max(D.body.clientHeight, D.documentElement.clientHeight)
        );
	}
	
	function getDocWidth() {
        var D = document;
        return Math.max(
            Math.max(D.body.scrollWidth, D.documentElement.scrollWidth),
            Math.max(D.body.offsetWidth, D.documentElement.offsetWidth),
            Math.max(D.body.clientWidth, D.documentElement.clientWidth)
        );
	}
	
	
	// Zakladki w dystrybucji
	function initDistribution() {
		Cufon.replace('.distribution_dls dl dd', {fontFamily: 'Museo Sans 500'});
		$(".distribution_dls dl:first").addClass("active").show('slow');
		
		$(".distribution_dls dl").click(function(){
			if (false == $(this).hasClass("active")) {
				$(".distribution_dls dl.active").removeClass("active");
				$(".distribution_dls dl.active dt").hide("slow");
				$(this).addClass("active").show("slow");
//		Cufon.replace('dl.active dd', {fontFamily: 'Museo Sans 500'});
		 		$('#wrap').jScrollPane(); 
			}	
		});

	} //.initDistribution
	
	// podpiecie akcji przeladowania strony
	function winitActions() {
		
		
		$("#productMenu dl dd a, .col_left a, .col_right a, a.more,#breadcrumbs a, ul.sitemap a, ul.pager a, a.ax").click(function() {
			 return wLoadPageByUrl($(this).attr("href"));
		});
		
		
		$("a[rel='blank']").focus(function() {
			$(this).attr("target","_blank");
		});
		
		
		
		// aktywacja galleri
		wGallery();
		
		
		//Over w opowiesciach
		 $('.story').mouseover(function() {$(this).addClass('over');});
		 $('.story').mouseout(function() {$(this).removeClass('over');});
		 
		 // galeria przewijana 
		 wInitGalleryRotated();
		 
		   //Newsletter
		   $(".newsletter").colorbox({width:"470px", inline:true, href:"#newsletter"});
		   
		   //Checkbox
		   $('#newsletter .check').checkBox();
	
		// aktywacja dystrubucji
		initDistribution(); 
	   
		
		// aktywacja galerii w media o nas
		publicationGallery();
		 //Aktywacja scrolla 
		 //$('#wrap').jScrollPaneRemove(); 
		 //$('#wrap').jScrollPane(); 
		
		 
	}
	
	function showGalleryImage(gIdx, gAll) {
		$('#galleryRotated a.prev').hide()
		$('#galleryRotated a.next').hide();
			
		if (gIdx > 0 && gAll > 1) {
			$('#galleryRotated a.prev').show();
		}
		
		if (gIdx < gAll - 1 && gAll > 1) {
			$('#galleryRotated a.next').show();
		}
		
		$('#galleryRotated img:eq('+ gIdx +')').fadeIn().show();;
		$('#galleryRotated p.counter').html(gIdx + 1 + '/' + gAll);
	}
	
	// pokazuje loader AJAX
	function wShowLoader() {
		$("#wLoader").show();
	}
	
	// ukrywa loader AJAX
	function wHideLoader() {
		$("#wLoader").hide();
	}
	
	// odpalnie odpowiednich js po wykonaniu akcji ajax
	function wFinalizeAction() {
		winitActions();
		wLoadFonts();
		Cufon.now(); 		
	}
	
	function wHorizontalSliderReload(url) {
			$.ajax({
		  		type: "GET",
		  		url: "/ServerComforty.php?m=loadPageByUrl",
		  		data: url,
		  		async: false,
		  		beforeSend: function() {},
		        complete: function(){ },
		        success: function(rez2) {
		        	rv = JSON.parse(rez2);
		        	if (rv.state == false) {
		   				alert("Wystąpił błąd podczas komunikacji z serwerem");
		   				return false;
		   			} else {
		   				$("#wrap").remove();
		   				$("#breadcrumbs").remove();
//		   				$("#content").append($("<div>").attr("id", "wrap"));
		   				$("#content").html("" + rv.response.content);
		   				wFinalizeAction();
		   				$('#wrap').jScrollPane();
		   				
//		   				if ( history.pushState ) history.pushState( {"state" : url}, document.title, "http://" + document.domain + "/?" + url );
		   			}
		        }
		  	});
	}
	  
	function wInitGalleryRotated() {
		var gIdx = 0;
		var gAll = $('#galleryRotated img').length;
		showGalleryImage(gIdx, gAll);
		
		
		$('#galleryRotated img').hide(); 
		
		$('#galleryRotated img:eq('+gIdx+')').show();
		$('#galleryRotated a.next').click(function() {
			 $('#galleryRotated img:eq('+gIdx+')').fadeOut().hide();
			showGalleryImage(++gIdx, gAll);
			return false;
		});
		
		$('#galleryRotated a.prev').click(function(){
		 	$('#galleryRotated img:eq('+gIdx+')').fadeOut().hide();
		 	showGalleryImage(--gIdx, gAll);
			return false;
		});
	}
	
	/**
	 * Galeria
	 */
	
	function wGallery() {
		$("#gallery a").click(function() {
			 var maxPhotos =  photos.length;
			 
			 if (photos == undefined || photos.length ==  0) {
				 return false;
			 }
			
			
			 
		    var cIdx = $("#gallery a").index(this);
		   
		   
		   var docHeight = getDocHeight() + 50;
		   var docWidth = getDocWidth();
		   var topSpace = (getDocHeight() - 540)/2;
		   var leftSpace = (docWidth - 970)/2;
		   
		   $("body")
		   .append($('<div>').attr("id","warskiGallery")
		     .append('<div id="warskiOverlay" style="background-color: rgb(119, 119, 119); opacity: 0.7; cursor: pointer; height: ' + docHeight +'px; display: block;"></div>')
		     .append('<div id="warskiWrap" style="width: 970px; height: auto; top: ' + topSpace + 'px; left: ' + leftSpace + 'px; display: block;"><div id="warskiOuter"><div id="warskiContent" style="border-width: 10px; width: 950px; height: auto;"><div style="width: auto; height: auto; overflow: auto; position: relative;"><div id="wrap_photos"></div></div></div><a id="warskiClose" style="display: inline;"></a></div></div>')
		   );
		  
		  

		   
//		   var photosElements= $("#gallery a");
//		   var photos = new Array();
		   
//		   for (i =0; i< photosElements.length; i++) {
//		      photos[i]  = new Array($(photosElements[i]).attr("rel"), $(photosElements[i]).attr("href"));
//		   }
		   
		   // kursory lewo prawo i kontener na obrazek
		   $("#wrap_photos")
		    .append($('<div>').attr("id","big_photo")
		     .append($('<a href="#" >').attr("id","big_photo_left").focus(function() {$(this).blur();}))		
		     .append($('<a href="#" >').attr("id","big_photo_right").focus(function() {$(this).blur();}))		
		     .append($("<img>").attr("src", photos[cIdx][1]))       
		    )
		    .append('<img src="img/www/up.gif" alt="do góry" id="up">')
		    .append('<div id="wrap_list"><ul class="photos"></ul></div>')
		    .append('<img src="img/www/down.gif" alt="w dół" id="down">');
		    
		    
		    var photosConteiner = $("#wrap_list ul");
		    
		    for (i =0; i<maxPhotos; i++) {
		      photosConteiner.append($("<li>").append($("<img>").attr("src", photos[i][0]).attr("rel",i).css({"cursor" : "pointer"}).one("click", function() {
		          var idx2Load = $(this).attr("rel");
		          $("#big_photo img").attr("src", photos[idx2Load][1]);
		          cIdx = parseInt(idx2Load);
		        } )  ) );
		    }
		    
		    var eHeight = $("#wrap_list ul").height();
		    var cHeight = $("#wrap_list").height();
		    var eTopMargin = parseInt($("#wrap_list ul").css("margin-top"));
		    var oneStep = 76;
		    var step = 6 * oneStep;
		    var aSpeed = 500;
		    
		    // strzalka w lewo
		    $("#wrap_photos #big_photo_left").click(function() {
		    	if (cIdx > 0) {
			  		cIdx = cIdx - 1;
			  		$("#wrap_list ul li:eq("+cIdx+") img").click();
			  	} else if (cIdx == 0){
			  		cIdx = maxPhotos -1 ;
					$("#wrap_list ul li:eq("+cIdx+") img").click();
			  	}
		    	
		    	if (cIdx % oneStep == 0) {
		    		 $("#down").click();
		    	}
		    	
		    	return false;
		    });
		    
		    // strzalka w prawo
		    $("#wrap_photos #big_photo_right").click(function() {
		    	if (cIdx < maxPhotos - 1) {
			  		cIdx = cIdx + 1;
			  		$("#wrap_list ul li:eq("+cIdx+") img").click();
			  	} else if (cIdx == maxPhotos -1) {
			  		cIdx = 0 ;
					$("#wrap_list ul li:eq("+cIdx+") img").click();
			  	} 
		    	
		    	if (cIdx % oneStep == 0) {
		    		 $("#up").click();
		    	}
		    	
		    	return false;
		    });
		    
		    
		    $(document).keyup(function(event){
				
		    	if ($("#warskiGallery").is('*')) {
				  if (event.keyCode == 37) {
					  	if (cIdx > 0) {
					  		cIdx = cIdx - 1;
					  		$("#wrap_list ul li:eq("+cIdx+") img").click();
					  	} else if (cIdx == 0){
					  		cIdx = maxPhotos -1 ;
							$("#wrap_list ul li:eq("+cIdx+") img").click();
					  	}
					  	
//					  	if (cIdx % 7 == 0) {
//				    		 $("#down").click();
//				    	}
					  	
				  } else if (event.keyCode == 39) {
						if (cIdx < maxPhotos - 1) {
					  		cIdx = cIdx + 1;
					  		$("#wrap_list ul li:eq("+cIdx+") img").click();
					  	} else if (cIdx == maxPhotos -1) {
					  		cIdx = 0 ;
							$("#wrap_list ul li:eq("+cIdx+") img").click();
					  	}
						
//						if (cIdx % 7 == 0) {
//				    		 $("#up").click();
//				    	}
				  }
				  
		    	}
				  
			 });
		    
		    var slideSteps = Math.ceil(maxPhotos /  7);

		    var slideCur	=  1;
		      
		    $("#up").click(function() {
		    	slideCur += 1;
//		    	alert("up" + slideCur);
		    	if (slideCur <= slideSteps) {
			        $("#wrap_list ul").animate({
			            marginTop: '-=' + step
			          }, aSpeed, function() {
			               eTopMargin = parseInt($("#wrap_list ul").css("margin-top")) ;
			          });
		    	}
		    	if (slideCur >= slideSteps) {
		    		$("#up").hide();
		    	}
		    	if (slideCur <=1) {
		    		$("#down").hide();
		    	} else {
		    		$("#down").show();
		    	}
		    });
		    
		    $("#down").click(function() {
		    	slideCur -= 1;
//		    	alert("down" + slideCur); 

		    	if (slideCur >= 1) {
			    	$("#wrap_list ul").animate({
				          marginTop: '+=' + step
				        }, aSpeed, function() {
				           eTopMargin = parseInt($("#wrap_list ul").css("margin-top")) ;
				        });
		    	}
		    	
		    	if (slideCur <= 1) {
		    		$("#down").hide();
		    	} 
		    	
		    	if (slideCur > 1) {
		    		$("#up").show();
		    	}
		    });
		    
		    if (slideCur <=1) {
	    		$("#down"). hide();
	    	}
			if (slideCur >= slideSteps) {
	    		$("#up").hide();
	    	}
		    /*          
		    $("#up").click(function() {
		        if (eHeight + eTopMargin >=  cHeight )   {
		          $("#wrap_list ul").animate({
		            marginTop: '-=' + step
		          }, aSpeed, function() {
		               eTopMargin = parseInt($("#wrap_list ul").css("margin-top")) ;
		          });
		        }
		    });
		   
		   $("#down").click(function() {
		      if (eTopMargin   <  0)   {
		        $("#wrap_list ul").animate({
		          marginTop: '+=' + step
		        }, aSpeed, function() {
		           eTopMargin = parseInt($("#wrap_list ul").css("margin-top")) ;
		        });
		      }
		    });
		   
		  
		   if (eHeight + eTopMargin >=  cHeight ) {
               $("#up").show();
		   }  else {
               $("#up").hide();
           }
           */

		 /*  
         if (eTopMargin   <  0 || eHeight <= cHeight ) {
               $("#down").hide();
         } else {
               $("#down").show();
         }
         */

		  // if (cIdx > 0) {
//		      $("#wrap_list ul").animate({marginTop: '-=' + (oneStep * cIdx)},aSpeed, function () {});      
		  // }
		   $("#warskiClose").click(function() { autoStartGallery = 0; $("#warskiGallery").remove()});
		  
		   return false;
		  });
	  
		  if (parseInt(autoStartGallery) == 1) {	
		  		$("#gallery ul li").eq(0).find("a").click();
		  }
	}
	
	 $(document).keyup(function(event) {
	
		  if (event.keyCode == 27 && $("#warskiClose").is('*')) {
			  autoStartGallery = 0; 
			  $("#warskiClose").click();
		  }
	 });
	 
	 
	// zaladowanie zawartosci strony
	function wLoadPageContent(pid) {
		
	  	$.ajax({
	  		type: "GET",
	  		url: "/ServerComforty.php?m=loadPageContent&pid=" + pid,
	  		data: "",
	  		async: false,
	  		beforeSend: function() {wShowLoader();},
	        complete: function(){wHideLoader(); },
	        success: function(rez2) {
	        	rv = JSON.parse(rez2);
	        	if (rv.state == false) {
	   				alert("Wystapił błąd podczas komunikacji z serwerem");
	   				return false;
	   			} else {
	   				$("#wrap").remove();
	   				$("#breadcrumbs").remove();
//	   				$("#content").append($("<div>").attr("id", "wrap"));
	   				$("#content").html("" + rv.response);
	   				wFinalizeAction();
	   				$('#wrap').jScrollPane();
	   				//fleXenv.fleXcrollMain('wrap');
	   			
//	   				if ( history.pushState ) history.pushState( {"state" : url}, document.title, "http://" + document.domain + "/?" + url );	


	   			}
	        }
	  	});
	  	
		return false;
	}
	
	function wLoadPageByUrl(url) {
		

		if (false == url.startsWith("#!") && (url.startsWith("#") || url.startsWith("http"))) {
			return true;
		}
		
		url = url.replace("\?", "");
		url = url.replace("/", "");
		
		if (url.startsWith("mailto")) {
			return true;
		}

		
		var curPage =$("#menu a[href='/?"+url+"']"); 
		if (curPage.is("*")) {
			$("#menu a").removeClass("active");
			$("#menu li").removeClass("active");
			$(curPage).addClass("active");
			$(curPage).parent().addClass("active");
		} else if (url == "pageId=1") {
			$("#menu a").removeClass("active");
			$("#menu li").removeClass("active");
		}

	            

	  	$.ajax({
	  		type: "GET",
	  		url: "/ServerComforty.php?m=loadPageByUrl",
	  		data: url,
	  		async: false,
	  		beforeSend: function() {wShowLoader();},
	        complete: function(){wHideLoader(); },
	        success: function(rez2) {
	        	rv = JSON.parse(rez2);
	        	if (rv.state == false) {
	   				alert("Wystapił błąd podczas komunikacji z serwerem");
	   				return false;
	   			} else {
	   				$("#wrap").remove();
	   				$("#breadcrumbs").remove();
//	   				$("#content").append($("<div>").attr("id", "wrap"));
	   				$("#content").html("" + rv.response.content);
	   				wFinalizeAction();
	   				$('#wrap').jScrollPane();

	   				$("#lang li.PL a").attr("href", rv.response.realUrl);
	   				$("#lang li.EN a").attr("href", "/en" + rv.response.realUrl);
//	   				if ( history.pushState ) history.pushState( {"state" : url}, document.title, "http://" + document.domain + "/?" + url );
	   				bookmarks.sethash('#!' + url,url,'#content');
	   				
	   				//fleXenv.fleXcrollMain('wrap');
	   			}
	        }
	  	});
	  	
		return false;
	}

	
$(window).load(function() {

	// blur	
    $("a, input[type='image'], #scroll").focus(function() {
		$(this).blur();
	});
    
	
	$("#menu a").click(function() {
		$("#menu a").removeClass("active");
		$("#menu li").removeClass("active");
		
		$("#footer ul a").removeClass("active");
		$("#footer ul a").parent().removeClass("active");

		$(this).addClass("active");
		$(this).parent().addClass("active");
	
		return wLoadPageByUrl($(this).attr("href"));
	});
	
	
	$("#footer ul a").click(function() {
		$("#menu a").removeClass("active");
                $("#menu li").removeClass("active");

		$("#footer ul a").removeClass("active");
		$("#footer ul a").parent().removeClass("active");

                $(this).addClass("active");
                $(this).parent().addClass("active");

		var ret =  wLoadPageByUrl($(this).attr("href"));
		return ret;
	});

	$("a.ax").click(function() {
		return wLoadPageByUrl($(this).attr("href"));
	});

 // przewiajanie obrazkow
	$('#wrap').jScrollPane(); 
	 
	 // Bindowanie Flexcrolla
	 //fleXenv.fleXcrollMain('wrap');
	
	
	winitActions();
	 
	$("#sound").click(function() {
			
			if (audioPlay == true) {
//				$(this).css({"text-decoration":"line-through"});
				audioPlay = false;
			} else {
//				$(this).css({"text-decoration":"none"});
				audioPlay = true;
			}
			
			$("#audioPlayer object").remove();
			$("#audioPlayer embed").remove();
			
			playerShow(audioTrack,'', audioPlay);
			return false;
	});
	
	
	
	// odpalenie czcionek
//	Cufon.now(); 			
});


