/* cookie plugin http://tinyurl.com/ynlz46 */
jQuery.cookie=function(name,value,options){if (typeof value != 'undefined') {options = options || {};if (value === null) {value = '';options = $.extend({}, options);options.expires = -1;}var expires = '';if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {var date;if (typeof options.expires == 'number') {date = new Date();date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));} else {date = options.expires;}expires = '; expires=' + date.toUTCString();}var path = options.path ? '; path=' + (options.path) : '';var domain = options.domain ? '; domain=' + (options.domain) : '';var secure = options.secure ? '; secure' : '';document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');} else {var cookieValue = null;if (document.cookie && document.cookie != '') {var cookies = document.cookie.split(';');for (var i = 0; i < cookies.length; i++) {var cookie = jQuery.trim(cookies[i]);if (cookie.substring(0, name.length + 1) == (name + '=')) {cookieValue = decodeURIComponent(cookie.substring(name.length + 1));break;}}}return cookieValue;}};


/* lightbox function */
function lightbox(embed, width, height, opacity, callback, callback_parameter) {
	
	// store initial values for use later
	css_width = width;
	css_height = height;
	
	// converts width/height to strings for testing
	width = width+'';
	height = height+'';
	
	// if no opacity set, load default value
	css_opacity = (opacity) ? opacity : .88;
	
	/* calcutating centered lightbox placement based on width and height of content */
	// if: '%' present in width variable
	if ( width.search(/%/) != '-1' ) {
		
		// returns location of '%'
		percent = width.search(/%/);
		
		// removes '%' from variable
		width = width.slice(0,percent);
		
		// converts width value to decimal percentage
		if ( width.length == 1 ) {
			width = '.0'+width;
		} else if ( width.length == 2 ) {
			width = '.'+width;
		} else {
			width = 1;
		}
		
		// calculate the 'left' dimension based on percentage to center the div horizontally
		var insertleft = ($(document).width() / 2) - (($(document).width()*width) / 2);
		
	// if: no '%' present in height variable
	} else {
		
		// calculate the 'left' dimension based on pixels to center the div horizontally
		var insertleft = ($(document).width() / 2) - (width / 2); 
	}
	
	// if: '%' present in height variable
	if ( height.search(/%/) != '-1' ) {
		
		// returns location of '%'
		percent = height.search(/%/);
		
		// exctracts value minus '%'
		height = height.slice(0,percent);
		
		// converts height value to decimal percentage
		if ( height.length == 1 ) {
			height = '.0'+height;
		} else if ( height.length == 2 ) {
			height = '.'+height;
		} else {
			height = 1;
		}
		
		// calculate the 'top' dimension based on percentage to center the div vertically
		var inserttop = ($(window).height() / 2) - (($(window).height()*height) / 2) + $(window).scrollTop();
		
	// if: no '%' present in height variable
	} else {
		
		// calculate the 'top' dimension based on pixels to center the div vertically
		var inserttop = ($(window).height() / 2) - (height / 2) + $(window).scrollTop();
		inserttop = ($(window).height() < css_height+10) ? 10 : inserttop;
	}
	/* end calcutating lightbox placement based on width and height */

	$('<div id="overlay"></div><div id="lb-holder"></div>').prependTo('body');
	$('#overlay').css({
		opacity: 0,
		height: $(document).height(),
		width: '100%'
	}).animate({opacity: css_opacity}, 400, 'swing', function(){
		$('#lb-holder').show().html('<span class="close">[x]</span>'+embed).css({
			top: inserttop,
			left: insertleft,
			width: css_width,
			height: css_height
		});
		if (callback) {
			callback(callback_parameter);
		}
	});
}

/* Bind rollover event to lightboxed HTML */
function video_cleanup(){
	
	// remove default lightbox closer
	$('#lb-holder span.close').remove();
	
	// click here overlay
	$('.video-tutorial span').css('opacity', .60);
		$('.video-tutorial').hover(function(){
		$(this).children('span').animate({opacity:.85}, 150);
	}, function(){
		$(this).children('span').animate({opacity:.60}, 150);
	});
}

/* Tells user their Prophoto version cookie and allows them to change it */
function print_version_notification() {
	user_version = $.cookie('ppVersion');

	if ( !( $.cookie('ppVersion') ) ) {
		version_notification_message = "Are you currently a ProPhoto user? <a class='set-prophoto-version-cookie'>Click here</a> to tell us what version."
	} else {
		user_version_pretty	= user_version.replace(/p/g, 'P');
		version_notification_message = "Our system shows you are a<span id='user-version'> "+user_version_pretty+" </span>user. Not correct? <a class='set-prophoto-version-cookie'>Click here</a>";
	}
	$('#cookie-notification').html(version_notification_message);
}

/* Lightbox window where user can set their ProPhoto version cookie */
function load_user_version_options() {
// html for lightbox: message and buttons for selecting theme version
	message = ($('body').hasClass('home'))
			  ? 'Before we direct you to support, please tell us what version of the ProPhoto theme you are using.'
			  : 'Telling us your ProPhoto version will ensure that you are directed to support that is relevant to you.';
	ppversion = "<div id='version-options'>"+ message +"<div id='pre-purchase'>If you have questions but have not yet purchased the Prophoto theme, <a href='http://www.prophotoblogs.com/faqs'>click here</a></div><div id='version_button_wrap'><span id='version2' class='version_button'><a id='pp2' name='prophoto2'>Prophoto 2.x</a></span><span id='version3' class='version_button'><a id='pp3' name='prophoto3'>Prophoto 3.x</a></span></div><div id='version-help'><a>How do I know what version I have?</a></div><div id='v-help-text'><p>If you purchased the Theme since December 2008, <strong>you are using ProPhoto 2.x</strong>. If you purchased prior to that, follow the steps below:</p><br /><p>1. Login to your blog admin area<br />2. Go to either 'Appearance' > 'Themes', or 'Design' > 'Themes' (for older Wordpress versions).<br />3. The title of your Prophoto theme will tell you the version</p></div></div>";

	// lightbox in cookie options
	lightbox(ppversion, 602, 300, .88, function(){
		$('#lb-holder span.close').remove();
	});
	
}

/* Handles setting cookie values when version options are selected */
function set_user_version_cookie( version, callback ) {	
	version_thanks = "<div id='version-thanks'><h3>Thanks!</h3>We'll remember this when you make future visits.</div>";
	//set variables for conditional callback
	is_wizard_page = ($('body').hasClass('home')) ? true : false;
	is_previous_wizard_user = ($.cookie('ppVersion')=='prophoto2' || $.cookie('ppVersion')=='prophoto3') ? true : false;
	user_has_changed_versions = ($.cookie('ppVersion')!=version);
	// set the cookie value
	$.cookie('ppVersion', version, {expires: 90, path: '/'});

	// fade out cookie options
	$('#version-options').fadeOut(300, function(){
		
		// add and display thank you message
		$('#version-options').html(version_thanks).fadeIn(300);
		print_version_notification();
		$('#version-options').animate({opacity:1}, 2000, function(){

			// If on Wizard and switching from ProPhoto 1
			if ((version != 'prophoto1') && ($('body').hasClass('pp1-redirect'))) {
				// remove the Prophoto 1 redirect link
				$('#pp1-redirect').remove();
				// show the Prophoto 2 support wizard
				$('#crumbs-and-back, #wizard-content').show();				
			}
			// fade out lightbox and overlay
			$('#overlay, #lb-holder').fadeOut(300, function(){
				$('#overlay, #lb-holder').remove();
				
				// fire optional callback
				if (is_wizard_page && !((version=='prophoto2' || version=='prophoto3')&&(is_previous_wizard_user))) {
					callback();
					
				// reload the page if version has changed
				} else { if (user_has_changed_versions) { window.location.reload(); } }
			});
		});
	});	
}


// subroutine for building the list of tweets from the .json data
function twitter_html( tweets ) {
	var twitter_html = [];
	for ( var i = 0; i<tweets.length; i++ ) {
		var username = tweets[i].user.screen_name;
		var status = tweets[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
	 		return '<a href="'+url+'">'+url+'</a>';
		}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
	 		return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
		});
		twitter_html.push('<span>'+status+'</span> <a class="twitter-time" href="http://twitter.com/'+username+'/statuses/'+tweets[i].id+'">'+twitter_time(tweets[i].created_at)+'</a>');
	}
	$('#tweet').html(twitter_html.join('')).css('height', 'auto');
}



// subroutine for returning nicely formatted time since tweeting
function twitter_time(time_value) {
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);

	if (delta < 60) {
		return 'less than a minute ago';
	} else if (delta < 120) {
		return 'about a minute ago';
	} else if (delta < (60*60)) {
		return (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if (delta < (120*60)) {
		return 'about an hour ago';
	} else if (delta < (24*60*60)) {
		return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if (delta < (48*60*60)) {
		return '1 day ago';
	} else {
		return (parseInt(delta / 86400)).toString() + ' days ago';
	}
}


/* function to retrieve a testimonial from db */
function load_random_testimonial(){
	
	// fadeOut current text and add throbber
	$('#testimonial-button span').html('loading...').fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1).fadeTo(200, .5).fadeTo(200, 1);
	$('#testimonial-outer').fadeOut(300, function(){
		// Retrieve the random feedback data
		$.ajax({
			url: "../wp-content/themes/marketing/includes/testimonial-loader.php?"+Math.floor(Math.random()*100000+1),
			type: 'GET',
			success: function(testimonial){
				testimonial_length = (testimonial.split("||"))[1];
				testimonial_height = Math.round((testimonial_length * 0.2)+200);
				testimonial_height = (testimonial_height > 300) ? testimonial_height : 300;
				testimonial = (testimonial.split("||"))[0];
				// turn off button throbber and show retrieved feedback
				$('#testimonial-inner').html(testimonial);
				$('#testimonial-outer').fadeIn(300);
				if ($('#testimonial-button').hasClass('hide')){
					$('#testimonial-button').removeClass('hide');
				}
				$('#testimonial-wrapper').animate({width: '560px', height: testimonial_height}, 600);
				$('#testimonial-button').html('<span>view more random feedback</span>');
			},
			error: function(){
				var error_mssg = 'Sorry, we aren\'t able to retrieve feedback at the moment.  Please try again later.';
				// hide trobber and show error
				$('#testimonial-inner').html(error_mssg);
				$('#testimonial-button').html('<span>view more random feedback</span>');
				$('#testimonial-outer').fadeIn(300, function(){				
						$('#testimonial-button').removeClass('hide');
						$('#testimonial-wrapper').animate({width: '560px', height: '300px'}, 600);
				});
			}
		});	
	});
	if (('#testimonial-button.hide').length == 0){
		$('#testimonial-wrapper').css('height', 'auto');
	}
}

var HomepageLightbox = {
	lightbox : function(content_name){
		if (!HomepageLightbox.alreadyOpen()){
			HomepageLightbox.create(content_name)
		} else {
			HomepageLightbox.loadContent(content_name)
		}
	},
	create : function(content_name){
		var dheight = $(document).height();
		$('<div id="overlay"></div><img id="throbber" src="'+mtheme+'/images/throbber.gif"><div id="insert"><div class="arrow-wrap"><a class="gallery-arrow disabled" id="gallery-arrow-prev"/></a></div><div id="home-view-port"></div><div class="arrow-wrap"><a class="gallery-arrow" id="gallery-arrow-next"/></a></div></div>').prependTo('body');
		$('body').addClass('lightboxed '+content_name)
		$('#overlay').css({
			opacity: 0,
			height: dheight,
			width: '100%'
		}).animate({opacity: .86}, 400, 'swing', function(){
			var dwidth = document.body.clientWidth;
			var wheight = $(window).height();
			var divwidth = (content_name == 'overview-video')
			var insertleft = (dwidth / 2) - 490+'px';
			var divheight = 534
			var inserttop = ((wheight - divheight) / 2) + $(window).scrollTop();
			if ( wheight < 534 ) {
				inserttop = 9 + $(window).scrollTop();
			}
			$('<a id="closeout"></a>').prependTo('#insert');
			$('#insert').css({
				//left: insertleft,
				//top: inserttop
				left: '28px',
				top: '16px'
			});
			HomepageLightbox.loadContent(content_name);
		});		
	},
	loadContent : function(content_name){
		$('#home-view-port').empty();
		$('body').removeClass('overview-video customize gallery share').addClass(content_name);
		// IF: video
		if (content_name == 'overview-video') {
			// add class for hiding gallery navigation elements
			file_name = content_name+'.php';
		// IF: screenshots
		} else {
			file_name = content_name+'-screenshots.php';
		}
		$('#throbber').show();
		$('#home-view-port').load(mtheme+'/includes/homepage-lightbox.php?content_name='+content_name, '', function(){
			$('#throbber').hide();
			$('#home-view-port, #insert').fadeIn(600);			
		});
	},
	switchVideo : function(){
		$('#overview-qt').empty();
		$("<div class='video-tutorial-inner'><embed src='"+surl+"/wp-content/uploads/videos/flvplayer.swf?file="+surl+"/wp-content/uploads/videos/overview/overview-small.flv&#038;autoStart=true' width='600' height='473' quality='high' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></div>").appendTo('#overview-qt');
		$('#version-switch').fadeTo('slow', 0);
	},
	close : function(){
		$('#insert').fadeOut(300, function(){
			$('body').removeClass('hide-gallery-buttons').removeClass('lightboxed');
			$('#overlay').animate({opacity: 0}, 300, function(){
				$('#overlay, #throbber, #insert').remove();
			});
		});
	},
	showThumbs : function(){
		$('#thumb-overlay').fadeOut(300);
	},
	alreadyOpen : function(){
		return $('body').hasClass('lightboxed');
	}
};

$(document).ready(function() {
	

			
	jQuery.getScript( 'http://twitter.com/statuses/user_timeline/prophotoblogs.json?callback=twitter_html&count=1' );

	// define global paths for js
	mtheme = $('#footer').attr('mtheme');
	stheme = $('#footer').attr('stheme');
	murl   = $('#footer').attr('murl');
	surl   = $('#footer').attr('surl');
	
	// set version cookie from links we know indicate user is on p2
	if (/p2=/.test(window.location.href)) $.cookie('ppVersion','prophoto2', {expires: 90, path: '/'});
	
	/* Load version cookie handling for support pages */
	if ($('body').hasClass('support')) {	
		
		// if: no ppVersion cookie set
		if ( !( $.cookie('ppVersion') ) ) {
			// Lightbox version selector
			load_user_version_options();
		}
		
		print_version_notification()

		// load version cookie options from within version notification message
		$('.set-prophoto-version-cookie').live('click', function(){
			load_user_version_options();
		});
	
		// Click on Prophoto 2 cookie button
		$('#pp2').live('click', function(){
			set_user_version_cookie( jQuery(this).attr('name'), function(){
				// load Prophoto2 intro video after cookie handling
				lightbox(pp2_intro, 700, 660, .88, video_cleanup);
			});
		});

		// Click on Prophoto 3 cookie button
		$('#pp3').live('click', function(){
			set_user_version_cookie( jQuery(this).attr('name'), function(){
				lightbox(pp2_intro, 700, 660, .88, video_cleanup)
			});
				// load Prophoto2 intro video after cookie handling
		});
	
		// Click on 'what version' help link	
		$('#version-help a').live('click', function(){
			$this = $(this);

			// fadeOut 'what version' link
			$this.parent('#version-help').fadeOut(300, function(){

				// grow lightbox height to reveal help mssg
				$('#version-options').animate({height:'+=150'}, 300);

				// fade in help mssg
				$this.parent('#version-help').next().fadeIn(300);
			});
		});
	}
	
	
	// preload the ajax throbbers
	$('<img>').attr('src', mtheme+'/images/throbber.gif');
	
	// faq hide-show slider
	$('.slide-click').click(function(){
		var $this = $(this);
		if ( $this.next().hasClass('open') ) {
			$this.removeClass('open').next('.inner-chunk').removeClass('open').slideUp(400);			
		} else {
			$this.addClass('open').next('.inner-chunk').addClass('open').slideDown(400);
		}
	});
	
	// switch video version
	$('p#version-switch a').live('click', function(){
		HomepageLightbox.switchVideo();
	});
	
	// load lightboxed content on click
	$('body.home .lightbox-button').live('click', function(){
		var content_name = $(this).attr('rel');
		$('.active').removeClass('active');
		$('#'+content_name).parents('li').addClass('active');
		HomepageLightbox.lightbox(content_name);
	});

	// close the lightbox on closeout button click
	$('#closeout').live('click', function(){
		$('.active').removeClass('active')
		HomepageLightbox.close();
	});

	// sidebar-gallery mini preview ajaxy thing
	$("#sidebar-viewer ul li img").click(function(){
		var thisid = $(this).attr('id');
		var dheight = $(document).height();
		var dwidth = $(document).width();
		var wheight = $(window).height();
		var insertleft = (dwidth / 2) - 265;
		$(this).parent().addClass('active');
		$('<div id="overlay"></div><img id="throbber" src="'+mtheme+'/images/throbber.gif"><div id="insert" class="rounded"></div>').prependTo('body');
		$('#overlay').css({
			opacity: 0,
			height: dheight,
			width: '100%'
		}).animate({opacity: .86}, 400, 'swing', function(){
			$('#throbber').show();
			$('#insert').load(mtheme+'/includes/gallery.php #'+thisid, '', function(){
				var divheight = 534
				var inserttop = ((wheight - divheight) / 2) + $(window).scrollTop();
				$('#throbber').hide();
				if ( wheight < 534 ) {
					inserttop = 9 + $(window).scrollTop();
				}
				$('<a id="closeout"></a>').prependTo('#insert');
				$('#insert').fadeIn().css({
					left: insertleft,
					top: inserttop
				});
				$('#closeout').click(function(){
					$('#sidebar-viewer li').removeClass('active');
					$('#insert').fadeOut(300, function(){
						$('#overlay').animate({opacity: 0}, 300, function(){
							$('#overlay, #throbber, #insert').remove();
						});
					});
				});	
			});			
		});		
	});
	$('#sidebar-viewer li').mouseover(function(){
		$(this).addClass('hover');
	}).mouseout(function(){
		$(this).removeClass('hover');
	});
	$('.sb').mouseover(function(){
		$(this).addClass('sb-hover');
	}).mouseout(function(){
		$(this).removeClass('sb-hover');
	});
	
	
	// sidebar mini-galler slider
	$('.sb').click(function(){
		var $this = $(this);
		var id = $($this).attr('id');
		$('.sb').removeClass('sb-active');
		$($this).addClass('sb-active');
		var start = 0;
		if ( id == "sb_2" ) { start = -224; }
		if ( id == "sb_3" ) { start = -448; }
		var loccss = $('#sidebar-viewer ul').css('left');
		var loc = parseFloat(loccss, 10);				
		var offset = start - loc;			
		var toleft = offset + loc;				
		$('#sidebar-viewer ul').animate({left: toleft}, 800 );				
	});
	
	// buy now button rollovers
	$('.buy_btn').mouseover(function(){
		$(this).css('background-position', '-198px 0');
	}).mouseout(function(){
		$(this).css('background-position', '0 0');
	});

	// testimonial loader stuff
	$('#testimonial-button').click(function(){
		load_random_testimonial();
	});
				

	// uh, cuz i'm lazy and css3 is not supported by msie
	$('h2.entry-title a').parent().css('border', 'none');
	
	jQuery('#three-steps a').click(function(){return false;});
	
});