$(function(){
	var nav_active_tab = $('#nav > ul > li.active'); // current nav item
	var nav_current_tab = nav_active_tab; // current nav item

	// hide all sub navs, unless it is from the current selected top nav
	if($('#nav > ul > li').hasClass('active')) {
		$('#nav li[class!="active"] ul').css('display', 'none');
	} else {
		//  occurs on pages with no active top nav
		$('#nav li:eq(0)').addClass('active');
		nav_active_tab = $('#nav > ul > li.active'); // current nav item
		nav_current_tab = nav_active_tab; // current nav item
	}

	//  onhover event for only top level tabs
	$('#nav > ul > li').hover(
		function() {
			var nav_new_tab = this;

			if(nav_current_tab != nav_new_tab) {
				//  highlight the new top nav
				$("#nav > ul > li").removeClass('active');
				$("#nav > ul > li").removeClass('hilite');
				$(this).addClass('hilite');

				//  swap the sub nav
				$("#nav li").not(this).children("ul").css('display', 'none');
				$(this).children("ul").css('display','block');

				nav_current_tab = nav_new_tab;
			}
		}
	);

	$('#nav').hover(
		function() {
			$(this).stopTime('exit');
		},
		function() {
			$(this).oneTime(1100, 'exit', function() {
				//  snap top nav back to active tab
				$('#nav > ul > li').removeClass('hilite');
				$(nav_active_tab).addClass('active');

				//  swap the sub nav
				$("#nav > ul > li").not(nav_active_tab).children("ul").css('display', 'none');
				$(nav_active_tab).children("ul").css('display','block');
			});
		}
	);

	// set tabs to tallest list
	/*
	var tallest = 0;
	$('div.panes-newswidget ul').each(function(i) {
		if($(this).height() > tallest) {
			tallest = $(this).height();
		}
	});
	$('div.panes-newswidget ul').height(tallest);
	*/

	/* setup tabs */
	// setup ul.tabs to work as tabs for each ul directly under div.panes
	$('ul.tabs-news').tabs('div.panes-news > ul');
	$('ul.tabs-feature-news').tabs('div.panes-feature-news > ul');

	$('ul.tabs-newswidget').tabs('div.panes-newswidget > ul');
	$('ul.tabs-snl').tabs('div.panes-snl > table');
	//  this stops the right column from changing positions when the tab is changed

	/* stripe tables */
	$('.striped tr').mouseover(function(){$(this).addClass('over');}).mouseout(function(){$(this).removeClass('over');});
	$('.striped tr:nth-child(odd)').addClass('odd');

	$(".accordion").tabs(".accordion .pane", {tabs: 'h2', effect: 'slide', initialIndex: null});

	// add issuu
//	$('#text-15 .textwidget').prepend('<object style="width:340px;height:219px" ><param name="movie" value="http://static.issuu.com/webembed/viewers/style1/v1/IssuuViewer.swf?mode=embed&amp;layout=http%3A%2F%2Fskin.issuu.com%2Fv%2Flight%2Flayout.xml&amp;showFlipBtn=true&amp;documentId=110815121036-a7a7b8f4db4649248ae7b2817f3b63e1&amp;docName=insurancejournal_west_2011.08.15&amp;username=insurancejournal&amp;loadingInfoText=Satire%20Issue&amp;et=1313410619515&amp;er=18" /><param name="allowfullscreen" value="true"/><param name="menu" value="false"/><embed src="http://static.issuu.com/webembed/viewers/style1/v1/IssuuViewer.swf" type="application/x-shockwave-flash" allowfullscreen="true" menu="false" style="width:340px;height:219px" flashvars="mode=embed&amp;layout=http%3A%2F%2Fskin.issuu.com%2Fv%2Flight%2Flayout.xml&amp;showFlipBtn=true&amp;documentId=110815121036-a7a7b8f4db4649248ae7b2817f3b63e1&amp;docName=insurancejournal_west_2011.08.15&amp;username=insurancejournal&amp;loadingInfoText=Satire%20Issue&amp;et=1313410619515&amp;er=18" /></object>');

	var theTable = $("#job-board");
	if (typeof theTable != 'undefined' && $.isFunction('tablesorter')) {
		theTable.tablesorter();
		theTable.find("tbody > tr").mouseover(function(){$(this).addClass('over');}).mouseout(function(){$(this).removeClass('over');});

		theTable.find("tbody > tr").find("td:eq(1)").mousedown(function(){
			$(this).prev().find(":checkbox").click()
		});

		$("#tablefilter").keyup(function() {
			$.uiTableFilter( theTable, this.value );
		})

		$('#tablefilter-form').submit(function(){
			theTable.find("tbody > tr:visible > td:eq(1)").mousedown();
		    return false;
		}).focus(); //Give focus to input field
	}

	$(".social-email[rel]").overlay({
		// some mask tweaks suitable for modal dialogs
		mask: {
			color: '#999999',
			loadSpeed: 200,
			opacity: 0.4
		},
		top: 'center'
	});

	$("#email-this").submit(function() {
		$("#email-warning").hide();
		$.ajax({
			url:  "/lib/email-this.php",
			type: "POST",
			data: $(this).serialize(),
			success: function(data) {
				if(data == 'true') {
					$("#email-success").show();
					$("#email-success").text('Your email has been sent.');
					$("#email-this").hide();
				} else {

					$("#email-warning").show();
					$("#email-warning").text('There was an error sending your email.  Please try again.');
				}
			}
		});
		return false;
	});

	//  tops search tabs in header
	$("#search-header-tabs span").click(function() {
		$("#search-header-tabs span[rel!="+$(this).attr("rel")+"]").removeClass("active");
		$("#search-header-tabs span[rel="+$(this).attr("rel")+"]").addClass("active");

		$("#search-header-form #search-header-section").val($(this).attr("rel"));

		//  swap location based on type
		if($(this).attr("rel") == 'markets') {
			$('#search-header-form').attr('action','/search/');
		} else if($(this).attr("rel") == 'jobs') {
			$('#search-header-form').attr('action','/jobs/');
		} else {
			$('#search-header-form').attr('action','/search/');
		}
		return false;
	});

	if ($.isFunction('skitter')) {
		$("#box-skitter").skitter({
			animation:  "fade",
			interval:   5000
		});
	}
});

function hideReviewsFlyout(){
	$('#reviewsTab').removeClass('hover');
	$('#flyoutWrapper').slideUp('fast');
}
function showReviewsFlyout(){
	$('#reviewsTab').addClass('hover');
	$('#flyoutWrapper').slideDown(50);
}


/* ----- GOOGLE AJAX SEARCH ----- */
//google.load('search', '1', {'nocss' : true});

var monthsShort = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var gsNewsSearch;
var gsSearchTerm = '';

function gsAddPaginationLinks() {
	// The cursor object has all things to do with pagination
	var cursor = gsNewsSearch.cursor;
	var curPage = cursor.currentPageIndex; // check what page the app is on
	var pagesDiv = document.createElement('div');

	var pages = '<ul class="page-numbers clearfix" style="border-bottom: 0;">';
	if(cursor.pages.length > 1) {
		for (var i = 0; i < cursor.pages.length; i++) {
			var page = cursor.pages[i];
			if (curPage == i) { // if we are on the curPage, then don't make a link
				pages += '<li class="current">' + page.label + '</li>';
			} else {
				// If we aren't on the current page, then we want a link to this page.
				// So we create a link that calls the gotoPage() method on the searcher.
				pages += '<li><a href="javascript:gsNewsSearch.gotoPage('+i+');">' + page.label + '</a></li>';
			}
		}
	}
	pages += '</ul>';
	pagesDiv.innerHTML = pages;

	var contentDiv = document.getElementById('gs-company-news');
	contentDiv.appendChild(pagesDiv);
}

function gsSearchComplete() {
	// Check that we got results
	if (gsNewsSearch.results && gsNewsSearch.results.length > 0) {
		// Grab our content div, clear it.
		var contentDiv = document.getElementById('gs-company-news');
		contentDiv.innerHTML = '';

		// Loop through our results, printing them to the page.
		var results = gsNewsSearch.results;
		for (var i = 0; i < results.length; i++) {

			if (i == 0) {
				var listContainer = document.createElement('ul');
				listContainer.setAttribute('class', 'ruled');
			}

			// For each result write it's title and image to the screen
			var result = results[i];

			var itemContainer = document.createElement('li');
			itemContainer.setAttribute('class', 'gs-newsResult gs-result');

			var link = document.createElement('a');
			link.setAttribute('href', result.unescapedUrl);
			link.setAttribute('class', 'gs-title');
			link.innerHTML = result.titleNoFormatting;

			var meta = document.createElement('div');
			meta.setAttribute('class', 'meta gs-meta');

			var publisher = document.createElement('span');
			publisher.setAttribute('class', 'gs-publisher');
			publisher.innerHTML = ' - ' + result.publisher;

			var theTime = new Date(result.publishedDate)
			var month = theTime.getMonth()
			var day = theTime.getDate()
			var year = theTime.getFullYear()

			var publishedDate = document.createElement('span');
			publishedDate.setAttribute('class', 'gs-publishedDate');
			publishedDate.innerHTML = monthsShort[month] + ' ' + day + ', ' + year;

			itemContainer.appendChild(link);
			meta.appendChild(publishedDate);
			meta.appendChild(publisher);
			itemContainer.appendChild(meta);

			// Put our title + image in the content
			listContainer.appendChild(itemContainer);
		}
			contentDiv.appendChild(listContainer);

		// Now add the paging links so the user can see more results.
		gsAddPaginationLinks(gsNewsSearch);
	}
}


/* cookie functions */
function setCookie(name, value, expiredays, path, domain, secure) {
	var expdate=new Date();
	expdate.setDate(expdate.getDate()+expiredays);

	document.cookie= name + '=' + escape(value) +
		((expiredays) ? '; expires=' + expdate.toUTCString() : '') +
		((path) ? '; path=' + path : '') +
		((domain) ? '; domain=' + domain : '') +
		((secure) ? '; secure' : '');
}

function getCookie(name) {
	if (document.cookie.length>0) {
		start=document.cookie.indexOf(name + '=');
		if (start!=-1) {
			start=start + name.length+1;
			end=document.cookie.indexOf(';',start);
			if (end==-1) end=document.cookie.length;
			return unescape(document.cookie.substring(start,end));
		}
	}
	return null;
}

function checkCookie(name) {
	value = getCookie(name);
	if (value!==null && value!=='') {
		alert('cookie ' + name + ': ' + value);
	} else {
		value = prompt('Please enter value for '+name+':', '');
		if (value!==null && value!=='') {
			setCookie(name,value,7);
		}
	}
}

function issetCookie(name) {
	value = getCookie(name);
	if (value!==null) {return true;}
	return false;
}

