$(function(){
	/* Forces page to the top  */
	setTimeout(function() {
		if (location.hash) {
			window.scrollTo(0, 0);
		}
	}, 1);

	$('#logofix, .scrollable-fix, #content-nav').pngFix(); 	
	
	window.onload = function () {

		var rel = $("form#chrome_refresh #toBeReloaded").val();
		var str = navigator.appVersion;
		
		if( str.indexOf( "Chrome" ) !== -1 && $.browsers.win() ) {
			if ( rel == 1 ) {
				//console.log("reload");
				window.location.reload();
			} else {
				//console.log("reloaded");
				$("form#chrome_refresh #toBeReloaded").val("1");
			};
		};
		//console.log(rel);
		//console.log($("#toBeReloaded").val());
	}

	
	
	// Print *********************************************
	$('#printjs').live("click",function(){
		var PrintTab = $(this).attr("rel");
		//console.log( PrintTab );
		if( PrintTab == "" ){
			// Page load but with #tab-7 in URL
			var urltab = window.location.href;
			var urltabhash = urltab.split('#'); 
			//console.log( urltab );
			
			if ( urltabhash[1] == "tabs-2" || urltabhash[1] == "tabs-3" || urltabhash[1] == "tabs-4" || urltabhash[1] == "tabs-5" || urltabhash[1] == "tabs-6" || urltabhash[1] == "tabs-7" ) {
				var PrintTabID = urltabhash[1];
				//console.log("printing hash");
			} else {	
				//console.log("printing all");
				var PrintTabID = 'content-content-left-col';
			}
			
			$("#"+PrintTabID).printElement({ 
				leaveOpen:true,
				printMode:'popup',
				overrideElementCSS:['/css/print.css', { href:'../css/print.css',media:'print'}],
				pageTitle: 'CapitalStructure - Print Page',
				printBodyOptions: {
					"styleToAdd": 'padding:10px;margin:10px;',
					"classNameToAdd": 'printbody'
				}
			});
			
		} else if( PrintTab == "tabs-1" ) {
			$("#content-content-left-col").printElement({ 
				leaveOpen:true,
				printMode:'popup',
				overrideElementCSS:['/css/print.css', { href:'../css/print.css',media:'print'}],
				pageTitle: 'CapitalStructure - Print Page',
				printBodyOptions: {
					"styleToAdd": 'padding:10px;margin:10px;',
					"classNameToAdd": 'printbody'
				}
			});
		
		} else if( PrintTab == "tabs-2" || PrintTab == "tabs-3" || PrintTab == "tabs-4" || PrintTab == "tabs-5" || PrintTab == "tabs-6" || PrintTab == "tabs-7" ) {
			$("#"+PrintTab).printElement({ 
				leaveOpen:true,
				printMode:'popup',
				overrideElementCSS:['/css/print.css', { href:'../css/print.css',media:'print'}],
				pageTitle: 'CapitalStructure - Print Page',
				printBodyOptions: {
					"styleToAdd": 'padding:10px;margin:10px;',
					"classNameToAdd": 'printbody'
				}
			});
		}
	});
	
	$("#hung_sel").change(function() {
		var src = $(this).val();
		if ( src == "2" ) { $("#viewhung").hide(); } else { $("#viewhung").show(); }
	});
	
	$("div.structured-level1:empty").text("empty");
	
	// Main Menu Select control **************************
	$('#nav-container li a').live("click",function(){
		$('#nav-container li a').removeClass('selected');
		$(this).addClass('selected');
	});
	
	$(".scrollable").scrollable({ circular: true, speed: 3000, easing: 'custom' }).autoscroll({ autoplay: true, autopause: true, interval:10000 });
	
	// Tooltips
	$(".tooltip-popup a").hover(function() {
		$(this).next("em").stop(true, true).animate({opacity: "show", top: "-50"}, "slow");
	}, function() {
		$(this).next("em").animate({opacity: "hide", top: "-70"}, "fast");
	});

	// Reset the screen to (0,0)
	$.scrollTo( 0 );

	// Terms ScrollTo ***********************************
	if ($("#right-jump-nav a")[0]) {
		$('#right-jump-nav a').click(function(){
			$.scrollTo( this.hash, 1500, { offset: {top:0, left:0} });
			$(this.hash).find('span.message').text( this.title );
			return false;
		});
	}
	
	if ($("td.addalert div.actions")[0]) {
		$('td.addalert div.actions').click(function(){
			if( !$("input#pr_new_alert_name").val() ) { 
				$("td.addalert").css("background-color","#B71E1E");
				$("td.addalert #new_alert_text").css("color","#ffffff");
			} else {
				$('form#profile-form').submit();
			};
			return false;
		});
	}
	
	
	
	// Leverage form add selects ***********************
	var strBrowserVersion = $.browsers.version.string();
	if((strBrowserVersion >= 6) && (strBrowserVersion < 7)){
		//Don't do multiselects
	} else {
		$("select[multiple]").asmSelect({
			addItemTarget: 'bottom',
			animate: true,
			highlight: false,
			sortable: true
		});
	};

	$('#ld_launchdate_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#ld_launchdate_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#pr_date_pause_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#pr_date_pause_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#lc_commitmentdate_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#lc_commitmentdate_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#lc_date_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#lc_date_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#ls_launchdate_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#ls_launchdate_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#ls_maturitydate_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#ls_maturitydate_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#sc_commitmentdate_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#sc_commitmentdate_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#sc_date_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});
	$('#sc_date_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1980:2020'});

	
	// calendars for the admin section
	$('#report_date_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2020'});
	$('#report_date_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2020', maxDate: '+0'});

	$('#hy_launch_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2020'});
	$('#hy_launch_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2020'});
	$('#hy_maturity_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2020'});
	$('#hy_maturity_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2020'});

	$('#ll_launch_from').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2050'});
	$('#ll_launch_to').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2050'});
	$('#calendar1').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2050'});
	$('#calendar2').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2050'});
	$('#calendar3').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2050'});
	$('#calendar4').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2050'});
	$('#calendar5').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2050'});
	$('#calendar6').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2050'});
	$('#calendar7').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2050'});
	$('#calendar8').datepicker({dateFormat: 'dd/mm/yy', changeMonth: true,	changeYear: true, yearRange: '1985:2050'});
		
	//Region 
	$('a.show-region').toggle( 
		function () {
			$("div.region").fadeIn();
		}, 
		function () {
			$("div.region").fadeOut();
		}
	);
	
	// hidden data *************************************
	$('img.show-hidden').click( function () {
		if ($(this).attr("src") == "/images/rollup-arrow.gif") { 
			$(this).attr("src", "/images/rolldown-arrow.gif");
		} else {
			$(this).attr("src", "/images/rollup-arrow.gif");		
		};
		var rowCount = $(this).attr("rel");
		$(".row-count-"+rowCount).fadeThenSlideToggle().parent().parent("tr").toggleClass("hover");
		$(this).parent().parent("tr").toggleClass("trhover");
	});
	
	$('a.show-hidden-edit').click( function () {
		if ($(this).attr("title") == "Close") { 
			$(this).attr("title", "Edit");
			$(this).html("<img src=/images/page_edit.png width=16 height=16 alt=Edit border=0 />");
		} else {
			$(this).attr("title", "Close");
			$(this).html("<img src=/images/page_close.png width=16 height=16 alt=Edit border=0 />");			
		};
		var rowCount = $(this).attr("rel");
		$(".edit-"+rowCount).fadeThenSlideToggle().parent().parent("tr").toggleClass("hover");
		$(this).parent().parent("tr").toggleClass("bo-trhover");
	});
	
	// Profile form checkboxes / radios and auto-completes *****
	if ($("#float-actions")[0]) {
		var msie6 = $.browser == 'msie' && $.browser.version < 7;
	  
		if (!msie6) {
			var top = $('#float-actions').offset().top - parseFloat($('#float-actions').css('margin-top').replace(/auto/, 0));
			$(window).scroll(function (event) {
				// what the y position of the scroll is
				var y = $(this).scrollTop();

				// whether that's below the form
				if (y >= top) {
					// if so, ad the fixed class
					$('#float-actions').addClass('fixed');
				} else {
					// otherwise remove it
					$('#float-actions').removeClass('fixed');
				}
			});
		} 
	};
	
	/* Browser and OS detection */
	//alert("triggered: Windows:-" + $.browsers.win() + " and IE:- " + $.browsers.msie() + " Ver:- " + $.browsers.version.string());
	/* Mac and Firefox */
	if($.browsers.mac() && $.browsers.firefox()) {
		$('body').addClass('MacFirefox');
	};
	/* Mac and Safari */
	if($.browsers.mac() && $.browsers.safari()) {
		$('body').addClass('MacSafari');
		//alert("triggered: OSX:-" + $.browsers.mac() + " and Safari:- " + $.browsers.safari() + " Ver:- " + $.browsers.version.string());
	};
	
	/* Windows and IE7 */
	if($.browsers.win() && $.browsers.msie()) {
		var strBrowserVersion = $.browsers.version.string();
		if((strBrowserVersion >= 6) && (strBrowserVersion < 7)){
			$('body').addClass('WinIE6');
			//alert("oh joy, IE6");
		} else if ((strBrowserVersion >= 7) && (strBrowserVersion < 8)){
			$('body').addClass('WinIE7');
		} else {
			$('body').addClass('WinIE8');
			//alert("IE8")
		};
	};
	
	
	$("button, input:submit", ".actions").button();
	
	$("#reporttiming").buttonset();
	$("#criteriatype").buttonset();
	$("#actions1").buttonset();
	$("#actions2").buttonset();
	$("#actions3").buttonset();
	
	$("#reporttype").buttonset();
	$("#check1").button();
	$("#check2").button();
	$("#check3").button();
	$("#check4").button();
	$("#check5").button();
	$("#check6").button();
	$("#check7").button();
	$("#check8").button();
	$("#check9").button();
	$("#check10").button();
	$("#check11").button();

	$("#check1").click( function()	{
		var checked_status = this.checked;
		
		if ( this.checked ) {
			$("input[name*='pr_news_source_ex']").attr('checked', true);
			$("input[name*='pr_news_source_ex']").button('refresh');
			$("input[name*='pr_news_source_cs']").attr('checked', true);
			$("input[name*='pr_news_source_cs']").button('refresh');
			$("input[name*='pr_news_source_ra']").attr('checked', true);
			$("input[name*='pr_news_source_ra']").button('refresh');
			$("input[name*='pr_news_source_cp']").attr('checked', true);
			$("input[name*='pr_news_source_cp']").button('refresh');
			$("input[name*='pr_news_source_pa']").attr('checked', true);
			$("input[name*='pr_news_source_pa']").button('refresh');
		} else {
			$("input[name*='pr_news_source_ex']").attr('checked', false);
			$("input[name*='pr_news_source_ex']").button('refresh');
			$("input[name*='pr_news_source_cs']").attr('checked', false);
			$("input[name*='pr_news_source_cs']").button('refresh');
			$("input[name*='pr_news_source_ra']").attr('checked', false);
			$("input[name*='pr_news_source_ra']").button('refresh');
			$("input[name*='pr_news_source_cp']").attr('checked', false);
			$("input[name*='pr_news_source_cp']").button('refresh');
			$("input[name*='pr_news_source_pa']").attr('checked', false);
			$("input[name*='pr_news_source_pa']").button('refresh');
		}

	});
	
	$("#check7").click( function()	{
		var checked_status = this.checked;
		
		if ( this.checked ) {
			$("input[name*='pr_universe_ss']").attr('checked', true);
			$("input[name*='pr_universe_ss']").button('refresh');
			$("input[name*='pr_universe_hy']").attr('checked', true);
			$("input[name*='pr_universe_hy']").button('refresh');
			$("input[name*='pr_universe_ll']").attr('checked', true);
			$("input[name*='pr_universe_ll']").button('refresh');
			$("input[name*='pr_universe_pm']").attr('checked', true);
			$("input[name*='pr_universe_pm']").button('refresh');
		} else {
			$("input[name*='pr_universe_ss']").attr('checked', false);
			$("input[name*='pr_universe_ss']").button('refresh');
			$("input[name*='pr_universe_hy']").attr('checked', false);
			$("input[name*='pr_universe_hy']").button('refresh');
			$("input[name*='pr_universe_ll']").attr('checked', false);
			$("input[name*='pr_universe_ll']").button('refresh');
			$("input[name*='pr_universe_pm']").attr('checked', false);
			$("input[name*='pr_universe_pm']").button('refresh');
		}

	});
	
	
	if ($(".multiselect")[0]) {
		//$(".multiselect").multiselect();
	};
	
	$("#tabs").tabs({
		select: function(event, ui) { 
			var url = ui.tab.href;
			//console.log(" " + url + " ");
			var CurrentTab = url.split('#');
			//console.log(" " + CurrentTab[1] + " ");
			$('div#header-container').find('.printpage').attr('rel', CurrentTab[1]);
		}
	});
	
	// $("#subtabs").tabs();
	
	$("#league-tabs").tabs({});
	
	
	/*
	$('#calendar-tabs').tabs({
		var urlTabParams = $(this).attr("rel");
		load: function(){
			
		};
	});
	*/
	//console.log (" working ");
	
	// get uv vars
	function getUrlVars() 
	{ 
	    var vars = [], hash; 
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); 
	    for(var i = 0; i < hashes.length; i++) 
	    { 
	        hash = hashes[i].split('='); 
	        vars.push(hash[0]); 
	        vars[hash[0]] = hash[1]; 
	    } 
	    return vars; 
	}
	var selectedCalendarTab = getUrlVars()["calendartab"];
	var selTab = 0;
	if (selectedCalendarTab != undefined) {
		var selTab = selectedCalendarTab;
	}
	
	$('#calendar-tabs').tabs({
		ajaxOptions: {
			async: false,
			error: function(xhr, status, index, anchor) {
					$(anchor.hash).html("Couldn't load this tab.");
					//$("#lc_display_type").val('all');
				}
			},
		spinner: 'Loading...',
		collapsible: false,
		fx: {
			//opacity: 'toggle' 
		},
		select: function(event, ui) {
			
			
			/* Force the removal of the selected state class */
			$('#calendar-tabs ul li').removeClass('ui-state-active');
						
			var url = $.data(ui.tab, 'load.tabs');
			var check = ui.panel.id;
			
			//console.log (url + " and " + check);
			
			currentTab1 = url.split("=");
			//console.log (currentTab1);
			currentTab2 = currentTab1[1].split("&");
			//console.log (currentTab2);
			
			$("#lc_display_type").val(currentTab2[0]);
			$("#sc_display_type").val(currentTab2[0]);
			
			if( check == "View_Full_Calendar" ) {
				location.href = url;
				return false;
			}
			
			$(this).find('div.ajax-loader').show();
			
			return true;

		},
		selected: selTab,
		load: function(event, ui) { 
			$(this).find('div.ajax-loader').hide();
		},
		cookie: { 
			name: 'tab_cookie',
            expires: 7
		}
	});
	
	/**
	 * Event handle for view all links
	 */
	
	$('.announced').live('click',function(){
		$(document).scrollTop(0);
		$('#calendar-tabs').tabs( "select" , 1 );
		return false;
	});
	$('.expected').live('click',function(){
		$(document).scrollTop(0);
		$('#calendar-tabs').tabs( "select" , 2 );
		return false;
	});
	$('.completed').live('click',function(){
		$(document).scrollTop(0);
		$('#calendar-tabs').tabs( "select" , 3 );
		return false;
	});
	$('.hung').live('click',function(){
		$(document).scrollTop(0);
		$('#calendar-tabs').tabs( "select" , 4 );
		return false;
	});
	
	
	/*
	$("#borrower").autocomplete({
		source: "ajaxsearchsuggestor?as_type=COMPANY",
		width: 193,
		max: 4,
		minLength: 3,
		highlight: false,
		multiple: true,
		multipleSeparator: " ",
		scroll: true,
		scrollHeight: 300
	});
*/
	
	$('#leveraged_calendar').submit(function() { // catch the form's submit event
		$('#calendar-tabs').find('div.ajax-loader').show();
		$(this).find("div.loading-text").html("Loading...");
		$.ajax({ // create an AJAX call...
			data: $(this).serialize(), // get the form data
			type: $(this).attr('method'), // GET or POST
			url: $(this).attr('action'), // the file to call
			success: function(response) { // on success..			
				
				var allLink = 'leveragedcalendarall?lc_display_type=all&lc_search=search';
				var expectedLink = 'leveragedcalendarall?lc_display_type=expected&lc_search=search';
				var announcedLink = 'leveragedcalendarall?lc_display_type=announced&lc_search=search';
				var completedLink = 'leveragedcalendarall?lc_display_type=completed&lc_search=search';
				var thisLink = '';
								
				if ($('#borrower').val() != undefined) {
					thisLink += '&lc_company_name=';
					thisLink += $('#borrower').val();
				}
				
				var multipleSectors = $("#lc_sector").val() || [];
				$.each(
						multipleSectors,
						function( intIndex, idSector ){
							thisLink += '&lc_sector[]=';
							thisLink += idSector;
						}
				);
				
				var multipleCountries = $("#lc_country").val() || [];
				$.each(
						multipleCountries,
						function( intIndex, idCountry ){
							thisLink += '&lc_country[]=';
							thisLink += idCountry;
						}
				);
				
				var multipleTypes = $("#lc_transaction_type").val() || [];
				$.each(
						multipleTypes,
						function( intIndex, idTypes ){
							thisLink += '&lc_transaction_type[]=';
							thisLink += idTypes;
						}
				);
				
				var multipleTypes = $("#lc_facility_tranche").val() || [];
				$.each(
						multipleTypes,
						function( intIndex, idTypes ){
							thisLink += '&lc_facility_tranche[]=';
							thisLink += idTypes;
						}
				);
				
				var multipleCurrencies = $("#lc_currency").val() || [];
				$.each(
						multipleCurrencies,
						function( intIndex, idCurrency ){
							thisLink += '&lc_currency[]=';
							thisLink += idCurrency;
						}
				);
				
				var multipleLeads = $("#lc_lead_managers").val() || [];
				$.each(
						multipleLeads,
						function( intIndex, idLead ){
							thisLink += '&lc_lead_managers[]=';
							thisLink += idLead;
						}
				);
				
				var multipleSponsors = $("#lc_sponsor").val() || [];
				$.each(
						multipleSponsors,
						function( intIndex, idSponsor ){
							thisLink += '&lc_sponsor[]=';
							thisLink += idSponsor;
						}
				);
				
				if ($('#lc_hung_syndication').val() != undefined) {
					thisLink += '&lc_hung_syndication=';
					thisLink += $('#lc_hung_syndication').val();
				}
				if ($('#lc_date_from').val() != undefined) {
					thisLink += '&lc_date_from=';
					thisLink += $('#lc_date_from').val();
				}
				if ($('#lc_date_to').val() != undefined) {
					thisLink += '&lc_date_to=';
					thisLink += $('#lc_date_to').val();
				}
				if ($('#lc_commitmentdate_from').val() != undefined) {
					thisLink += '&lc_commitmentdate_from=';
					thisLink += $('#lc_commitmentdate_from').val();
				}
				if ($('#lc_commitmentdate_to').val() != undefined) {
					thisLink += '&lc_commitmentdate_to=';
					thisLink += $('#lc_commitmentdate_to').val();
				}
				if ($('#lc_hung_syndication').val() != undefined) {
					thisLink += '&lc_hung_syndication=';
					thisLink += $('#lc_hung_syndication').val();
				}
				
				//alert($('#leveraged_calendar').serialize());
				
				//thisLink += $('#leveraged_calendar').serialize();
				
				thisLink += "#calendar-tabs-content";
				
				allLink +=  thisLink;
				expectedLink += thisLink;
				announcedLink += thisLink;
				completedLink += thisLink;
				
				//var thislink = $('#lc_date_from').val();
				
				//console.log ("passed link : " + thisLink);
				
				
				
				$("a#viewall").attr('href', allLink);
				$("a#viewexpected").attr('href', expectedLink);
				$("a#viewannounced").attr('href', announcedLink);
				$("a#viewcompleted").attr('href', completedLink);
				
				$("#calendar-tabs-content").html(response); // update the DIV
				//$("div.loading-text").html("Search Completed");
				$("#calendar-tabs").find('div.ajax-loader').hide();
				
				//console.log ("success");
				$('#calendar-tabs').tabs({
					ajaxOptions: {
						async: false,
						error: function(xhr, status, index, anchor) {
								$(anchor.hash).html("Couldn't load this tab.");
							}
						},
					collapsible: false
				});
			}
		});
		return false; // cancel original event to prevent form submitting
	});
	
	$('#special_calendar').submit(function() { // catch the form's submit event
		$('#calendar-tabs').find('div.ajax-loader').show();
		$(this).find("div.loading-text").html("Loading...");
		$.ajax({ // create an AJAX call...
			data: $(this).serialize(), // get the form data
			type: $(this).attr('method'), // GET or POST
			url: $(this).attr('action'), // the file to call
			success: function(response) { // on success..			
				var allLink = 'specialcalendarall?sc_display_type=all&sc_search=search';
				var cb1link = 'specialcalendarall?sc_display_type=cb1&sc_search=search';
				var cb2link = 'specialcalendarall?sc_display_type=cb2&sc_search=search';
				var cb3link = 'specialcalendarall?sc_display_type=cb3&sc_search=search';
				var cb4link = 'specialcalendarall?sc_display_type=cb3&sc_search=search';
				var cb5link = 'specialcalendarall?sc_display_type=cb3&sc_search=search';
				var thisLink = '';
				
				if ($('#borrower').val() != undefined) {
					thisLink += '&sc_company_name=';
					thisLink += $('#borrower').val();
				}
				
				var multipleSectors = $("#sc_sector").val() || [];
				$.each(
						multipleSectors,
						function( intIndex, idSector ){
							thisLink += '&sc_sector[]=';
							thisLink += idSector;
						}
				);
				
				var multipleCountries = $("#sc_country").val() || [];
				$.each(
						multipleCountries,
						function( intIndex, idCountry ){
							thisLink += '&sc_country[]=';
							thisLink += idCountry;
						}
				);
				
				var multipleAdvisors = $("#sc_advisor").val() || [];
				$.each(
						multipleAdvisors,
						function( intIndex, idAdvisor ){
							thisLink += '&sc_advisor[]=';
							thisLink += idAdvisor;
						}
				);
				
				var multipleSponsors = $("#sc_sponsor").val() || [];
				$.each(
						multipleSponsors,
						function( intIndex, idSponsor ){
							thisLink += '&sc_sponsor[]=';
							thisLink += idSponsor;
						}
				);
				
				thisLink += "#calendar-tabs-content";
				
				allLink +=  thisLink;
				cb1link += thisLink;
				cb2link += thisLink;
				cb3link += thisLink;
				cb4link += thisLink;
				cb5link += thisLink;
				
				//var thislink = $('#sc_date_from').val();
				
				//console.log ("passed link : " + thisLink);
				
				$("a#viewall").attr('href', allLink);
				$("a#viewcb1").attr('href', cb1link);
				$("a#viewcb2").attr('href', cb2link);
				$("a#viewcb3").attr('href', cb3link);
				$("a#viewcb4").attr('href', cb4link);
				$("a#viewcb5").attr('href', cb5link);
				
				$('#calendar-tabs-content').html(response); // update the DIV
				//$("div.loading-text").html("Search Completed");
				$('#calendar-tabs').find('div.ajax-loader').hide();
				//console.log ("success");
				$('#calendar-tabs').tabs({
					ajaxOptions: {
						async: false,
						error: function(xhr, status, index, anchor) {
								$(anchor.hash).html("Couldn't load this tab.");
							}
						},
					collapsible: false
				});
			},
			complete: function() {}
		});
		return false; // cancel original event to prevent form submitting
	});
	
	$('#highyield_calendar').submit(function() { // catch the form's submit event
		$('#calendar-tabs').find('div.ajax-loader').show();
		$(this).find("div.loading-text").html("Loading...");
		$.ajax({ // create an AJAX call...
			data: $(this).serialize(), // get the form data
			type: $(this).attr('method'), // GET or POST
			url: $(this).attr('action'), // the file to call
			success: function(response) { // on success..			
				var allLink = 'highyieldcalendarall?lc_display_type=all&lc_search=search';
				var expectedLink = 'highyieldcalendarall?lc_display_type=expected&lc_search=search';
				var announcedLink = 'highyieldcalendarall?lc_display_type=announced&lc_search=search';
				var completedLink = 'highyieldcalendarall?lc_display_type=completed&lc_search=search';
				var thisLink = '';
				
				if ($('#borrower').val() != undefined) {
					thisLink += '&lc_company_name=';
					thisLink += $('#borrower').val();
				}
				
				var multipleSectors = $("#lc_sector").val() || [];
				$.each(
						multipleSectors,
						function( intIndex, idSector ){
							thisLink += '&lc_sector[]=';
							thisLink += idSector;
						}
				);
				
				var multipleCountries = $("#lc_country").val() || [];
				$.each(
						multipleCountries,
						function( intIndex, idCountry ){
							thisLink += '&lc_country[]=';
							thisLink += idCountry;
						}
				);
				
				var multipleCurrencies = $("#lc_currency").val() || [];
				$.each(
						multipleCurrencies,
						function( intIndex, idCurrency ){
							thisLink += '&lc_currency[]=';
							thisLink += idCurrency;
						}
				);
				
				var multipleLeads = $("#lc_lead_managers").val() || [];
				$.each(
						multipleLeads,
						function( intIndex, idLead ){
							thisLink += '&lc_lead_managers[]=';
							thisLink += idLead;
						}
				);
				
				var multipleSponsors = $("#lc_sponsor").val() || [];
				$.each(
						multipleSponsors,
						function( intIndex, idSponsor ){
							thisLink += '&lc_sponsor[]=';
							thisLink += idSponsor;
						}
				);
				
				var multipleSnp = $("#lc_snp").val() || [];
				$.each(
						multipleSnp,
						function( intIndex, idSnp ){
							thisLink += '&lc_snp[]=';
							thisLink += idSnp;
						}
				);
				
				var multipleMoodys = $("#lc_moodys").val() || [];
				$.each(
						multipleMoodys,
						function( intIndex, idMoodys ){
							thisLink += '&lc_moodys[]=';
							thisLink += idMoodys;
						}
				);
				
				if ($('#lc_currency').val() != undefined) {
					thisLink += '&lc_currency=';
					thisLink += $('#lc_currency').val();
				}
				if ($('#lc_lead_managers').val() != undefined) {
					thisLink += '&lc_lead_managers=';
					thisLink += $('#lc_lead_managers').val();
				}
				if ($('#lc_sponsor').val() != undefined) {
					thisLink += '&lc_sponsor=';
					thisLink += $('#lc_sponsor').val();
				}
				
				thisLink += "#calendar-tabs-content";
				
				allLink +=  thisLink;
				expectedLink += thisLink;
				announcedLink += thisLink;
				completedLink += thisLink;
				
				//var thislink = $('#lc_date_from').val();
				
				//console.log ("passed link : " + thisLink);
				
				$("a#viewall").attr('href', allLink);
				$("a#viewexpected").attr('href', expectedLink);
				$("a#viewannounced").attr('href', announcedLink);
				$("a#viewcompleted").attr('href', completedLink);
				
				$('#calendar-tabs-content').html(response); // update the DIV
				//$("div.loading-text").html("Search Completed");
				$('#calendar-tabs').find('div.ajax-loader').hide();
				//console.log ("success");
				$('#calendar-tabs').tabs({
					ajaxOptions: {
						async: false,
						error: function(xhr, status, index, anchor) {
								$(anchor.hash).html("Couldn't load this tab.");
							}
						},
					collapsible: false
				});
			},
			complete: function() {}
		});
		return false; // cancel original event to prevent form submitting
	});

	/*
	$('#leveraged_calendar').submit(function() {
		alert('Handler for .submit() called.');
		return false;
	});
	*/
	
	// Banner Animation ********************************
	setInterval( "slideSwitch()", 7000 );
	
	// Login Box **************************************
	//$("#dialog-form").dialog("destroy");
	$("#dialog-form").dialog({
		zIndex: 3999,
		autoOpen: false,
		height: 330,
		width: 340,
		modal: true,
		close: function() {
			//allFields.val('').removeClass('ui-state-error');
			var url = window.location.href.split('?');
			window.location.href = url[0];
		}
	});

	$('a.login').click(function() {
		$('#dialog-form').dialog('open');
	});
	
	$("#dialog-form-readmore").dialog({
		zIndex: 3999,
		autoOpen: false,
		height: 170,
		width: 340,
		modal: true,
		close: function() {
			var url = window.location.href.split('?');
			window.location.href = url[0];
		}
	});
	
	/* Glossary Popup */
	$('a.glossary').click(function() {
		$(this).html("Opening Glossary").delay(800);
		var gotoanchor = $(this).attr('id');
		var gloassarywindow = window.open("/clientfacing/glossary#"+gotoanchor,"Glossary","menubar=0,resizable=1,width=450,height=550,scrollbars=1,status=0,location=no,toolbar=0,directories=0");
		gloassarywindow.moveTo(0, 0);
		$('a.glossary').html("Glossary");
	});
	
	/* Scroll to open report */
	var reportID = getUrlVars()["reportID"];
	if (reportID != undefined) { 
		var array_reportID = reportID.split("#"); 
		var rID = array_reportID[0];
		var tabID = array_reportID[1];
		if (tabID == "tabs-7") {
			// Works in FF/IE but not Chrome
			//$("html,body").scrollTo( "#"+rID, 1000,  { offset: { top:-23, left:0 } } );
			// Works in Chrome and FF/IE
			$("html,body").animate({scrollTop: $("#"+rID).offset().top-23},2000);
		}
	}
	
	//$('a.readmore').click(function() {
	//	$('#dialog-form-readmore').dialog('open');
	//});
	
	// open the login dialogue if the user has tried to access a page whilst not authenticated
	// and been redirected to the login
	var sUrl = window.location.href.split("?");
	
	if (sUrl[1] != undefined) {
		
		var sUri = sUrl[1];
		var sParam = sUri.split("=");
		
		var sReadmore = sParam[1];
		sReadmore.indexOf(sParam[1]);
		
		if (sParam[0] == "lg_request" && sParam[0] != "") {
			if (sReadmore.search("readmore") != -1) {
				$('#dialog-form-readmore').dialog('open');
			} else {
				$('#dialog-form').dialog('open');
			}
		}
	}
		
	// get uv vars
	function getUrlVars() 
	{ 
	    var vars = [], hash; 
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); 
	    for(var i = 0; i < hashes.length; i++) 
	    { 
	        hash = hashes[i].split('='); 
	        vars.push(hash[0]); 
	        vars[hash[0]] = hash[1]; 
	    } 
	    return vars; 
	}
	var loginError = getUrlVars()["loginError"];
	if (loginError == 1) {
		$('#dialog-form').dialog('open');
	}

	// Validate sign up form *************************
	if ($("#signup-form")[0]) {
		$("#signup-form").validate({
			rules: {
				txt_Name: {
					required: true,
					minlength: 2
				},
				txtarea_Address: {
					required: true,
					minlength: 2
				},
				txt_Town: {
					required: true,
					minlength: 2
				},
				txt_Country: {
					required: true
				},
				txt_Postcode: {
					required: true,
					minlength: 2
				},
				txt_Email: {
					required: true,
					email: true
				},
				txt_Email_again: {
					equalTo: "#txt_Email"
				},
				txt_Phone: {
					required: true,
					minlength: 6,
					number: true
				},
				txt_PhoneOther: {
					required: false,
					minlength: 2
				},
				txt_EnquiryType: {
					required: true
				}
			},
			messages: {
				txt_Name: {
					required: "Please enter your name",
					minlength: "Your name must consist of at least 2 characters"
				},
				txtarea_Address:
				{
					required: "Please enter your address",
					minlength: "Your address must consist of at least 2 characters"
				},
				txt_Town:
				{
					required: "Please enter a town",
					minlength: "Your town must consist of at least 2 characters"
				},
				txt_Country:
				{
					required: "Please select a country"
				},
				txt_Postcode:
				{
					required: "Please enter a postcode",
					minlength: "Your postcode must consist of at least 2 characters"
				},
				txt_Email: "Please enter a valid email address, example: you@yourdomain.com",
				txt_Email_again: {
					equalTo: "Emails do not match, please check and try again"	
				},
				txt_Phone: {
					required: "Please enter a phone number either work or mobile",
					minlength: "Your phone number must consist of at least 6 numbers",
					number: "Your phone number must be numeric with no spaces"
				},
				txt_EnquiryType:
				{
					required: "Please select an enquiry type"
				}
			}
		});
		//$("input.txt_Phone").mask("99999 999999");
		//$("input.txt_Postcode").mask("**** ***");
	}
	
	
	//  Event Calendar ************************************
	if ($("#datepicker")[0]) {

		var now = new Date();
		var curr_date = now.getDate();
		var curr_month = now.getMonth();
		curr_month++;
		if (curr_date <= 9) {
			var curr_date = '0'+curr_date;
		}
		if (curr_month <= 9) {
			var curr_month = '0'+curr_month;
		}
		var curr_year = now.getFullYear();
		var formattedDate = (curr_month + "/" + curr_date + "/" + curr_year);

		$.ajax({
			url: "/clientfacing/ajaxdatepicker",
			data: "json",
			datatype: "json",
			success: function(json){

				$('#datepicker').datepicker({
					inline: true,
					firstDay: 1, 
					showOtherMonths: true,	
					selectOtherMonths: true,
					onSelect: pickDate,
					beforeShowDay: function (date) {

							for (var i = 0; i < json.length; i++) {
																
								if (new Date(json[i]).toString() == date.toString()) {
									//console.log(json[i], i, date);
									return [true, 'calender-event-highlight', 'Event'];
								}
								
							}
							return [false, ''];

					}
				});
				
				$('a.goBack').live("click",function(){ 
					$("#todays-events").html("<h3>loading events...</h3>");
		
					$.ajax({
						url: "/clientfacing/ajaxeventdetails",
						data: "ae_date="+ formattedDate,
						datatype: "html",
						success: function(data){
							$("#todays-events").html(data);
						}
					});
				});
				$('a.goBack').hide();
			}
		});
		
		$("#todays-events").html("<h3>loading events...</h3>");
		
		$.ajax({
			url: "/clientfacing/ajaxeventdetails",
			data: "ae_date="+ formattedDate,
			datatype: "html",
			success: function(data){
				$("#todays-events").html(data);
			}
		});
			
	}
		
	function pickDate(dateStr) {
		// Do something with the chosen date..
		// Ajax call
		$("#todays-events").html("<h3>loading events...</h3>");
		$.ajax({
			url: "/clientfacing/ajaxeventdetails",
			data: "ae_date="+ dateStr,
			datatype: "html",
			success: function(data){
				$("#todays-events").html(data);
				$('a.goBack').show();
			}
		});
		//alert(dateStr);
	}
	
	// BACK OFFICE JS *************************************
	if ($("#dialog-form-login")[0]) {
			$("#dialog-form-login").dialog({
			zIndex: 3999,
			autoOpen: true,
			height: 230,
			width: 340,
			modal: true,
			closeText: 'hide',
			resizable: false,
			title: 'Administration Login'
		});
	};
	
	$('#companytable tr').hover(function () {
	   $(this).toggleClass('bo-highlight');
	});
	
	$('#lltable tr').hover(function () {
	   $(this).toggleClass('bo-highlight');
	});
	
	
	$('.bo-table tr td').hover(function () {
		$(this).parent("tr").toggleClass("bo-highlight");
	    //.toggleClass('bo-highlight'); //
	});
});	

jQuery.fn.fadeThenSlideToggle = function(speed, easing, callback) {
	if (this.is(":hidden")) {
		return this.slideDown(speed, easing).fadeTo(speed, 1, easing, callback);
	} else {
		return this.fadeTo(speed, 0, easing).slideUp(speed, easing, callback);
	}
};
		
function slideSwitch() {
	var $active = $('#content-nav-bg IMG.active');

	if ( $active.length == 0 ) $active = $('#content-nav-bg IMG:last');

	var $next =  $active.next().length ? $active.next()
		: $('#content-nav-bg IMG:first');

	$active.addClass('last-active');

	$next.css({opacity: 0.0})
		.addClass('active')
		.animate({opacity: 1.0}, 3000, function() {
			$active.removeClass('active last-active');
		});
};

$.easing.custom = function (x, t, b, c, d) {
	var s = 1.70158; 
	return c*(t/=d)*t + b;
}

function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	} 
	return vars;
}

function logMaxViewRequest(tab) {
	var companyID = getUrlVars()["companyID"];
	var reportID = getUrlVars()["reportID"];
	var structuredLoanID = getUrlVars()["structuredLoanID"];
	
	// get tab id from URL
	if (reportID != undefined) {
		var array_reportID = reportID.split("#");
	}
	if (companyID != undefined) {
		var array_companyID = companyID.split("#");
	}
	if (structuredLoanID != undefined) {
		var array_structuredLoanID = structuredLoanID.split("#");
		
	}
	
	if (tab == undefined) {
		if (reportID != undefined) {
			var tab = array_reportID[1];
		}
		if (tab == undefined && companyID != undefined) {
			var tab = array_companyID[1];
		}
		if (tab == undefined & structuredLoanID != undefined) {
			var tab = array_structuredLoanID[1];
		}
	}
	
	// get company, report and structured finance ids from URL
	if (companyID != undefined) {
		var companyID = array_companyID[0];
	}
	if (reportID != undefined) {
		var reportID = array_reportID[0];
	}
	
	// structured finance id should be set as the report id
	if (structuredLoanID != undefined) {
		var reportID = structuredLoanID;
	}
	
	// set daily and hourly logs
	$.get("/clientfacing/ajaxmaxviewlog", { al_period_type: "HOURLY", al_company_id: companyID, al_report_id: reportID, al_tabs: tab } );
	$.get("/clientfacing/ajaxmaxviewlog", { al_period_type: "DAILY", al_company_id: companyID, al_report_id: reportID, al_tabs: tab } );
}


function managePrintReports( seloption , el) {
	
	var pathname = window.location.pathname; 
	
	// clear the cookie if the user wants to clear all selected reports
	if(seloption == 'clear') {
		$.cookie(pathname, '');
		
		// uncheck checkboxes
		var numReports = document.view_reports.length;
		for (i = 0; i < numReports; i++) {
			document.view_reports.reportIDS[i].checked = false;
		}
		document.select_all.reset();;
		return true;
	}
		
	// setup the array to store the selected report ids; this is written to the cookie
	reportArray = $.cookie(pathname);
	if (!reportArray) {
		var reportArray = new Array();
	} else {
		reportArray = reportArray.split(/,/);
	}
	
	// get the reports that have been checked
	var numReports = document.view_reports.length;
	for (i = 0; i < numReports; i++) {
		var reportID = document.view_reports.reportIDS[i].value;
		
		// remove report id from array
		reportArray = jQuery.grep(reportArray, function(value) {
			return value != reportID
		});
		
		if (document.view_reports.reportIDS[i].checked && reportArray.length <= 25) {
			// add report id to array
			reportArray.push(reportID);
		}
	}
	
	// select all reports on the page
	if(seloption == 'selectall') {
		$.cookie(pathname, '');
		
		if( el.checked ){
			// check all the checkboxes
			var numReports = document.view_reports.length;
			for (i = 0; i < numReports; i++) {
				var reportID = document.view_reports.reportIDS[i].value;
				document.view_reports.reportIDS[i].checked = true;
				reportArray.push(reportID);
			}
		}else{
			// uncheck all the checkboxes
			var numReports = document.view_reports.length;
			for (i = 0; i < numReports; i++) {
				var reportID = document.view_reports.reportIDS[i].value;
				document.view_reports.reportIDS[i].checked = false;
				reportArray.push(reportID);
			}
			
			// clear the cookie
			$.cookie(pathname, '');
			return true;
		}
	}
	
	// count number of stored reports
	if (reportArray.length > 25) {
		alert('You may not select to print more than 25 reports.');
		return true;
	}
	
	
	//alert(reportArray);
	// update cookie, storing the selected report ids. expire in 2 hours
	var date = new Date(); 
	date.setTime(date.getTime() + (120 * 60 * 1000)); 
	$.cookie(pathname, reportArray, { expires: date });
}






