var siteTitle = "Ludzka Twarz EFS: ";
var $j = jQuery.noConflict();
var tabSpeed = 500;
var slideShowSpeed = 1000;
var slideShowTimeout = 5000;
var slideTransitionEffect = "easeInOutBack";
var transitionTime = 1000; // page changing speed
var loading = false;

var homePageSlideImageWidth = 640;

$j(document).ready(function () { 
	function loadContent(menu_item) {
		showLoader();
		var urlToLoad = menu_item;
		$j.ajax({
			type: "GET",
			url: urlToLoad,
			data: "ajax=false",

			success: function(msg) {
				$j(".container100x100").append(msg);
				loading = false;
				open_section();
				hideLoader();
			}
		});
	}
	function open_section() {
		$j(".size100x100:first").animate({left: "-100%"}, {queue:false, duration:transitionTime, easing:"easeInOutBack"} );
		$j(".size100x100:last").animate({left: "-50%"}, {queue:false, duration:transitionTime, easing:"easeInOutBack", "complete" : function() {removeContainer()} } );
		//
		themeBehaviours();
	}
	function removeContainer() {
		var containerToDelete = $j(".size100x100:first");
		var containerToPosition = $j(".size100x100:last");
		$j(containerToDelete).remove();
		$j(containerToPosition).css({"left":0});
	}
	function showLoader() {
		$j(".ajax_loader").remove();
		$j("body").append('<div class="ajax_loader"></div>');
		$j(".ajax_loader").fadeOut(0).fadeIn("slow");
	}
	function hideLoader() {
		$j(".ajax_loader").fadeOut("slow", function() { $j(this).remove(); });
	}
	
	//easeInOutExpo, easeInOutElastic
	function themeBehaviours() {
		linksBehaviour();
		inputsBehaviour();
		slideshowBehaviour();
		tabsBehaviour();
		thumbnailBehaviour();
		portfolioBehaviour();
		themeCommonBehaviour();
		accordionBehaviour();
	}
	
	function linksBehaviour () {
		$j("#header a, .ajax_link").click(function () { 
			if ($j(this).hasClass("current-item") == false && loading == false) {
				loading = false;
				//$j(".current-item").removeClass("current-item");
				$j(this).addClass("current-item");
				//loadContent($j(this).attr("href"));
				SWFAddress.setValue($j(this).attr("href"));
			}
			return false;
		});
	}
	
	function inputsBehaviour() {
		$j("input:not(.submit), textarea").each(function(){
			$j(this).attr({"rel": $j(this).val()});
			
			$j(this)
			.focus(function () {
				if ($j(this).val() == $j(this).attr('rel')) {
					$j(this).val('');
				}
			})
			.blur(function () {
				if ($j(this).val() == '') {
					$j(this).val($j(this).attr('rel'));
				}
			});
		});
		/// Contact form
		var install_url = '';
		$j("#send_me_a_message .submit").click( function(){
			$j(".error").removeClass("error");

			var hasError = false;
			var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	
			var emailToVal = $j("#your_email").val();
			if (emailToVal == '') {
				$j("#your_email").addClass("error");
				hasError = true;
			} else if (!emailReg.test(emailToVal) && emailToVal != undefined) {	
				$j("#your_email").addClass("error");
				hasError = true;
			}
	
			var nameVal = $j("#your_name").val();
			if (nameVal == '' || nameVal == 'What is your name?' ) {
				$j("#your_name").addClass("error");
				hasError = true;
			}
	
			var messageVal = $j("#your_message").val();
			if(messageVal == '' || messageVal == 'Your message') {
				$j("#your_message").addClass("error");
				hasError = true;
			}
	
			if (hasError == false) {
				//var install_url = sitepath;
	
				$author = nameVal;
				$email = emailToVal;
				$message = messageVal;
				$randval = Math.random();
	
				$j.ajax({
					 type: "GET",
					 url: install_url + "contact.php",
					 data: "author="+$author+"&email="+$email+"&comment="+$message+"&randval="+$randval,
					 beforeSend:function()
					 {
						$j('#your_message').attr("disabled", true);
						$j('#your_name').attr("disabled", true);
						$j('#your_email').attr("disabled", true);
					  },
					 error:function()
					 {
						$j('#your_message').removeAttr("disabled");
						$j('#your_name').removeAttr("disabled");
						$j('#your_email').removeAttr("disabled");
					  },
					 success: function(response)
					 {								
						$j("#form_holder").slideUp(800);
						$j("#form_holder").after('<div id="form_message">Message has been sent!</div>');
						$j("#form_message").slideUp(0).slideDown(800)
					 }
				});
			}
	
			return false;
		});
	}
	function slideshowBehaviour() {
		var ss_count = 0;
		$j(".size100x100:last .small_slideshow").each(function(){
			$j(this)
			.wrap('<div class="relative"></div>')
			.before('<div class="ss_nav ss_nav_'+ss_count+'">')
			.cycle({
				fx: 'scrollRight', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
				pause: 1,
				speed: slideShowSpeed,
				timeout: slideShowTimeout,
				delay: -ss_count * 1000,
				before: slideshowOnBefore,
				after:slideshowOnAfter,
				easing: slideTransitionEffect,
				pager:  '.ss_nav_'+ss_count
			});
			ss_count++;
		});
		
		function slideshowOnBefore(currSlideElement, nextSlideElement, options) {
			$j(nextSlideElement).find("span").animate({"opacity": 0}, 0);
		}
		
		function slideshowOnAfter(currSlideElement, nextSlideElement, options) {
			$j(nextSlideElement).find("span").animate({"opacity": 0.85}, 2000);
		}
	}
	
	function tabsBehaviour() {
		var tabs_count = 0;
		$j(".size100x100 .tabs").each(function(){
			$j(this)
			.attr("id", "tabs_"+tabs_count)
			.before('<div class="tabs_nav tabs_nav_'+tabs_count+'">')
			.cycle({
				fx: 'fade',
				timeout: 0,
				speed: tabSpeed,
				containerResize: 1,
				before:  tabsOnBefore, 
				pager:  '.tabs_nav_'+tabs_count
			});
			var tab = $j(this);
			$j(".size100x100 .tabs_nav_"+tabs_count+" a").each(function(){
				var currentTabIndex = $j(this).prevAll().length;
				var tabTitle = $j("#tabs_"+tabs_count+" span").eq(currentTabIndex).html();
				$j(this).html(tabTitle);
			});
			var tabtitle = $j(this).find("span").html();
			tabs_count++;
		});
		
		function tabsOnBefore(currSlideElement, nextSlideElement, options) {
			var tabHeight = $j(nextSlideElement).outerHeight();
			$j(nextSlideElement).parent().animate({"height": tabHeight+"px"}, tabSpeed);
		}
	}
	
	function thumbnailBehaviour() {
		$j('.thumbnail_link').hover(function(){
			$j(this).find('img').fadeTo("fast", 0.7);
		},
		function(){
			$j(this).find('img').fadeTo("fast", 1);
		});
	}
	
	function themeCommonBehaviour() {
		$j(".sidebar_margin").each(function(){
			$j(this).find("h2:first").css({"marginBottom" : "15px"});
		});
		
		$j("a[rel^='prettyPhoto']").prettyPhoto({
			animationSpeed: 'normal', /* fast/slow/normal */
			padding: 15, /* padding for each side of the picture */
			opacity: 0.7, /* Value betwee 0 and 1 */
			showTitle: false, /* true/false */
			allowresize: true, /* true/false */
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'dark_square', /* light_rounded / dark_rounded / light_square / dark_square */
			hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
			modal: false, /* If set to true, only the close button will close the window */
			changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
			callback: function(){} /* Called when prettyPhoto is closed */
		});
		
		$j(".tweets").tweet({
			join_text: "",
			username: twitterlogin,
			avatar_size: 0,
			count: 5,
			auto_join_text_default: "", 
			auto_join_text_ed: "",
			auto_join_text_ing: "",
			auto_join_text_reply: "",
			auto_join_text_url: "",
			loading_text: "loading tweets..."
		});
		
		$j(".thumbnail_link img").load(function() {
 			$j(this).css("opacity", "0.0").animate({opacity: 1.0}, 800);
 		});
	}
	
	function portfolioBehaviour() {
		$j("a.portfolio_link").each(function(){
			if ($j(this).attr('href').match(/(watch)/)) {
				$j(this).addClass("video");
				$j(this).parent().find(".cover").prepend('<img class="video_icon" src="images/play.png" />');
			}
			
		});
		
		$j('.portfolio_th').hover(function(){  
			$j(".cover", this).stop().animate({left:'260px'}, {queue:false, duration:800, easing:slideTransitionEffect});  
		}, function() {  
			$j(".cover", this).stop().animate({left:'5px'}, {queue:false, duration:350, easing:"swing"});  
		});
	}
	
	/*** Accordion ***/
	var slidesInt = null;
	function accordionBehaviour() {
		var slidesCount = $j(".accordion:last .accordionSlide").length;
		var slideInitialWidth = Math.floor( ($j(".accordion").width() - slidesCount) / slidesCount);
		var slideColapsedWidth = Math.floor( ($j(".accordion").width() - homePageSlideImageWidth ) / (slidesCount - 1) - 1);
		var time = 4000;
		var slideHovered = false;
		clearInterval(slidesInt);
		
		function startAccordion() {
			$j(".accordion:last .accordionSlide").each(function(){
				$j(this).css({"width" : slideInitialWidth+"px"});
				$j(this).find("div:first").wrap('<div class="slideText"></div>');
				$j(this).find("img").animate({left: -320}, 0);
			});
			
			$j(".accordion:last .accordionSlide").hover(function(){
				slideHovered = true;
				clearInterval(slidesInt);
			},
			function(){
				slideHovered = false;
				setSlidesInterval();
			});
			
			$j(".accordion:last .accordionSlide").click(function () { 
				if ($j(this).hasClass("currentSlide")) {
					var newLink = $j(this).find("a").attr("href");
					SWFAddress.setValue(newLink)
				} else {
					$j(".currentSlide").removeClass("currentSlide");
					$j(this).prev().addClass("currentSlide");
					nextSlide(slideColapsedWidth);
				}
				return false;
			});		
			
		}
		function setSlidesInterval() {
			slidesInt = setInterval(function() {
				if (slideHovered == false) {
					nextSlide(slideColapsedWidth);
				}
			}, time);
		}
		
		setSlidesInterval();
		
		first = true;
		function nextSlide(slideColapsedWidth) {
			if ($j(".currentSlide").length == 0) {
				$j(".accordion:last .accordionSlide:last").addClass("currentSlide");
			}
			$current = $j(".accordion:last .currentSlide");
			$next = $j(".accordion:last .currentSlide").next();
			
			if ($next.attr('class') == undefined) {
				$next = $j(".accordion:last .accordionSlide:first");
			}
			
			$current.removeClass("currentSlide");
			$j(".accordionSlide").stop().animate({ width: slideColapsedWidth }, {duration:850, easing:"swing"});
			$j(".accordionSlide").find(".slideText").animate({opacity:0}, {queue:false, duration:850, easing:"swing"});
			$j(".accordionSlide").find("img").animate({left: -320}, {queue:false, duration:850, easing:"swing"});
			
			$next.addClass("currentSlide").stop().animate({ width: homePageSlideImageWidth }, {duration:850, easing:"swing"});
			if (!first) {
				$next.find(".slideText")
					.animate({"left": homePageSlideImageWidth}, {queue:false, duration:0})
					.animate({opacity:0.85, left:10}, {queue:false, duration:850, easing:"swing"});
			} else {
				first = false;
				$next.find(".slideText")
					.animate({opacity:0.85, left:10}, {queue:false, duration:850, easing:"swing"});
			}
			$next.find("img").animate({left: 0}, {queue:false, duration:850, easing:"swing"});
		}
		startAccordion();
	}
	
	themeBehaviours();
	
	function handleChange(event) {
		if (event.path != "/" && event.path != "respond") {
			$j(".small_slideshow, .tabs").each(function(){
				$j(this).cycle('stop');				
			});
			//
			var path = event.path;
			if (path.substr(path.length - 1) != '/') {
				path += '/';
			}
			var pathToLoad = event.path.substr(1);
			SWFAddress.setTitle(siteTitle + pathToLoad);
			$j(".current-item").removeClass("current-item");
			$j("#header a").each(function(){
				if ($j(this).attr("href") == pathToLoad) {
					$j(this).addClass("current-item");
				}
			});
			loadContent(pathToLoad);
		}
	}
	SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);
});
