/*
*	The Little Photoshop Live 
*/


var slider;
var slideContent;
var currentSlide = 0;
var maxSlides;


$(function() {

	// Back to top
	
	$("#back-to-top").click(function() {
		$("html, body").animate({"scrollTop" : "0px"});
		return false;
	});

	// Edit Comments
	if ($(".editcomment").length > 0)
	{
		$(".editcomment").hide();
		$(".editcomment").parent().hover(function() { 
			$(this).children(".editcomment").fadeIn(); 
		}, function() { 
			$(this).children(".editcomment").fadeOut();
		 });
	}
	

	// Product Sidebar Mouseover Transitions Toolbox (apply class superfadey to <div><span></span></div>)
	var superfadey = $("div.superfadey");
	if (superfadey.length > 0)
	{
	
		superfadey.children().hide();
		superfadey.hover(function() {
			$(this).children().fadeIn();
		}, function() {
			$(this).children().fadeOut();	
		});
				
	}
	
	$("#lps-poll a").click(function() {
	
		var pollDiv = $("#lps-poll");
		var pollLoad = $("#poll-loading");

		var voteValue = $("#lps-poll input:checked").val();
		
		if (!voteValue)
		{
			alert('Poll Error: You must select an option to vote for!');
			return false;
		}


		pollLoad.fadeIn();
		pollDiv.slideUp('slow', function() {
			
			$.ajax({  
	  			type: "POST",  
	  			url: "/functions/lps/register_vote/" + voteValue, 
	  			success: function(msg) {
	  			
		  			pollDiv.html('<p>Thanks! Your vote has been registered.</p>').slideDown();
		  			pollLoad.fadeOut();		  			
	  					
	  			}
	  				
	  		});
		
		});

		
		return false;
	
	});


	// Social Media Icons
	if ($("#icons"))
	{
		$("#icons li a").fadeTo(0, 0.7);
		
		$("#icons li a").hover(function() {
			$(this).stop();
			$(this).fadeTo("fast", 1.0);
		}, function() {
			$(this).stop();
			$(this).fadeTo("fast", 0.7);
		});
	}	
	
	
	// Courses
	if ($(".course"))
		$(".course:nth-child(3n+2)").css("margin-right", "0px");
	
	
	// Menu
	$("#homelink").hover(function () {
		$(this).stop().animate	({backgroundPosition:"(0px -376px)"});
	}, function() {
		$(this).stop().animate	({backgroundPosition:"(0px -395px)"});
	});
	
	$("#shoplink").hover(function () {
		$(this).stop().animate	({backgroundPosition:"(-110px -376px)"});
	}, function() {
		$(this).stop().animate	({backgroundPosition:"(-110px -395px)"});
	});
	
	$("#traininglink").hover(function () {
		$(this).stop().animate	({backgroundPosition:"(-295px -376px)"});
	}, function() {
		$(this).stop().animate	({backgroundPosition:"(-295px -395px)"});
	});
	
	$("#contactlink").hover(function () {
		$(this).stop().animate	({backgroundPosition:"(-425px -376px)"});
	}, function() {
		$(this).stop().animate	({backgroundPosition:"(-425px -395px)"});
	});

	
	$("#loadingbar").hide();
	
	
	// Contact Form
	if ($(".contact_form").length > 0)
		$(".contact_form").submit(function() { contactForm(); return false; });
	
	
	// Sticky Sales Bar
	if ($(".parent-pageid-1976").length > 0)
		$(window).scroll(function () { 
			if($(window).scrollTop() > 125)
			{
				$("#sales-bar-basic").css({
					"position" : "fixed",
					"z-index" : "10"
				});
			} else {
				$("#sales-bar-basic").css({
					"position" : "absolute",
					"z-index" : "10"
				});
			}
	    });
	    
    
    // About Page Slider
    if ($(".slider").length > 0)
    	slideInit();
    
    // About Page Slider
    if ($(".fader").length > 0)
    	fadeInit();
    
    // Sidebar Ajax
    if ($("#flickrpool").length > 0)
    	loadFlickr();
    	
    if ($("#tweets").length > 0)
    	loadTweets();
		
	$(".iframe").fancybox({
		"frameWidth" : 450,
		"frameHeight" : 600,
		"centerOnScroll" : false
	});
	
	
	$('#search input[type="text"]')
	.focus(function() {
		if ($(this).val() === 'Search..') {
			$(this).val('');
		}
	})
	.blur(function() {
		if ($(this).val() === '') {
			$(this).val('Search..');
		}
	});

});

function loadFlickr() {


	$.ajax({
		type:'GET',
		url:"http://api.flickr.com/services/feeds/groups_pool.gne",
		data:"id=837686@N22&lang=en-us&format=json&jsoncallback=?",
		success:function(feed) {

		    // Create an empty array to store images 
            var thumbs = []; 
 
            // Loop through the items 
            for(var i=0, l=feed.items.length; i < l && i < 12; ++i)  
            { 
        		var img = feed.items[i].media.m.replace(/^(.*?)_m\.jpg$/, 
        			'<img src="$1_s.jpg"' ); 
        			
        		img = '<a href="' + feed.items[i].link + '">' + img + ' alt="' +
        		feed.items[i].title + '" title="' + 
        		feed.items[i].title + '" /></a>';
        			
        		thumbs.push('<li>' + img + '</li>');
            } 
 
            // Display the thumbnails on the page 
            $("#flickrpool").hide().html(thumbs.join('') + '').fadeIn();
            $("#flickrpool li:nth-child(3n)").addClass("endrow");

		},
		dataType: 'jsonp'
	});

}




function loadTweets() {

	// Make the JSON call
	$.ajax({
		type:'GET',
		url:"http://search.twitter.com/search.json",
		data:"q=littlephotoshop",
		success:function(feed) {
			
			// Sucessful call, lets get the tweets
			var tweets = [];
			
			for(var i=0, l=feed.results.length; i < l && i < 8; ++i) 
			{
				
				// Autoformat links into the tweet
				var tweet_details = feed.results[i].text.split(" ");
				
				for (var j=0; j<tweet_details.length; j++) {
					if (tweet_details[j].charAt(0) === "@")
					{
						if (tweet_details[j].charAt(tweet_details[j].length-1) === ":")
						{
							link = tweet_details[j].substring(1, tweet_details[j].length-1);
						} else {
							link = tweet_details[j].substring(1);
						}
						var t = '<a href="http://www.twitter.com/' + 
								link + '">' + tweet_details[j] + '</a>';
						tweet_details[j] = t;
					} else if (tweet_details[j].substring(0, 7) === "http://")
					{
						var t = '<a href="' + tweet_details[j] + 
								'">' + tweet_details[j] + '</a>';
						tweet_details[j] = t;
					} else if (tweet_details[j].charAt(0) === "#")
					{
						var t = '<a href="http://twitter.com/search?q=' + tweet_details[j] + 
								'">' + tweet_details[j] + '</a>';
						tweet_details[j] = t;
					}
				}
				
				// Build the formatted Tweet for output
				var tweet = '<li class="tweet" style="background: url(' + 
							feed.results[i].profile_image_url + ') 0px 0 no-repeat;">' + 
							'<h4>' + feed.results[i].from_user +' says:</h4>' + 
							'<p>'  + tweet_details.join(' ') +  '</p>' +
							'</li>'; 
							
				// Add it to our array
				tweets.push(tweet);
			}
			
			// output the stream to the page
			$("#tweets").hide().html(tweets.join('')).fadeIn();

		},
		dataType: 'jsonp'
	});

}

/**
 * @author Alexander Farkas
 * v. 1.1
 */

(function($){
	
	if(!document.defaultView || !document.defaultView.getComputedStyle){
		var oldCurCSS = jQuery.curCSS;
		jQuery.curCSS = function(elem, name, force){
			if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style && style[ name ] ){
				return style[ name ];
			}
			return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
		};
	}
})(jQuery);

(function($) {
	
	function toArray(strg){
		strg = strg.replace(/left|top/g,'0px');
		strg = strg.replace(/right|bottom/g,'100%');
		strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
		var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
		return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
	}
	
	$.fx.step. backgroundPosition = function(fx) {
		if (!fx.bgPosReady) {
			
			var start = $.curCSS(fx.elem,'backgroundPosition');
			if(!start){//FF2 no inline-style fallback
				start = '0px 0px';
			}
			
			start = toArray(start);
			fx.start = [start[0],start[2]];
			
			var end = toArray(fx.options.curAnim.backgroundPosition);
			fx.end = [end[0],end[2]];
			
			fx.unit = [end[1],end[3]];
			fx.bgPosReady = true;
		}
		
		var nowPosX = [];
		nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
		nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
		fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

	};
})(jQuery);



function slideInit() {

	slider = $(".slider");
	slideContent = $(".slider ul");
	
	maxSlides = (slideContent.children().length);
	
	if (maxSlides > 0)
	{
		// Clone the first element to the last block to make sure it repeats infinitely
		slideContent.children().filter(':last').after(slideContent.children().filter(':first').clone());
	
		var slideTimer = window.setInterval("nextSlide()", 6000);
	}
}

function nextSlide() {

	currentSlide ++;
	
	if (currentSlide > maxSlides)
	{
		currentSlide = 1;
		slideContent.css("left", "0px");
	}
	
	var distance = currentSlide * 635;
	slideContent.animate({"left" : "-" + distance + "px"}, 500);

}



function fadeInit() {

	slider = $(".fader");
	slideContent = $(".fader ul");
	
	slideContent.children().hide();
	
	maxSlides = (slideContent.children().length);
	
	if (maxSlides > 0)
	{
		slideContent.children().eq(0).fadeIn();
		var slideTimer = window.setInterval("nextFade()", 12000);
		var slideTimer2 = window.setTimeout("subFade()", 6000);
	}
}

function nextFade() {

	currentSlide ++;
	
	if (currentSlide >= maxSlides)
	{		
		slideContent.children().eq(currentSlide-1).fadeOut(function() {
	
			slideContent.children().eq(0).fadeIn();
	
		});
		
		currentSlide = 0;
		
	} else {
	
		slideContent.children().eq(currentSlide-1).fadeOut(function() {
	
			slideContent.children().eq(currentSlide).fadeIn();
	
		});
	
	}
	
	if (currentSlide == 0 || currentSlide == 2 || currentSlide == 4) {
		var slideTimer2 = window.setTimeout("subFade()", 6000);
	}

}

function subFade() {

	currentSlide ++;
	slideContent.children().eq(currentSlide).fadeIn(1500, function() {
	
		slideContent.children().eq(currentSlide-1).hide();
	
	});

}


function contactForm() {
		var dataString = $("form").serialize();
	
		var fullname = $("#name").val();
		var email = $("#email").val();
		
		// Validate all fields
		if (fullname == "") {
			alert("Please Enter Your Name.");
			return false;
		}
		
		if (email == "") {
			alert("Please Enter Your Email Address.");
			return false;
		}
		
		// Build Ajax Query
		
		$("#theform").fadeOut(function() {
		
		
			$("#loadingbar").fadeIn(function() {
			
			
				$.ajax({  
		  			type: "POST",  
		  			url: "/process.php",  
		  			data: dataString,  
		  			success: function(msg) {
		  			
		  				$("#loadingbar").fadeOut(function() {
			  				$("#theform").html("<h3>Thanks</h3><p> Your E-Mail enquiry has been sent. We will be in touch as soon as possible.</p><p>- The Little Photoshop Team</p>").fadeIn();
			  			});
		
		   		   	}  
				});			
			
			
			});
		
		});
		
		return false;

}