var $j = jQuery.noConflict();

var int=0;//Internet Explorer Fix
$j(window).bind("load", function() {
	int = setInterval("fadeImg()", 300);
});

function fadeImg() {
	var images = $j('.imgfade:hidden').length;
	if (images == 1) {
		clearInterval(int);
		delete int;
	}
	var randomnumber = Math.floor(Math.random()*images);
	$j('.imgfade:hidden').eq(randomnumber).fadeIn(300);
}


function loadTweets() {
	$j("#last_tweets, .tweets").tweet({
	  join_text: "auto",
	  username: twitterlogin,
	  avatar_size: 60,
	  count: 1,
	  auto_join_text_default: "", 
	  auto_join_text_ed: "",
	  auto_join_text_ing: "",
	  auto_join_text_reply: "",
	  auto_join_text_url: "",
	  loading_text: "..."
	});
}

function inputBehaviour() {
	//$j(".comments_holder input:not(.submit), .comments_holder textarea, .widget_search_form input:not(.submit), .widget_search_form textarea").each(function(){
	$j("input:text, 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('');
			}
			$j(this).addClass("focus");
		})
		.blur(function () {
			if ($j(this).val() == '') {
				$j(this).val($j(this).attr('rel'));
			} else {
				$j(this).addClass("notempty");
			}
			$j(this).removeClass("focus");
		});
	});
} // end of function inputBehaviour

function titlePadding() {
	var subm = $j("#submenu");
	if (subm.length != 0) {
		var pr = subm.outerWidth();
		$j("h1.pagetitle").css({"paddingRight" : pr});
	}
}
function toggleBehaviour() {
	$j('.toggle').click(function () {
		$j(this).stop().toggleClass("toggle_close").next('div.toggle_content').toggle(500);
	});
}

function thumbnailBehaviour() {
	var thHovered = null;
	$j(".prettyPhoto img, .news_teaser img, .portfolio_section .grid_4 img").hover(function(e) {
		var th = $j(this);
		thHovered = $j(this);
		var offset = th.offset(); 
		if ($j('#zoom').length == 0) {
			$j("body").append('<div id="zoom"></div>');
			var zx = offset.left + th.outerWidth()/2 - $j("#zoom").outerWidth()/2;
			var zy = offset.top + th.outerHeight()/2 - $j("#zoom").outerHeight()/2;
			$j("#zoom").css({
				"opacity" : 0,
				"top"  : zy,
				"left" : zx
			}).stop().animate({opacity: 1}, 400);
		}
	},
    // Roll Out
    function(e) {
		var th = $j(this);
		var offset = th.offset();
		var thwidth = $j(this).outerWidth();
		var thheight = $j(this).outerHeight();
		if (
			e.pageX < offset.left || parseInt(offset.left + thwidth) <= e.pageX
			||
			e.pageY <= offset.top || parseInt(offset.top + thheight) <= e.pageY
		) {
			$j("#zoom").remove();
		}
	});
	$j("#zoom").live('click', function() {
		if (thHovered.parent().hasClass("border") || thHovered.parent().parent().hasClass("grid_4")) {
			var myUrl = thHovered.parent().attr("href");
			window.location.href = myUrl;
		} else {
			thHovered.trigger('click');
		}
		$j(this).remove();
	});
}




function scrollToTop() {
	/*-----------------------
	* jQuery Plugin: Scroll to Top
	* by Craig Wilson, Ph.Creative http://www.ph-creative.com
	* 
	* Copyright (c) 2009 Ph.Creative Ltd.
	* Licensed under the MIT License http://www.opensource.org/licenses/mit-license.php
	*
	* Description: Adds an unobtrusive "Scroll to Top" link to your page with smooth scrolling.
	* For usage instructions and version updates to go http://blog.ph-creative.com/post/jquery-plugin-scroll-to-top-v3.aspx
	* 
	* Version: 3.0, 29/10/2009
	-----------------------*/
	$j(function(){$j.fn.scrollToTop=function(options){if(options.speed){var speed=options.speed;}else{var speed="slow";}if(options.ease){var ease=options.ease;}else{var ease="jswing";}if(options.start){var start=options.start;}else{var start="0";}var scrollDiv=$j(this);$j(this).hide().removeAttr("href");if($j(window).scrollTop()>start){$j(this).fadeIn("slow");}$j(window).scroll(function(){if($j(window).scrollTop()>start){$j(scrollDiv).fadeIn("slow");}else{$j(scrollDiv).fadeOut("slow");}});$j(this).click(function(event){$j("html, body").animate({scrollTop:"0px"},speed,ease);});}});
	
	$j("#scrollToTop").scrollToTop({
	   speed: 500,
	   ease:  "swing",
	   start: 200
	});
}

function contactFormBehaviour() {
	$j(".contactform").submit(function(){
		$j(".error").removeClass("error");
		
		var randval = Math.random();
		var hasError = false;
		var sub_form = $j(this);
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		
		$j(this).find("input:text, textarea").each(function(index){
			var input = $j(this);
			var val = input.val();
			if ($j(this).hasClass("required") && val == "") {
				hasError = true;
				$j(this).addClass("error");
			}
			if ($j(this).hasClass("validates_as_email") && !emailReg.test(val)) {
				hasError = true;
				$j(this).addClass("error");
			}
		});
		
		var mailpath = $j(this).attr("action");
		var str = $j(this).serialize() +"&randval="+randval;
		if (hasError == false) {
			$j(".form_answer").remove();
			$j.ajax({
				 type: "POST",
				 url: mailpath,
				 data: str,
				 success: function(response)
				 {
					if (response == "ok") {
						sub_form.before('<div class="green_message form_answer">Message has been sent!</div>');
						$j(".form_answer").hide().show("fast");
					} else if (response == "error") {
						sub_form.before('<div class="yellow_message form_answer">Unknown error please try again later.</div>');
						$j(".form_answer").hide().show("fast");
					}
				 }
			});
		} else {
			if ($j(".form_answer").length == 0) {
				sub_form.before('<div class="yellow_message form_answer">Please fill in all required fields.</div>');
				$j(".form_answer").hide().show("fast");
			} else if ($j(".form_answer").hasClass("green_message")) {
				$j(".form_answer").remove();
				sub_form.before('<div class="yellow_message form_answer">Please fill in all required fields.</div>');
				$j(".form_answer").hide().show("fast");
			}
		}
		
		return false;
	});
}

function initJsSweetness() {
	$j("a[rel^='prettyPhoto'], .prettyPhoto, .gallery a").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: 'facebook', /* 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("input:submit").addClass("submit");
	imagePreviewBehaviour();
	tooltipBehaviour();
	tabsBehaviour();
	toggleBehaviour();
	thumbnailBehaviour();
	scrollToTop();
	loadTweets();
	inputBehaviour();
	titlePadding();
	slideshowBehaviour();
	contactFormBehaviour();
	innerAdBehaviour();
	
	$j(".imgpreview, .prettyPhoto, a[rel^='prettyPhoto']").each(function(){
		var img = $j(this).find("img").length;
		if (img == 0) {
			$j(this).addClass("imgTexLinkPreview");
		}
	});
} // end of function initJsSweetness

/**** Global variables which are used by the image preview plugin **/
// Thanks DigitalCavalry (http://themeforest.net/user/digitalcavalry) for the box positioning hint. I owe you a beer! ;)
var g_previewImgWidth = 0;
var g_previewImgHeight = 0;
var g_imgExtraYOffset = 0;
var g_showLoader = false;
var g_initHoverX = 0;
var g_initHoverY = 0;
var g_topPositionAdjusted = false;

var g_imgDescription = '';
function imagePreviewBehaviour() {
    $j(".imgpreview").click(function() {
		return false;
	});
	$j(".imgpreview").hover(function(e) {
        var offsetX = 0;       
        var offsetY = -10;
        var hoveredObject = this;        
        var imageSrc = $j(hoveredObject).attr("href");
  
        $j("body").append('<div id="imgPreview"><div id="imgPreviewImg"></div><div id="imgPreviewDescription"></div></div>');
        $j("body").append('<div id="imgLoader"></div>');
		
        $j("#imgLoader")
			.stop()
			.css({
				"opacity" : 0,
				"left"    : (e.pageX + 8) + "px",
			    "top"     : (e.pageY - 25) + "px"
			})
			.animate({opacity: 1}, 400);
        g_showLoader = true;
            
        $j("#imgPreview").hide();
          
		var img = new Image();
		$j(img).load(function() {
			g_previewImgWidth = img.width;
			g_previewImgHeight = img.height;
			g_imgExtraYOffset = 0;
			
			offsetX = -(g_previewImgWidth / 2);
			g_imgDescription = $j(hoveredObject).attr("title");
			if (g_imgDescription.length != 0) {
				$j(hoveredObject).removeAttr('title');
				$j("#imgPreviewDescription").html(g_imgDescription);
				$j("#imgPreview").show();
				g_imgExtraYOffset = $j("#imgPreviewDescription").outerHeight(true);
				$j("#imgPreview").hide();
			} else {
				$j("#imgPreviewDescription").remove();
			}

			g_initHoverX = e.pageX;
			g_initHoverY = e.pageY;
			var browserWidth = $j(window).width();
			var browserHeight = $j(window).height();
			var previewLeftPosition = e.pageX + offsetX;
			var previewTopPosition = e.pageY + offsetY - g_previewImgHeight - g_imgExtraYOffset;
			
			if (g_previewImgHeight > e.clientY) {
			   previewTopPosition += g_imgExtraYOffset + g_previewImgHeight - offsetY*2;
			   g_topPositionAdjusted = true;
			}
			if (previewLeftPosition < 0) {
				previewLeftPosition = 0;
			}
			if (previewLeftPosition + g_previewImgWidth > browserWidth) {
				previewLeftPosition = browserWidth - g_previewImgWidth;
			}

			$j("#imgPreviewImg").html(this);
			$j("#imgPreviewImg").css({"height": g_previewImgHeight+"px"});

			$j("#imgPreview").hide()
				.css({
					 "visibility" : "visible",
					 "height"     : "auto",
					 "width"      : g_previewImgWidth+"px",
					 "top"        : previewTopPosition + "px",
					 "left"       : previewLeftPosition + "px"
				}).show();
			$j("#imgLoader").stop().animate({opacity: 0}, 400, function(){$j(this).remove()});
			g_showLoader = false;
			
			$j("#imgPreview")
				.css({
					"margin"  : "0px",
					"padding" : "0px",
					"opacity" : "0"})
				.animate({opacity: 1}, 500);
		}).attr("src", imageSrc);

    },
    // Roll Out
    function() {
		if (g_imgDescription.length != 0) {
			var titleAtr = $j("#imgPreviewDescription").html();
			$j(this).attr({"title": titleAtr});
			g_imgDescription = '';
		}
		
        $j("#imgPreview").stop().remove(); 
        $j("#imgLoader").stop().remove();
		g_topPositionAdjusted = false;
		g_showLoader = false;
    });    
    
    $j(".imgpreview").mousemove(function(e) {
		var offsetX = -g_previewImgWidth / 2;
		var offsetY = -10;
		
		var browserWidth = $j(window).width();
		var previewLeftPosition = e.pageX + offsetX;
		var previewTopPosition = e.pageY + offsetY - g_previewImgHeight - g_imgExtraYOffset;

		if (g_previewImgHeight > e.clientY || g_topPositionAdjusted == true) {
			if (g_topPositionAdjusted == true) {
				previewTopPosition += g_imgExtraYOffset + g_previewImgHeight - (offsetY*2);
			}
		}
		if (previewLeftPosition < 0) {
			previewLeftPosition = 0;
		}
		if (previewLeftPosition + g_previewImgWidth > browserWidth) {
			previewLeftPosition = browserWidth - g_previewImgWidth;
		}

		$j("#imgPreview")
			.css({
				"top"  : previewTopPosition + "px",
				"left" : previewLeftPosition + "px"
			});

		if (g_showLoader) {
			$j("#imgLoader")
				.css({
					"left" : (e.pageX + 8) + "px",
					"top"  : (e.pageY - 24) + "px"
				});
		}
	});

}; // end of function imagePreviewBehaviour

var g_tooltipDescription = '';
function tooltipBehaviour() {
	$j(".tooltip, .flickr_badge_image img, .social img").hover(function(e) {
        var offsetX = 0;
        var offsetY = 15;
        var hoveredObject = this;        
  
        $j("body").append('<div id="tooltipDiv"></div>');
        $j("#tooltipDiv").hide();

		g_tooltipDescription = $j(hoveredObject).attr("title");
		if (g_tooltipDescription.length != 0) {
			var hovertitle = $j(hoveredObject).attr('title');
			$j(hoveredObject).removeAttr('title');
			if ($j(hoveredObject).parent().attr("title") == hovertitle) {
				$j(hoveredObject).parent().removeAttr('title');
			}
			
			$j("#tooltipDiv").html(g_tooltipDescription);
		} else {
			return;
		}
		
		g_initHoverX = e.pageX;
		g_initHoverY = e.pageY;
		var browserWidth = $j(window).width();
		var tooltipLeft = e.pageX + offsetX;
		var tooltipTop = e.pageY + offsetY;
		var tooltipWidth = $j("#tooltipDiv").outerWidth(true);
		
		if (tooltipLeft < 0) {
			tooltipLeft = 0;
		}
		if (tooltipLeft + tooltipWidth > browserWidth) {
			tooltipLeft = browserWidth - tooltipWidth;
		}
		
		$j("#tooltipDiv").hide()
			.css({
				 "visibility" : "visible",
				 "height"     : "auto",
				 "width"      : "auto",
				 "top"        : tooltipTop + "px",
				 "left"       : tooltipLeft + "px"
			}).show();
		
		var currentTooltipWidth = $j("#tooltipDiv").outerWidth(true);
		if (currentTooltipWidth > 300) {
			$j("#tooltipDiv").css({"width" : "300px"});
		}
		
		$j("#tooltipDiv")
			.css({
				"margin"  : "0px",
				"opacity" : "0"})
			.animate({opacity: 1}, 500);
    },
    // Roll Out
    function() {
		if (g_tooltipDescription.length != 0) {
			var titleAtr = $j("#tooltipDiv").html();
			$j(this).attr({"title": titleAtr});
			g_tooltipDescription = '';
		}
		
        $j("#tooltipDiv").stop().remove(); 
		g_topPositionAdjusted = false;
    });    
    
    $j(".tooltip, .flickr_badge_image img, .social img").mousemove(function(e) {
		var offsetX = 0;
		var offsetY = 15;
		
		var browserWidth = $j(window).width();
		var tooltipLeft = e.pageX + offsetX;
		var tooltipTop = e.pageY + offsetY;
		var tooltipWidth = $j("#tooltipDiv").outerWidth(true);

		if (tooltipLeft < 0) {
			tooltipLeft = 0;
		}
		if (tooltipLeft + tooltipWidth > browserWidth) {
			tooltipLeft = browserWidth - tooltipWidth;
		}

		$j("#tooltipDiv")
			.css({
				"top"  : tooltipTop + "px",
				"left" : tooltipLeft + "px"
			});

	});
} // end of function tooltipBehaviour

var tabSpeed = 500;
function tabsBehaviour() {
	var tabs_count = 0;
	$j(".tabs").each(function(){
		$j(this).children().addClass("tab");
		$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(".tabs_nav_"+tabs_count+" a").each(function(){
			var currentTabIndex = $j(this).prevAll().length;
			var tabTitle = $j("#tabs_"+tabs_count+" span.tabTitle").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 innerAdBehaviour() {
	var innerad_height = 160;
	$j(".innerad").hover(function() {
		$j(this).find(".topslide").stop().animate({
			"top" : -innerad_height
		});
		
		$j(this).find(".bottomslide").stop().animate({
			"top" : -innerad_height
		});
	},
    // Roll Out
    function() {
		$j(this).find(".topslide").stop().animate({
			"top" : 0
		});
		
		$j(this).find(".bottomslide").stop().animate({
			"top" : 0
		});
	});
}

function slideshowBehaviour() {
	var ss_count = 0;
	$j(".small_slideshow").each(function(){
		$j(this)
		.wrap('<div class="relative"></div>')
		.before('<div class="ss_nav ss_nav_'+ss_count+'">')
		.cycle({
			fx: slideEffect, // 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
		})
		.find('.description').width($j(this).width() - 20);
		ss_count++;
	});
	
	function slideshowOnBefore(currSlideElement, nextSlideElement, options) {
		$j(nextSlideElement).find("div.description").animate({"opacity": 0}, 0);
	}
	
	function slideshowOnAfter(currSlideElement, nextSlideElement, options) {
		$j(nextSlideElement).find("div.description").animate({"opacity": 1}, 2000);
	}
} // end of function slideshowBehaviour


jQuery(document).ready(function($j) {
	$j('.imgfade').hide();
	initJsSweetness();
	$j("#top_menu a").removeAttr('title');
	$j("ul.sf-menu").superfish({
		delay: 200, // one second delay on mouseout
		animation: {opacity:'toggle', height:'show'}, // fade-in and slide-down animation
		speed: 500, // faster animation speed
		autoArrows: false, // disable generation of arrow mark-up
		dropShadows: false // disable drop shadows
	});
	
	//fadeLoadedImages();
	
	if (homepage) {
		if (slidertype == "Coin Slider") {
			$j('#fancycoinholder')
				.css({"display" : "block"})
				.coinslider({
					width: 1052, // width of slider panel
					height: 340, // height of slider panel
					spw: 12, // squares per width
					sph: 5, // squares per height
					delay: slidesdelay*1000, // delay between images in ms
					sDelay: 30, // delay beetwen squares in ms
					opacity: 0.7, // opacity of title and navigation
					titleSpeed: 500, // speed of title appereance in ms
					effect: 'random', // random, swirl, rain, straight
					navigation: true, // prev next and buttons
					links : true, // show images as links 
					hoverPause: true // pause on hover
			});
		} else if (slidertype == "Fancy Slider") {
			$j('#fancyholder')
				.css({"display" : "block"})
				.jqFancyTransitions({ 
					effect: 'zipper', // wave, zipper, curtain
					direction: 'random', // left, right, alternate, random, fountain, fountainAlternate
					width: 1052, // width of panel
					height: 340, // height of panel
					strips: 20, // number of strips
					delay: slidesdelay*1000, // delay between images in ms
					stripDelay: 50, // delay beetwen strips in ms
					titleOpacity: 0.7, // opacity of title
					titleSpeed: 1000, // speed of title appereance in ms
					position: 'alternate', // top, bottom, alternate, curtain
					navigation: true, // prev and next navigation buttons
					links: true // show images as links
			});
		}
		
		$j('#timer').countdown({until: liftoffTime, format: 'HMS', layout: '{hn} {hl} {mn} {ml} {sn} {sl}'});
	}
});
