/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


/* fus-ing functions */
function fusser( fus ) {
	user_version = $.cookie('ppVersion');
	$('#'+fus).load(surl+'/about/'+fus+'/ .fus-content', 
		function(){
			$('#'+fus).not('.admin_blurb').slideDown('fast');
			$('#throb-'+fus).remove();
			$('.fus').not('.loaded').each(function(){
				this_fus = $(this).attr('id');
				$(this).addClass('loaded');
				fusser( this_fus );
			});
			fus_cleanup( this_fus );
		});
}
function fus_cleanup( this_fus ) {
	$('.ftp_box').not(':first').remove();
	$('.permissions_box').not(':first').remove();
	$('.video-tutorial span').css('opacity', .60); // click here overlay
	$('.video-tutorial').hover(function(){
		$(this).children('span').animate({opacity:.85}, 150);
	}, function(){
		$(this).children('span').animate({opacity:.60}, 150);
	});
	$('.hidden img').each(function(){
		if ($(this).attr('width') > 550 ) $(this).attr('width', 550);
	});
	/* mac/pc */
	if ( $('.Mac').length ) {
		function show_correct( choice ) {
			if (choice == 'Both') return;
			$('.Mac, .PC').not('.'+choice).hide();
		}
		var choice = '';
		if ( $.cookie('macpc') ) {
			show_correct($.cookie('macpc'));
		} else if ( !$('#macpc').length ) {
			var which_computer = '<div id="macpc" class="extra_box self-clear"><div class="computer_icon"></div><div class="extra_box_text">So that we can show you only the most useful information please tell us <strong>if you primarily use a Mac or a PC</strong>.  We will remember your choice.<a>Mac</a><a>PC</a><a>Both</a></div></div>';
			if ( !this_fus ) $('.page-title').after(which_computer);
			else $('#'+this_fus).prepend(which_computer);
			$('#macpc a').click(function(){
				show_correct($(this).text());
				$.cookie('macpc', $(this).text());
				$("#macpc")
					.css('height', $('#macpc').height())
					.empty()
					.html('<p style="font-size:120%;font-weight:700;text-align:center"><br />Got it. Thanks.</p>')
					.animate({opacity:1}, 1500, function(){$(this).fadeOut()});			
			});
		}
	}
}



/* chunker functions */
next_link = "<a class='next-chunk' href=''>next section &raquo;</a>";
prev_link = "<a class='prev-chunk' href=''>&laquo; prev section</a>";
function add_chunk_links( index ) {
	var next = prev =  '';
	if ( $('.chunker').eq(index+1).length ) {
		next=next_link;
		$('.support-form-wrapper').hide();
	}
	else $('.support-form-wrapper').show();
	if ( $('.chunker').eq(index-1).length ) prev=prev_link;
	$('.chunker').eq(index).append("<p class='chunk-links self-clear'>"+prev+next+"</p>");
}
/* contact form stuff */
function bind_contact_form_events(){
	$('form.support-form input[type=\'checkbox\'], div.support-form input[type=\'text\']').unbind();
	$('form.support-form input[type=\'checkbox\']').click(function(){
		if ( $(this).is(':checked') ) $("label[for='"+$(this).attr('id')+"']").removeClass('error');
	});
	$("form.support-form input[type='text']").blur(function(){
			if ( $(this).val() != '' && $(this).next().hasClass('error') ) $(this).next().remove();
	});
	$('form.support-form').unbind('submit');
	$('form.support-form').submit(function(){
		var thisform = $(this);
		var form_id = '#'+thisform.attr('id');
		var formparent = thisform.parent();
		var name = $('form.support-form #first_name').val(); 
		var blog_address = $('form.support-form #address').val();
		var email = $('form.support-form #email').val();
		//alert(name+blog_address+email);
		var error = false;
		
		// didn't check the required checkboxes
		if ( $(form_id+' input[type=\'checkbox\']').not(':checked').length ) {
			$(form_id+' input[type=\'checkbox\']').not(':checked').each(function(){
				$(form_id+" label[for='"+$(this).attr('id')+"']").addClass('error');
			});
			error = true;
		}
		
		// empty required field
		$(form_id+" input[type='text']").not('.required').each(function(){
			if ( $(this).val() == '' ) {
				if ( !$(this).next().hasClass('error') )
					$(this).after('<span class="error input-error">* this is a required field</span>');
				error = true;
			}
		});
		
		// check the email
		if ( !email.match(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/) ) {
			var email_input = $('form.support-form #email')
			if ( !email_input.next().hasClass('error') )
				email_input.after('<span class="error input-error">* must be valid email</span>');
			error = true;
		}
		
		
		// bail on errors
		if ( error ) return false;
		
		
		// set cookies to be curteous on return visit
		$.cookie('pp_user_name', name, {expires: 90, path: '/'});
		$.cookie('pp_user_email', email, {expires: 90, path: '/'});
		$.cookie('pp_user_blog_address', blog_address, {expires: 90, path: '/'});
		
		var contact_error = '<p style="color:red;">There was an <strong>error submitting your form</strong>. Please email us directly at tech@netrivet.com and notify us that the support form failed so we can look into it.</p>';
		var contact_success = '<p style="font-size:1.2em">Form submitted <strong>successfully</strong>, you will hear from us soon.</p><div id="WPPI"><p><img src="'+stheme+'/images/WPPI.jpg" /><span>Estimated response times may be off</span>While we\'re in Vegas at the <strong>WPPI tradeshow</strong>, we will still be responding to all support requests in the same business day, but the <strong>response times might be a little different from normal</strong>. Also, if you have a low-priority question, we may ask you to wait a couple days until we get back and things slow down for us.  Thanks for your understanding!</p></div>';
		formdata = thisform.serialize();
		formparent.css('height',formparent.height())
			.empty()
			.animate({height: '195px'},300)
			.prepend('<p>submitting...</p>');
		$.ajax({
			type: "POST",
			url: surl+"/wp-content/themes/support/includes/process-contact.php",
			data: formdata,
			error: function(xhr){
				formparent.empty().prepend(contact_error);
			},
			success: function(response){
				var msg = ( response == 1 ) ? contact_success : contact_error;
				formparent.empty().prepend(msg);
			}
		});
		return false;
	});
}

// poplate contact form with any existing cookies
function add_cookies_to_form() {
	// get any existing cookies
	name    = ( $.cookie('pp_user_name') )         ? $.cookie('pp_user_name')         : "";
	email   = ( $.cookie('pp_user_email') )        ? $.cookie('pp_user_email')        : "";
	address = ( $.cookie('pp_user_blog_address') ) ? $.cookie('pp_user_blog_address') : "";
	// add any cookies to form fields
	$('form.support-form #first_name').val(name);
	$('form.support-form #email').val(email);
	$('form.support-form #address').val(address);
}

$(document).ready(function(){
			
	fus_cleanup(); // clean up redundant, fussed in items
	
	/* contact forms */
	bind_contact_form_events();
	add_cookies_to_form();
	// ajax loaded contact forms
	$('.load-fus-contact').live('click', function(){
		var this_click = $(this);
		var this_fus = this_click.parent().parent().attr('id');
		this_click.text('Loading...');
		this_click.next().load(surl+'/about/'+this_fus+'/ div.support-form', function(){
			bind_contact_form_events();
			add_cookies_to_form();	
			this_click.fadeTo(400,0,function(){
				$(this).animate({opacity:0},300,function(){$(this).slideUp('fast');});
			});
		});
	});
		
	/* fus */
	$('.fus-click').live("click", function(){
		fus_click = $(this);
		the_fus = fus_click.attr('fus');
		if (!fus_click.hasClass('loaded')) { // click to ajax load fus
			fus_click.addClass('loaded');
			if ($('#'+the_fus).length) { // same fus already open on this page
				$('#'+the_fus).remove();
				$('#fus-click-'+the_fus).removeClass('fus-open');
			}
			var fussy_html = "<span id='throb-"+the_fus+"' class='throbber'>&nbsp;</span><div class='fus hidden' id='"+the_fus+"' style='display:none;'></div>";
			if ( fus_click.parents('.extra_box').length ) { // fus inside gotcha box
				fus_click
					.before("<span class='place_holder'></span>")// add placeholder for replacing fus-click later
					.addClass('translated')
					.insertAfter(fus_click.parents('.extra_box'))
					.end()
					.after(fussy_html);
			} else {
				$(this).after(fussy_html);
			}
			fusser( the_fus );
			$(this).addClass('fus-open');
			return false;
		} else { // click to minimize and remove ajax loaded fus
			if (fus_click.hasClass('translated')) {
				fus_click.removeClass('translated').insertAfter('.place_holder');
				$('.place_holder').remove();
			} else if ( fus_click.parents('.gotcha_box').length ) {
				fus_click
					.before("<span class='place_holder'></span>")// add placeholder for replacing fus-click later
					.addClass('translated')
					.insertAfter(fus_click.parents('.extra_box'));
			}
			$(this).toggleClass('fus-open').removeClass('loaded');
			$('#'+the_fus).slideUp( 500, function(){
				$(this).remove();
			});
			return false;
		}
	});	
	$('.fus-closer').live("click", function(){
		fus_click = $(this).parent().parent().siblings('.fus-click');
		the_fus = fus_click.attr('fus');
		click_offset = fus_click.offset().top;
		scroll_win = $(window).scrollTop();
		if (fus_click.hasClass('translated')) {
			fus_click.removeClass('translated').insertAfter('.place_holder');
			$('.place_holder').remove();
		} else if ( fus_click.parents('.gotcha_box').length ) {
			fus_click
				.before("<span class='place_holder'></span>")// add placeholder for replacing fus-click later
				.addClass('translated')
				.insertAfter(fus_click.parents('.extra_box'));
		}
		fus_click.toggleClass('fus-open').removeClass('loaded');
		if ( click_offset < scroll_win ) {
			/*debug*/
			//alert('offset= '+click_offset+', cscroll= '+scroll_click+', wscroll= '+scroll_win+', wheight= '+height_win);
			//return false;
			$.scrollTo(fus_click, 500, {over:-5, onAfter:function(){
				$('#'+the_fus).slideUp( 500, function(){
					$(this).remove();
				});
			}});
			return false;
		} else {
			$('#'+the_fus).slideUp( 500, function(){
				$(this).remove();
			});			
		}
	});
	
	/* multi-fus stuff */
	//resize images to fit in #multi_viewer div
	$('#multi_viewer p img').each(function(){
		if ($(this).attr('width') > 560) $(this).attr('width', 560);
	});
	
	//select and show the "pick one" fus on page load
	$('#fus_selector').each(function(){
		this.selectedIndex=0;
	});
	$('#multi_viewer div.pick_one').show();
	
	//display the selected fuss when the select box value changes
	$('#fus_selector').change(function(){
		fus_class = "." + $('#fus_selector option:selected').attr('rel');
		//fadeOut currently showing fus
		$('#multi_viewer div.show').removeClass('show').fadeOut(300, function(){ //CALLBACK
			//fadeIn selected fus
			$(fus_class).addClass('show').fadeIn(300);				
		});
	});
	
	/* chunker stuff */
	if ( $('.chunker').length ) { // only if there are chunks
		hash = window.location.hash.substr(1);
		if ( hash ) { // load hash if requested
			var this_chunk = $(".chunker[rel='"+hash+"']");
			this_chunk.show();
			var index = $('.chunker').index(this_chunk);
			add_chunk_links(index);
		} else { // or show first chunk
			$('.chunker:first').show();
			add_chunk_links(0);
		}		
		$('.chunk-links a').live('click', function(){ // chunk navigation clicks
			this_click = $(this);
			parent_chunker = this_click.parent().parent();
			index = $('.chunker').index(parent_chunker);
			new_chunk = (this_click.hasClass('next-chunk')) ? index+1 : index-1;
			$.scrollTo( 0, 500, {onAfter:function(){
				parent_chunker.fadeOut(300, function(){
					$('.chunk-links').remove();
					$('.chunker').eq(new_chunk).fadeIn(300, function(){
						window.location.hash = $(this).attr('rel');
						add_chunk_links(new_chunk);
					});
				});
			}});
			return false;
		});
	}
	
	/* video tutorials */
	$('.video-tutorial, .hidden-video').live("click", function(){ 
		thisclick = $(this);
		var embedcode = "<div class='video-tutorial'><embed src='"+surl+"/wp-content/uploads/videos/flvplayer.swf?file="+thisclick.attr('source')+"&#038;autoStart=true' width='600' height='473' quality='high' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed></div>";
		var lofi = ( thisclick.hasClass('lofi') ) ? '<p>slow internet connection?  switch to lower-quality, faster-loading video by <a>clicking here</a></p>' : '';
		embedcode = '<h3>'+thisclick.attr('title')+'</h3>' + embedcode + lofi;
		lightbox(embedcode, 600, 500);
		
	});
	$('#overlay, #lb-holder .close').live('click',function(){  // close video
		$('#lb-holder').fadeOut(200,function(){
			$('#overlay').fadeOut(200,function(){
				$(this).remove();
				$('#lb-holder').remove();
			});
		});
	});
	$('#lb-holder p a').live('click',function(){  // switch to lofi
		$(this).parent().remove();
		var embed = $('#lb-holder').html();
		embed = embed.replace('.flv', '_lofi.flv');
		$('#lb-holder').empty().html(embed);
	});
	
	
	/* admin menu stuff */
	$('#wp-intro').addClass('show').show();
	
	$('#adminmenu a').mouseover(function(){
		$(this).not('.tab-selected').parent('li').addClass('hover');
	}).mouseout(function(){
		$(this).parent('li').removeClass('hover');
	});
	$('#adminmenu .wp-menu-toggle').mouseover(function(){
		$(this).parent('li').addClass('hover');
	}).mouseout(function(){
		$(this).parent('li').removeClass('hover');
	});	

	$('#adminmenu a.tab').click(function(){
		var $this = $(this);
		var $show = $('.show').length;
		var id = $(this).attr('fus');
		$('.tab-selected').removeClass('tab-selected');
		$('.selected').removeClass('selected');
		$('.current').removeClass('current');
		$(this).addClass('tab-selected').parents('li').addClass('selected').end().siblings('.wp-submenu').slideDown('fast').parent('li').addClass('open');
		if ( $show == 0 ) {
			$('#'+id).addClass('show').fadeIn(300);			
		} else {
			$('#wp-admin-content .show').removeClass('show').fadeOut(300,function(){
				$('#'+id).addClass('show').fadeIn(300);			
			});
		}
	});
	$('#adminmenu .wp-menu-toggle').click(function(){
		$(this).parents('li').toggleClass('open').end().siblings('.wp-submenu').slideToggle(300);
	});
	$('.wp-submenu a').click(function(){
		var $this = $(this);
		var $show = $('.show').length;
		var id = $(this).attr('fus');
		$('.current').removeClass('current');
		$('.selected').removeClass('selected');
		$this.parent().parent().parent().parent().addClass('selected');
		$(this).addClass('current');
		if ( $show == 0 ) {
			$('#'+id).addClass('show').fadeIn(300);			
		} else {
			$('#wp-admin-content .show').removeClass('show').fadeOut(300,function(){
			$('#'+id).addClass('show').fadeIn(300);			
			});
		}
	});
	
	// post and fus edit links
	$('.edit-link a').live('click', function(){ 
		$(this).attr('target', '_blank');
	});
	
	// show and hide option paths
	$('.where').live("click", function(){
		$(this).siblings('.path').slideToggle(400);
	});
});
