/****************************************************
*	IRWD Global Javascript - ver 1.88				*
*	2011 Evolve Media								*
****************************************************/

// Slider Assist
function formatText(index, panel) {
  return '<span class="slider_nav">' + index + '</span>';
}

// String Stripper
function stripper(inStr) {
	return inStr.replace(/[^0-9]/g, "");
}

// iFrame Magick
function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document.body.scrollHeight+50;
        newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}

// Preload
function preload(arrayOfImages) {$(arrayOfImages).each(function(){$('<img/>')[0].src = this;});}

// Social media overlay
function doOverlay(dtitle, dheight, dwidth, dmode){
	// Build Overlay
	var docHeight = $(document).height();
	var docWindow = $(window);
	$('body').append('<div id="soverlay"></div><div id="sdialog" class="loadBkg"><div id="sdtitle">'+dtitle+'<div id="sdclose"><a href="#">[close]</a></div></div><div id="sdcont">&nbsp;</div></div>');
	var soverlay = $('#soverlay');
	soverlay.height(docHeight);

	// Build Dialog
	var sdialog = $("#sdialog");
	//var dheight = 470;
	//var dwidth = 400;
	sdialog.css('height', dheight + $('#sdtitle').height()+'px');
	sdialog.css('width', dwidth+'px');
	sdialog.css('top', ((docWindow.height() / 2)-(sdialog.height() / 2)) + 'px');
	sdialog.css('left', ((docWindow.width() / 2)-(sdialog.width() / 2)) + 'px');
	
	// Load content
	$('#sdcont').load('/feeds/social.php?src='+dmode, function(){
		sdialog.removeClass('loadBkg');
	});
	
	// Show
	$(sdialog).fadeIn(800);
	$(soverlay).fadeIn(400);
	
	// Close button
	$('#sdclose a').click(function(){
		$(sdialog).fadeOut(400, function(){ $(this).remove(); });
		$(soverlay).fadeOut(800, function(){ $(this).remove(); });
		return false;
	});
	$(document).keyup(function(e) {
	if (e.keyCode == 27) { $('#sdclose a').click(); } // escape pressed
	});

}

$(document).ready(function(){

	// Login
	/*$('#login_launch').overlay({
		speed: 523,
		top: 'center',
		effect: 'default',
		
		mask: {
			color: '#666',
			loadSpeed: 923,
			opacity: 0.5
		}
	});*/

	// Account login
	/*$('#cust_care img[alt=Account Access]').click(function(){
		alert('A login screen will appear when you click here. Watch this space!');
		return false;
	});*/
	
	// Fancy Table (ie fix!)
	if($('#category_text table.fancytable').length > 0)
	{	
		var topRow = {
			'font-weight'	:	'bold',
			'color'			:	'#000000',
			'text-align'	:	'center'
		}

		var base = $('#category_content #category_text table.fancytable');
		base.find('tr:odd').css('background-color', '#f2f6f8');
		base.find('tr:even').css('background-color', '#d1eaf4');
		base.find('tr:first').css(topRow);
		
	}
	
	// Calendar
	if($('#kalender').length > 0)
	{
	
		// Preload images
		preload(['assets/snippets/kalender/themes/gold_enhanced/images/previous_over.gif','assets/snippets/kalender/themes/gold_enhanced/images/next_over.gif','assets/images/global/pdf.png']);
		
		// Shading!
		$('#kalender td.day:odd').each(function(i, x){
			var base = $(this);
			if(base.hasClass('kalender-dayHighlight'))
			{
				base.addClass('kalOdd');
			}
		});
		// Prevent overflow & hide last underline
		$('#kalender td.day').each(function(i,x){
			var base = $(this);
			base.find('.showCalTip:last').css('border-bottom', 'none');
		});
		
		//$('#kalender .showCalTip').ellipsis();
	
		// Tooltip
		var calTipWidth = 307;
		//if($.browser.msie && $.browser.version=="6.0") calTipWidth = 307; // I HATE YOU INTERNET IMPLODER!
		
		$('#kalender td .showCalTip').each(function()
		{
			$(this).qtip({
				content: $(this).find('div.xevent').html(), // Use the tooltip attribute of the element for the content
				position: {
					corner: {
						target: 'topLeft',
						tooltip: 'topLeft'
					},
					adjust: {
						x: 50,
						y: 8,
						screen: true
					}
				},
				style: {
					padding: 0,
					name: 'dark',
					tip: { corner: 'leftTop' },
					width: calTipWidth,
					border: {
						color: '#303030'
					}
				},
				hide: {
					fixed: true,
					delay: 250
				}
			});
		});
		
	} // END CALENDAR

	// GET PASSED PARAMS
  var urlParams = {};
  (function() {
  	var e,
  		a = /\+/g,
  		r = /([^&=]+)=?([^&]*)/g,
  		d = function(s) { return decodeURIComponent(s.replace(a, " ")); },
  		q = window.location.search.substring(1);
  		
  	while (e= r.exec(q))
  		urlParams[d(e[1])] = d(e[2]);
  })();
	
	// Expander
	$('#category_text ul.expander_list li.expander a.exp').click(function(){
		
		var base = $(this);
		var tregion = base.parent().find('ul.expander_itm');
		
		if(!base.hasClass('active'))
		{
			base.addClass('active');
			
			tregion.css('opacity', 0);
			tregion.animate({height: 'show', opacity: 1});
			//tregion.slideDown(500);
			
			//alert('whoop');
		} else {
			base.removeClass('active');
			tregion.animate({height: 'hide', opacity: 0});
			//tregion.slideUp(500);
		}
	
		return false;
	});
	if($('#category_text ul.expander_list').length > 0)
	{
		var base = $('#category_text ul.expander_list');
		if(base.hasClass('na_click'))
		{
/*			if ((urlParams["year"] == "") || !urlParams["year"] || (urlParams["year"] == "undefined"))
				base.find('a.exp:first').click();
			else */
				base.find('a.' + urlParams["year"]).click();
		}
	}

        // Facebook Wall
        $(function(){
	  $('#facebook_wall').fbWall({
	    id:'96675272108',
	    accessToken:'206158599425293|d98065f755a1c99d56511c49.1-100002844280239|SDI7pQDsHCFlKp0uzCRQOXYqy1o',
            showGuestEntries:false,
            showComments:false,
            max:3,
            timeConversion:12
          });
	});

	// Search text effect
	var searchText = ' search';
	$('input#s_box').focusin(function(){
		if($(this).val() == searchText) $(this).val('');
	});
	$('input#s_box').focusout(function(){
		if($(this).val() == '') $(this).val(searchText);
	});
	
	// Icons on PDF links
	$("#category_content a[href$='.pdf']").addClass('pdf');
	
	// Twitter links
	$("#category_content a[href^='http://www.twitter.com'], #category_content a[href^='http://twitter.com']").addClass('twitter');
	
	// Facebook links
	$("#category_content a[href^='http://www.facebook.com'], #category_content a[href^='http://facebook.com']").addClass('facebook');

	// Print button clicked
	$('#print').click(function() {
		window.print();
		return false;
	});
	
	// External links open in a new window
	$("a[href^='http:'], a[href^='https:']").not("[href*='"+window.location.host.toLowerCase()+"'], [href*='online.irwd.com'], [href*='www.irwd.com']").attr('target','_blank');
	
	// Animation lock
	var animationLock = false;
	
	// If tab page, figure out what the first tab is, make tab heights the same
	if($('div#tabs div.tabcontent').length > 0)
	{
		var lastClicked = $('div#tabs div#upper a').first().attr('rel');
		var lastSub = lastClicked;
		//$('.content0').hide();
		$('#content'+lastClicked).show();
	}
	
	// Tabs v2
	var lastActive = null;
	// Pick default frame on start
	$('.ntabs').each(function(e){
		// Hide panel CMS determined is first (may or may not be correct)
		$(this).find('.order0').hide();
	
		// Get first tab of set
		var tid = $(this).find('.nt_upper .utfirst a').attr('rel');
	
		// Open that tabs panel
		$(this).find('.ntabs_content .pg'+tid).show();
	});
	// Tab clicked
	$('div.nt_upper tr td div a').click(function(){
		// Only do stripper once
		var new_id = stripper($(this).attr('class'));
		
		// Change tab highlight & load section nav bar
		ntBar(new_id, $(this));
		
		// Load tab page
		ntPage(new_id, $(this));
			return false;
	});
	// Subtab clicked
	$('div.ntab_bar div.tabpanel div.nt_lower ul li a').click(function(){
		// Load tab page
		ntPage(stripper($(this).attr('class')), $(this));
		return false;
	});
	
	function ntBar(new_id, base){
		// Only load if we have to
		if($(base).parents('.ntabs').find('.panel'+new_id).css('display') == 'block') return true;
		
		// Change active tab
		$(base).parents('.ntabs').find('td.utfirst, td.utsel').removeClass('utfirst utsel');
		$(base).parents('td').addClass('utsel');
		
		// Fade out visible nav
		$(base).parents('.ntabs').find('.tabpanel:visible').hide(800, function(){
			// Hide any existing underlines
			$(base).parents('.ntabs').find('div.nt_lower ul li a').css('text-decoration', 'none');
			// Fade in new nav
			$(base).parents('.ntabs').find('.ntab_bar').find('.panel'+new_id).show(500);
		});
	}
	function ntPage(new_id, base){
		// Only load if we have to
		if($(base).parents('.ntabs').find('.pg'+new_id).css('display') == 'block') return true;
		
		// Remove previous underline
		$(base).parents('.ntabs').find('.tabpanel:visible').find('div.nt_lower ul li a').css('text-decoration', 'none');
		// Underline new selection
		$(base).parents('.ntabs').find('.tabpanel:visible').find('div.nt_lower ul li a.subtab'+new_id).css('text-decoration', 'underline');
		
		// Lock current height while we recalculate
		$(base).parents('.ntabs').find('.ntabs_content').css('height', $(base).parents('.ntabs').find('.ntabs_content').height()+'px');
		
		// Get new page height
		$(base).parents('.ntabs').find('.pg'+new_id).css('visibility','hidden').css('display','block');
		var newHeight = $(base).parents('.ntabs').find('.pg'+new_id).height();
		newHeight += 5;
		$(base).parents('.ntabs').find('.pg'+new_id).css('display','none').css('visibility','visible');
		
		// Fade out visible page
		$(base).parents('.ntabs').find('.tabcontent:visible').fadeOut(700);
		
		// Resize container
		$(base).parents('.ntabs').find('.ntabs_content').animate({
			height: [newHeight+"px", 'easeInOutQuart']
		}, 823, function() {
			// Fade in new content
			$(base).parents('.ntabs').find('.ntabs_content').find('.pg'+new_id).fadeIn(500,function(){
				
			});
		});
	}
	
	// Accordions
	$('a.ac_region_h').click(function(){
		// Close everything
		if($(this).parent().is('.active'))
		{
			var oldItem = $(this).parents('ul.ac_region_ul').find('div.ac_region_content:visible');
			var oldHeight = $(oldItem).height();
			$(this).parents('ul.ac_region_ul').find('h2.active').removeClass('active');
			$(oldItem).animate({height: [0, 'easeInOutQuart'], opacity: 'hide'}, 523, function(){$(oldItem).css('display','none').height(oldHeight);});
			return false;
		}
	
		// Remove perviously active header
		$(this).parents('ul.ac_region_ul').find('h2.active').removeClass('active');
		
		// Make clicked item active
		$(this).parent().addClass('active');
		
		// Get text regions
		var oldItem = $(this).parents('ul.ac_region_ul').find('div.ac_region_content:visible');
		var newItem = $(this).parents('li.ac_region_li').find('div.ac_region_content');
		
		// Get text region heights
		var oldHeight = $(oldItem).height();
		$(newItem).css('visibility','hidden').css('display','block');
		var newHeight = $(newItem).height();
		$(newItem).css('display','none').css('visibility','visible');
		
		// Animate!
		$(oldItem).animate({height: [0, 'easeInOutQuart'], opacity: 'hide'}, 523, function(){$(oldItem).css('display','none').height(oldHeight);});
		$(newItem).height(0).css('display','none').animate({height: [newHeight, 'easeInOutQuart'], opacity: 'show'}, 523);
		
		return false;
	});
	
	// Tours
	if($('#tourToggle').length > 0)
	{
		// Hide info if YES or EMPTY
		if($('#tourToggle input#iresidentNO:checked').length == 1){
			$('#employerInfo').show();
		} else {
			$('#employerInfo').hide();
		}
		
		$('#tourToggle input:radio').click(function(){
		
			if($(this).val() == 'no')
			{
				$('#employerInfo').slideDown(600, 'easeInOutQuart');
			} else {
				$('#employerInfo').slideUp(600, 'easeInOutQuart');
			}
		
		});
	}
	
	// Reservations
	function loadTerms(base) {
		var loadme = base.parent().attr("class")+".html";
		
		if(base.attr('checked')) {
			// Load terms & conditions
			$('#print_tos').hide();
			$('#tos').addClass('loadBkg');
			$('#iagree').attr('disabled', true);
			$('#tos').html('<p>&nbsp;</p>');
			$('#tos').load('/assets/files/terms/'+loadme, function(){
				// Make "I agree" selectable
				$('#iagree').removeAttr('disabled');
				// Hide loading animation
				$('#tos').removeClass('loadBkg');
				// Print button
				var tos_print = $('#print_tos').find('a');
				tos_print.attr('href', '/assets/files/terms/'+loadme+'?a=print');
				$('#print_tos').fadeIn(300);
				tos_print.click(function(){
					window.open (tos_print.attr('href'),"Terms and Conditions","menubar=1,location=1,resizable=1,scrollbars=1,width=500,height=400");
					return false;
				});
				
				
			});
		}
	}
	if($('#Reservations').length > 0){
		$('#print_tos').hide();
		$('#iagree').attr('disabled', true);
		$('#tos').html('<p>You must first select a location to read &amp; agree to the terms and conditions.</p>');
		
		$('#res_select input').click(function(){
			loadTerms($(this));
		});
		
		$('#res_select input:checked').each(function(i, x){
			var base = $(x);
			loadTerms(base);
		});
	}
	
	// Widgets
	$('#fb_launch').click(function(){
		doOverlay('IRWD On Facebook', 470, 400, 1);
		return false;
	});
	$('#twitter_launch, #twitter_head').click(function(){
		doOverlay('IRWD On Twitter', 396, 768, 2);
		return false;
	});
	
	// Preload overlay (png because IE sucks)
	preload(['assets/images/global/ieoverlay.png']);
	
	// Image descriptions
	$('#category_text > p > img').jcaption();
	
});

