// Setup Plugins for ISVOnline
$(document).ready(function () {
	
	/**
	 * Tooltip Plugin
	 * 
	 * File: jquery.tools.min.js
	 * Website: http://flowplayer.org/tools/tooltip/index.html
	 */
	$('#nav-personal a.flag[title]').tooltip({
		position: 'center left',
		effect: 'slide',
		direction: 'left',
		delay: 3000,
		slideInSpeed: 500,
		slideOutSpeed: 500,
		slideOffset: 20
	}).trigger('mouseover').trigger('mouseleave').unbind('mouseover');
	
	/**
	 * Adds glow to cross site banner
	 */
	$('#xsite').hover(function(){
		$(this).stop(true, true).addClass('hover', 500);
	},function(){
		$(this).stop(true, true).removeClass('hover', 500);
	});
	
	$('#nav-personal li').hover(function(){
		$('ul', this).stop(true, true).slideDown();
	}, function(){
		$('ul', this).stop(true, true).slideUp();
	});
	
	/**
	 * Prints the current page. Used on check payments
	 */
	$('.printpage').live('click', function(e){
		window.print();
		e.preventDefault();
	});
	
	/**
	 * Removes suggested input hints from input boxes when focused
	 *
	 * File: jquery-1.4.2.min.js
	 */
	$('.hint').live('focus', function(){
		$(this).removeClass('hint').addClass('hinted').data('hint', $(this).val()).val('');
	});
	$('.hinted').live('blur', function(){
		if ($(this).val() == '') {
			$(this).removeClass('hinted').addClass('hint').val($(this).data('hint'));
		}
	});
	
	
	/**
	 * Slide toggles for FAQ and FLIGHTS
	 *
	 * File: jquery-1.4.2.min.js
	 */
	$('dl.js-toggle dt').live('click', function(){
		$(this).next('dd').slideToggle(500);
	});
	
	
	/**
	 * General Purpose SlideToggle. Currently used on FAQ tabs
	 *
	 * File: jquery-1.4.2.min.js
	 * Website: http://api.jquery.com/slideToggle/
	 */
	$('a.js-toggle, input:checkbox.js-toggle').live('click', function(e){
		if ($(this).attr('rel')) {
			$($(this).attr('rel')).slideToggle();
		} else {
			$($(this).attr('href')).slideToggle();
		}
		if (!$(this).is('input:checkbox')) {
			e.preventDefault();
		}
	});
	
	/**
	 * UI Datepicker for use to specify a date using a graphical interface
	 *
	 * File: ui/jquery-ui-1.8.4.custom.min.js
	 * Website: http://jqueryui.com/demos/datepicker/
	 */
	$('.date input, input.datepicker').live('click', function() { 
		$(this).datepicker({showOn:'focus'}).focus();
	});
	
	/**
	 * Form Submit Disable. Prevents the user from hitting the submit button multiple times
	 * 
	 * TODO: Prevents the form from submitting in Internet Explorer
	$(document).delegate('form', 'submit', function(){
	    $('input[type=submit]', this).attr('disabled', 'disabled');
	});
	 */ 

	/**
	 * Adds a tabbed interface
	 * 
	 * File: ui/jquery-ui-1.8.1.custom.js
	 * Website: http://jqueryui.com/demos/tabs/
	 */
	$('.tabs').tabs({
		select: function(event, ui) {
			var url, follow;
			url = $.data(ui.tab, "load.tabs")
			follow = typeof $(ui.tab).attr("data-follow");
			if (follow !== "undefined" && url) {
				window.location = url;
				return false;
			}
		},
		load: function(event, ui) {
			autoload(ui.panel);
		}
	});
	dontChange = false;
	if (parent.location.hash) {
		parent.location.hash = '';
		dontChange = true;
	}
	
	/**
	 * Adds tab changing events when links to the same page (just different tabs) are clicked.
	 * Only works in certain browsers supported by hashchange plugin
	 *
	 * File: jquery.a-hashchange.min.js
	 * Website: http://benalman.com/projects/jquery-hashchange-plugin/
	 */
	$(window).hashchange(function(){
		if (!dontChange) {
			$('.tabs').tabs('select', location.hash.replace(/^#/, ''));
		} else {
			dontChange = false;
		}
	});
	
	/**
	 * Fade in and out upon hover
	 *
	 * File: jquery-1.4.2.min.js
	 * Instructions: http://api.jquery.com/fadeTo/  http://api.jquery.com/fadeOut/
	 */
	$('.js-fade').live('mouseenter mouseleave', function(event){
		if (event.type == 'mouseout') {
			$('>img', this).stop(true, true).fadeTo(300, 1);
		} else if (event.type == 'mouseover') {
			$('>img', this).stop(true, true).fadeTo(500, 0.5);
		}
	});
	
	/**
	 * Sideshow
	 *
	 * Used in conjunction with the js-gallery to show extra text content in the floating side div.
	 */
	$('body').delegate('.js-sideshow', 'click', function(e){
		$($(this).attr('href')).stop(true, true).slideDown().siblings().stop(true, true).slideUp();
		e.preventDefault();
	});
	
	/**
	 * Configurator Flipper
	 *
	 * File: flip/jquery.flip.js
	 * Website: http://lab.smashup.it/flip/
	$('.flipper ul.opt-first > li > a').click(function(e){
		$('.flip').flip({
			direction:'rl',
			color:'#30380F',
			content:$(this).siblings(),
			onBefore: function(){
				$('.flipper .cancel').hide();
			},
			onEnd: function(){
				$('.flipper .cancel').fadeIn(700);
			}
		});
		$opt2 = $($(this).attr('href'));
		if (!$opt2.is(":visible")) {
			$opt2.siblings('.opt-second').slideUp(500,function(){
				$opt2.slideDown(1000);
			});
		}
		e.preventDefault();
	});
	$('.flipper ul.opt-second > li > a').click(function(e){
		$('.flip').flip({
			direction:'bt',
			color:'#30380F',
			content:$(this).siblings(),
			onBefore: function(){
				$('.flipper .cancel').hide();
			},
			onEnd: function(){
				$('.flipper .cancel').fadeIn(700);
			}
		});
		$opt2 = $('#' + $(this).attr('rel'));
		e.preventDefault();
	});
	original = $('.flip').clone().detach();
	$('.flipper .cancel').click(function(e){
		$(this).hide();
		$('.opt-second').slideUp(500);
		$('.flip').flip({
			direction:'lr',
			color:'#30380F',
			content:original
		});
		e.preventDefault();
	});
	 */
	
	/**
	 * Navigation Submenu
	 *
	 * HoverIntent creates a pause upon hover and a pause upon mouseOut, making the submenu easier for visitors to use
	 *
	 * File: jquery.hoverIntent.min.js
	 * Website: http://cherne.net/brian/resources/jquery.hoverIntent.html
	 */
	$("#nav-main li").hover(function(){
		$('ul', this).stop(true, true).slideDown(500);
	}, function(){
		$('ul', this).stop(true, true).slideUp(250);
	});
	 
	/**
	 * Fixed Static position Navigation menu. When the page is scrolled down the menu sticks to the top of the screen.
	 *
	 * Website: http://www.bennadel.com/blog/1810-Creating-A-Sometimes-Fixed-Position-Element-With-jQuery.htm
	 */
	// Get a reference to the message whose position we want to "fix" on window-scroll.
	var $nav = $('#navigation');
	if ($nav.length) {
		var origin = $nav.offset();
		// Bind to the window scroll and resize events. Remember, resizing can also change the scroll of the page.
		$(window).bind("scroll resize", function(){	
			// Get the current scroll of the window.
			var viewTop = $(this).scrollTop();
			// Check to see if the view had scroll down past the top of the placeholder AND that the message is not yet fixed.
			if ((viewTop > origin.top) && !$nav.is( ".fixed" )){
				$nav.addClass("fixed"); 
			// Check to see if the view has scroll back up above the message AND that the message is currently fixed.
			} else if ((viewTop <= origin.top) && $nav.is(".fixed")){
				$nav.removeClass("fixed");
			}
		});
	}
	 
	 /**
	  * Pretty Loader
	  *
	  * Displays a loading icon next to the cursor during ajax calls
	  *
	  * File: jquery/prettyLoader/jquery.prettyLoader.js
	  * Website: http://www.no-margin-for-errors.com/projects/prettyloader/
	  */
	 $.prettyLoader({
	 	loader: '/js/jquery/prettyLoader/ajax-loader.gif'
	 });
	 
	 autoload();

	$(".addOther").click(function(e) {
		var start = parseInt($("#ProjectAchievementProjectAchievementForm tr").length) + 1;
		e.preventDefault();
		var tableClass = "." + $(this).attr("data-category-table");
		var name = $(this).attr("data-other-name") || "Other";
		var units = $(this).attr("data-other-units") || "";
		var notes = $(this).attr("data-other-notes") || "";
		var hours = $(this).attr("data-other-hours") == "1" ? true : false;
		var col1 = $('<td></td>');
		var col2 = $('<td></td>');
		var col3 = $('<td></td>');
		var row = $('<tr></tr>');
		
		var hiddenCategoryName = '<input type="hidden" name="data[ProjectAchievementResponse]['+start+'][project_achievement_category_name]" value="'+$(this).attr("data-category-name")+'" id="ProjectAchievementResponse'+start+'ProjectAchievementCategoryName">';
		var hiddenOptionName = '<input type="hidden" name="data[ProjectAchievementResponse]['+start+'][project_achievement_option_name]" value="'+name+'" id="ProjectAchievementResponse'+start+'ProjectAchievementOptionName">';
		
		var quantityInput = '<div class="input text"><input name="data[ProjectAchievementResponse]['+start+'][quantity]" type="text" id="ProjectAchievementResponse'+start+'Quantity">';
		if (units !== "") {
			quantityInput = quantityInput + units;
		}
		quantityInput = quantityInput + "</div>";
		
		if (hours) {
			quantityInput = quantityInput + '<div class="input text"><input name="data[ProjectAchievementResponse]['+start+'][hours]" type="text" id="ProjectAchievementResponse'+start+'Hours"></div>';
		}
		
		var noteInput = '<div class="input text"><input name="data[ProjectAchievementResponse]['+start+'][note]" type="text" id="ProjectAchievementResponse'+start+'Note">';
		if (notes !== "") {
			noteInput = noteInput + "<p>" + notes + "</p>";
		}
		noteInput = noteInput + '</div>';
		
		col1.html(hiddenCategoryName + hiddenOptionName + name);
		col2.html(quantityInput);
		col3.html(noteInput);
		row.html(col1[0].outerHTML + col2[0].outerHTML + col3[0].outerHTML);
		$(tableClass).first().append(row[0].outerHTML);
		return false;
	});
});

/*
* Autoload function houses all of the jQuery that cannot be .live() binded, and must be called after the page is loaded
* 
* File: ISVOnline.js
*/
function autoload($scope) {
	if (!$scope) {
		$scope = $(document);
	}
	
	/**
	*Loads swf objects for HOME and ACHIEVEMENTS
	*
	*File: jquery.swfobject.1-1-1.min.js
	*Website: http://jquery.thewikies.com/swfobject
	*/
	(function(f,h,i){function k(a,c){var b=(a[0]||0)-(c[0]||0);return b>0||!b&&a.length>0&&k(a.slice(1),c.slice(1))}function l(a){if(typeof a!=g)return a;var c=[],b="";for(var d in a){b=typeof a[d]==g?l(a[d]):[d,m?encodeURI(a[d]):a[d]].join("=");c.push(b)}return c.join("&")}function n(a){var c=[];for(var b in a)a[b]&&c.push([b,'="',a[b],'"'].join(""));return c.join(" ")}function o(a){var c=[];for(var b in a)c.push(['<param name="',b,'" value="',l(a[b]),'" />'].join(""));return c.join("")}var g="object",m=true;try{var j=i.description||function(){return(new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}()}catch(p){j="Unavailable"}var e=j.match(/\d+/g)||[0];f[h]={available:e[0]>0,activeX:i&&!i.name,version:{original:j,array:e,string:e.join("."),major:parseInt(e[0],10)||0,minor:parseInt(e[1],10)||0,release:parseInt(e[2],10)||0},hasVersion:function(a){a=/string|number/.test(typeof a)?a.toString().split("."):/object/.test(typeof a)?[a.major,a.minor]:a||[0,0];return k(e,a)},encodeParams:true,expressInstall:"expressInstall.swf",expressInstallIsActive:false,create:function(a){if(!a.swf||this.expressInstallIsActive||!this.available&&!a.hasVersionFail)return false;if(!this.hasVersion(a.hasVersion||1)){this.expressInstallIsActive=true;if(typeof a.hasVersionFail=="function")if(!a.hasVersionFail.apply(a))return false;a={swf:a.expressInstall||this.expressInstall,height:137,width:214,flashvars:{MMredirectURL:location.href,MMplayerType:this.activeX?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}attrs={data:a.swf,type:"application/x-shockwave-flash",id:a.id||"flash_"+Math.floor(Math.random()*999999999),width:a.width||320,height:a.height||180,style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"opaque";delete a.fallback;delete a.hasVersion;delete a.hasVersionFail;delete a.height;delete a.id;delete a.swf;delete a.useEncode;delete a.width;var c=document.createElement("div");c.innerHTML=["<object ",n(attrs),">",o(a),"</object>"].join("");return c.firstChild}};f.fn[h]=function(a){var c=this.find(g).andSelf().filter(g);/string|object/.test(typeof a)&&this.each(function(){var b=f(this),d;a=typeof a==g?a:{swf:a};a.fallback=this;if(d=f[h].create(a)){b.children().remove();b.html(d)}});typeof a=="function"&&c.each(function(){var b=this;b.jsInteractionTimeoutMs=b.jsInteractionTimeoutMs||0;if(b.jsInteractionTimeoutMs<660)b.clientWidth||b.clientHeight?a.call(b):setTimeout(function(){f(b)[h](a)},b.jsInteractionTimeoutMs+66)});return c}})(jQuery,"flash",navigator.plugins["Shockwave Flash"]||window.ActiveXObject);
	
	
	/**
	 * Slide toggles for FAQ and FLIGHTS
	 *
	 * File: jquery-1.4.2.min.js
	 */
	$('dl.js-toggle dd, .js-hide', $scope).hide();
	
	
	
	/**
	 * Generates a zooming photo carousel used on the photo gallery tabs. Purchased online
	 *
	 * File: boutique/jquery.boutique_min.js
	 * Website: 
	 */
	$('.js-carousel', $scope).boutique({
		starter:			1,				// Which frame to start with
		speed:				600,			// Overall animation speed in ms
		hovergrowth:		0.15,			// How much the front item will enlarge on mouse-over in percentage
		behind_opac:		0.6,			// Opacity of the furter back items
		back_opac:			0.2,			// Opacity of the furthest back items
		behind_size:		0.7,			// Size of the further back images in percentage
		back_size:			0.4,			// Size of the furthest back images in percentage
		autoplay:			true,			// Autoplay on/off
		autointerval:		3500			// Autoplay interval in ms
	});

	/**
	 * Numbered Slideshow
	 * 
	 * File: anythingSlider/jquery.anythingslider.js
	 * Website: http://css-tricks.com/examples/AnythingSlider/ http://github.com/chriscoyier/AnythingSlider
	 */
	$('ul.js-slideshow', $scope).each(function(i, El){
		var width = null;
		var height = null;
		if ($(El).attr('rel')) {
			var dimensions = $(El).attr('rel').match(/\d+/g);
			width = dimensions[0];
			height = dimensions[1];
		}
		$(El).anythingSlider({
			easing: "easeInOutExpo",        // Anything other than "linear" or "swing" requires the easing plugin
			delay: 5000,                    // How long between slide transitions in AutoPlay mode
			hashTags: false,                // Should links change the hashtag in the URL?
			width: width,
			height: height,
			buildArrows: false
		});
	});
	$('a.js-slideshow', $scope).click(function(){
		$($(this).attr('rel')).anythingSlider($(this).attr('href').substring(1));
		e.preventDefault();
	});
	
	/**
	 * InnerFade Slideshow
	 *
	 * File: jquery.innerfade.js
	 * Website: http://medienfreunde.com/lab/innerfade/
	 */
	$('.js-fadeslideshow').innerfade();
	
	/**
	 * Gallery (Pikachoose)
	 * TODO: currently auto-rotate has been disabled so that the sideshow content sticks with the image. This should be addressed.
	 *
	 * File: pikachoose/pikachoose.js  plugins/  themes/
	 * Website: http://pikachoose.com/
	 */
	$('.js-gallery', $scope).each(function(i, El){
		var width = 75;
		var height = 60;
		if ($(El).attr('rel')) {
			dimensions = $(El).attr('rel').match(/\d+/g);
			width = dimensions[0];
			height = dimensions[1];
		}
		$(El).PikaChoose({
			autoPlay: false,
			show_prev_next: false,
			thumb_width: width,
			thumb_height: height
		});
	});
	
	/**
	 * Lightbox
	 * 
	 * File: prettyPhoto/jquery.prettyPhoto.js
	 * Instructions: http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/
	 */
	$('.js-litebox', $scope).prettyPhoto();
	
	
	/**
	 * Elegant Accordion
	 * 
	 * File:
	 * Website: http://tympanus.net/codrops/2010/04/26/elegant-accordion-with-jquery-and-css3/
	 */
	$('.js-accordion', $scope).eAccordion({
		easing: 'swing',		// Anything other than "linear" or "swing" requires the easing plugin
		delay: 6000,			// How long between slide transitions in AutoPlay mode
		animationTime: 1000,		// How long the slide transition takes
		expandedWidth: '60%'	// Width of the expanded slide
	});

	$('form.no-enter').each(function() {
		var self = $(this);
		self.keypress(function(e) {
			if (e.keyCode === 13 && e.target.tagName !== "TEXTAREA") {
				e.preventDefault();
				return false;
			}
		});
	});
	
	/**
	 * Not sure why this is here. Obviously not production code
	 */
	/*$.getScript('http://localhost/js/jquery/achievements/achievements.js' , function() {
	  achievements();
	});*/
	
	/**
	 * Autocomplete
	 * TODO develop autocomplete feature for School and State inputs
	 *
	 * Website: http://jqueryui.com/demos/autocomplete/
	$('.autocomplete', $scope).each(function(index,el){
		$(el).autocomplete({
			url: $(this).attr('rel')
		});
	});
	 */

	/**
	 * Lazy-Load Images so that page load times are reduced
	 * 
	 * TODO Currently not working on firefox (or at all?). Needs to be properly configured to work with plugins
	 *
	 * File: jquery.lazyload.js
	 * Website: http://github.com/tuupola/jquery_lazyload
	$('img', $scope).lazyload({
		effect: 'fadeIn',
		placeholder: '../../img/layout/banner-gradient.png',
		threshold: 100,
		failurelimit: 10
	});
	 */
	
	/**
	 * Lazy-Load Images so that page load times are reduced
	 * 
	 * TODO Currently not working on firefox (or at all?). Needs to be properly configured to work with plugins
	 *
	 * File: jquery.lazyload.js
	 * Website: http://github.com/tuupola/jquery_lazyload
	$('img').lazyload({
		effect: 'fadeIn',
		placeholder: '../../img/layout/banner-gradient.png',
		container: $('#container, .tabs, .anythingWindow, .js-carousel'),
		threshold: 100,
		failurelimit: 10
	});
	 */
}

/** 
 * TinyMCE Initialization. jQuery version preferred
 *
 * Website: http://tinymce.moxiecode.com/
 * /
tinyMCE.init({
	// General options
	mode : "textareas",
	theme : "advanced",
	plugins : "style,layer,table,advimage,advlink,inlinepopups,preview,media,searchreplace,contextmenu,paste,fullscreen,xhtmlxtras,template,advlist",

	// Theme options
	theme_advanced_buttons1 : "code,fullscreen,preview,|,search,replace,|,attribs,removeformat,|,bold,italic,underline,strikethrough,|,sub,sup,|,justifyleft,justifycenter,justifyright,justifyfull,blockquote,outdent,indent,bullist,numlist,styleselect,formatselect",
	theme_advanced_buttons2 : "undo,redo,|,cut,copy,paste,pastetext,pasteword,|,charmap,link,unlink,anchor,image,media,|,cleanup,template,restoredraft,|,tablecontrols,|,hr,visualaid",
	theme_advanced_buttons3 : "",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : true,

	// Example content CSS (should be your site CSS)
	content_css : "../css/layout.css",

	// Drop lists for link/image/media/template dialogs
	template_external_list_url : "lists/template_list.js",
	external_link_list_url : "lists/link_list.js",
	external_image_list_url : "lists/image_list.js",
	media_external_list_url : "lists/media_list.js",

	// Style formats
	style_formats : [
		{title : 'Slide Right', classes : 'right'},
		{title : 'Slide Left', classes : 'left'},
		{title : 'Red header', block : 'h1', styles : {color : '#ff0000'}},
		{title : 'Example 1', inline : 'span', classes : 'example1'},
		{title : 'Example 2', inline : 'span', classes : 'example2'},
		{title : 'Table styles'},
		{title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
	],

	// Replace values for the template plugin
	template_replace_values : {
		username : "Some User",
		staffid : "991234"
	}
});*/

