// JavaScript Document

$(document).ready(function() {
	// run init functions
	fixContainerHeight();
	toggleBoxes();
	popupLinks();
	makeSortable();
	buildTabs();
	if($('a.colorbox').length > 0) {
		$.getScript(siteRoot + '/assets/jquery.colorbox.min.js', function() {
			buildColorBox();
		});
	}
	jwEmbed();
	fixGooleSearchFrame();
	buildCarousel();
	searchBoxClear();
});



// --------------------------------------------------
// fix container height
function fixContainerHeight() {
	// set container height to 100%
	$('#container').css('height', $(window).height());
	// also set to resize on window resize
	$(window).bind('resize', function() {
		$('#container').css('height', $(window).height());
	});
}


// --------------------------------------------------
// toggle show / hide boxes
function toggleBoxes() {
	// retrieve all toggleSources
	var s = $('.toggleSource');
	// loop all
	s.each(function() {
		// wrap the contents in a link	
		$(this).wrapInner('<a href="" title="Expand / Collapse"></a>');
		// capture the next sibling with class toggleTarget and hide it
		var target = $(this).next();
		target.hide();
		var a = $(this).find('a');
		a.click(function(e) {
			// toggle the target box
			target.slideToggle('fast');
			// change the background image
			bgImg = a.css('background-image');
			if(bgImg.match('arrowDown.png')) 	newBgImg = bgImg.replace(/arrowDown.png/, 'arrowUp.png');
			else								newBgImg = bgImg.replace(/arrowUp.png/, 'arrowDown.png');
			a.css( { 'background-image' : newBgImg } );
			// prevent the link from firing
			e.preventDefault();
		});
	});	
}




// --------------------------------------------------
// popup window links
function popupLinks() {
	// retrieve all popup links
	var a = $('a.popup');
	// loop through the links
	a.each(function() {
		// as long as the "noicon" class is not set, set the image
		if(!$(this).hasClass('noicon')) {
			$(this).css({ 
				'background-image' 		: 	'url(' + siteRoot + '/images/popup.gif)',
				'background-position'	: 	'right center',
				'background-repeat'		:	'no-repeat',
				'padding-right'			: 	'12px',
				'margin-right'			: 	'5px'
			});
		};
		// capture the href and title for future use
		var href = $(this).attr('href');
		var title = $(this).attr('title');
		// add the popup behavior
		$(this).attr({
			'href'					: 	'javascript:popup(\'' + href + '\',\'newWin\', \'\');',
			'title'					:	title + ' [Opens in a new window]'
		});
	});
}
function popup(url,name,opt) {
	window.open(url,name,opt);	
}




// --------------------------------------------------
// make sortable lists
function makeSortable() {
	// get the lists to sort and make them sortable
	if($('.makeSortabls').length > 0) {
		$('.makeSortable').sortable({
			update: function() {
				// capture the id of the list and use it to target the hidden form field
				var id = $(this).attr('id');
				// if there is a hidden form field associated with the list update it with the list order
				if($('#new_' + id)) {
					var sortArray = ($(this).sortable('toArray'));
					// update the hidden form field with the updated order
					$('#new_' + id).val(sortArray);
				}
			}
		});
	}
}




// --------------------------------------------------
// build tabs
function buildTabs() {
	// if there is not a selected tab, set one
	$('.tabs').each(function() {
		var tabSelected = false;
		// build the tabs and corners
		$(this).children('li').each(function() {
			// if the current tab is selected, mark a flag
			if($(this).hasClass('selected')) tabSelected = true;
			$(this).prepend('<div class="tabLeft"></div>');							
			$(this).append('<div class="tabRight"></div>');
		});
		
		// if there was no selected tab, use the first one
		if(tabSelected != true) $(this).find('li:first-child').addClass('selected');
		
		// hide all tab content except the current one
		$(this).find('li a').each(function() {
			var href = $(this).attr('href');
			var targetId = href.replace('#','');	
			if($(this).parent('li').hasClass('selected')) oldTabId = targetId;
			else $('#' + targetId).hide();
			
			// as long as the noBorder class does not exist, add a border and padding to all content areas
			if(!$(this).parents('ul.tabs').hasClass('noBorder')) {
				$('#' + targetId).css({ 'border':'1px solid #73734e' , 'padding':'10px' });
			} else {
				$(this).parents('ul.tabs').css({ 'border-bottom':'1px solid #73734e' });
			}
			
			// build the behavior for any link with the same target as the tab
			$('a[href='+href+']').bind('click', function(e) {
				// change the selected tab
				$('li a[href='+href+']').parents('ul').find('li.selected').removeClass('selected');
				$('li a[href='+href+']').parent('li').addClass('selected');
				// hide the current tab content
				$('#' + oldTabId).hide();
				// find the new tab content and show it
				var showId = $(this).attr('href').replace('#','');
				$('#' + showId).show();
				oldTabId = showId
				
				e.preventDefault();
			});
		});
	});
}






// --------------------------------------------------
// build carousel
function buildCarousel() {
	$('.carousel').each(function() {
        var options = {
        
        };
		$(this).carousel(options);
	});
}



// --------------------------------------------------
// build lightbox
function buildColorBox() {
	$('a.colorbox').each(function() {
		var opts = {};
		opts.maxWidth = '75%';
		opts.maxHeight = '75%';
		
		if($(this).hasClass('colorbox-video')) {
			opts.width = '640';
			opts.height = '480';
			opts.iframe = 'true';
		}
		$(this).colorbox(opts);
	});
}





// ==================================================
// jwPlayer
// ==================================================
function jwEmbed() {
	// find all players
	$('a.jwEmbed').each(function() {
		opts = $(this).attr('rel').split('|');
		// set options
		var jwOpts = new Array();
		jwOpts['jwId'] 			= $(this).attr('id');
		jwOpts['jwFile']		= $(this).attr('href');
		jwOpts['jwFilePrefix']	= opts[0];
		jwOpts['jwWidth']		= opts[1];
		jwOpts['jwHeight']		= opts[2];
		jwOpts['jwCapSuffix']	= 'en';
		jwOpts['jwCapStr']		= opts[3];
		jwOpts['jwCapOptsBuilt']	= false;
		
		// initialize the player
		jwInit(jwOpts);
	});
	
	
	// find links for changing the jwProperties
	$('a.jwUpdate').live('click', function(e) {
		// get the options
		var optPairs = $(this).attr('rel').split('|');
		var jwUpdateOpts = new Array();
		for(i=0; i<optPairs.length; i++) {
			splits = optPairs[i].split('=');
			var k = splits[0];
			var v = splits[1];
			jwUpdateOpts[k] = v;
		}
		
		e.preventDefault();
		// create the new file
		jwInit(jwUpdateOpts, true);
	});
}

// ==================================================
// jwInit
function jwInit(jwOpts, autoplay) {
	// cache the object
	var jw = $('#' + jwOpts['jwId']);
	// delete old file
	jwDelete(jwOpts);	
	// create new player
	jwCreate(jwOpts);
	// set timeout to make sure the video is loaded
	setTimeout(function() {
		jwBuildCaptionOptions(jwOpts);	
	}, 1000);
	
}

// ==================================================
// jwBuildCaptionOptions
function jwBuildCaptionOptions(jwOpts) {

	// build an array from the capStr
	jwCapArray = jwOpts['jwCapStr'].split(',');
	
	if(jwOpts['jwCapOptsBuilt'] == false && jwOpts['jwCapStr'] != '') {
		var setWidth = $('#' + jwOpts['jwId']).innerWidth() - 10;
		$('#' + jwOpts['jwId'] + '-wrapper').after('<div class="jwCapOptions" id="' + jwOpts['jwId'] + '-capOpts" style="width: ' + setWidth + 'px;"></div>');
		// add a link for each available caption
		for(i=0; i<jwCapArray.length; i++) {
			switch(jwCapArray[i]) {
				case 'esp':		var jwCapsText = 'Espannol'; jwCapsAbbr = 'Esp'; break;
				case 'jp':		var jwCapsText = 'Japanese'; jwCapsAbbr = 'Jp'; break;
				default: 		var jwCapsText = 'English'; jwCapsAbbr = 'En'; break;
			}
			$('#' + jwOpts['jwId'] + '-capOpts').append('<a href="" class="jwUpdate" rel="jwId='+jwOpts['jwId']+'|jwCapStr='+jwOpts['jwCapStr']+'|jwCapSuffix='+jwCapArray[i]+'|jwFilePrefix='+jwOpts['jwFilePrefix']+'|jwFile='+jwOpts['jwFile']+'|jwWidth='+jwOpts['jwWidth']+'|jwHeight='+jwOpts['jwHeight']+'"><abbr title="'+jwCapsText+' captions">'+jwCapsAbbr+'</abbr></a>');
		}
		// set the flag to prevent rebuilding
		jwOpts['jwCapOptsBuilt'] = true;
	}
}

// ==================================================
// jwDelete
function jwDelete(jwOpts) {
	// find the wrapper
	wrapper = $('#' + jwOpts['jwId']).parents('.jwWrapper');
	// remove the player
	swfobject.removeSWF(jwOpts['jwId']);
	// put a placeholder back in
	wrapper.html('<a href="" class="jwEmbed" id="' + jwOpts['jwId'] + '">Video</a>');
}

// ==================================================
// jwCreate
function jwCreate(jwOpts) {
	var flashvars = { 'captions.file' : siteRoot + '/' + jwOpts['jwFilePrefix'] + '-' + jwOpts['jwCapSuffix'] + '.xml' };
		flashvars.plugins 			= 'captions';
		flashvars.file 				= jwOpts['jwFile'];
		flashvars.image				= siteRoot + '/images/jwPoster.png';
		flashvars.screencolor		= 'ffffff'; 
	var params = {};
	var attributes = {};
	// create the object
	swfobject.embedSWF(siteRoot + '/assets/jwPlayer.swf', jwOpts['jwId'], jwOpts['jwWidth'], jwOpts['jwHeight'], '9.0.0', 'expressInstall.swf', flashvars, params, attributes);
	
}



// =================================================
// Search box clear
function searchBoxClear() {
	$('#search input#q').bind('click', function() {
		if($(this).attr('value') == 'Search Bridge School Site') {
			$(this).attr('value', '');
		}
	}).bind('blur', function() {
		if($(this).attr('value') == '') {
			$(this).attr('value', 'Search Bridge School Site');
		}
	});
}



// ==================================================
// fix google search frame
// ==================================================
function fixGooleSearchFrame() {
	$('#cse-search-results iframe').css({ 'width':'700px' });
}

