$(document).ready(function() {

if($("#floatheader")) { 
	$("#floatheader").floatHeader(); 
}

//Toggle help for more info on add trans for

$(".toggle_container").hide(); 

	//Switch the "Open" and "Close" state per click
	$("a.helptrigger").toggle(function(){
		$(this).addClass("active");
		}, function () {
		$(this).removeClass("active");
	});

	//Slide up and down on click
	$("a.helptrigger").click(function(){
		$(this).next(".toggle_container").slideToggle("slow");
	});


//Notes Are on Rating Module on Provider Details Page

$('.notes').hide();
$('.instructions').show();
$('a.note').hover(function() {
     var id = $(this).attr('id');
     $('.instructions').hide();
     $('#note' + id).show();
     },
		function() {
		var id = $(this).attr('id');
   		$('.instructions').show();
   		$('#note' + id).hide();		
     }); 
     
     $('a.note').click(function(){ return false });
     $('div.radtingmodule li.total a').click(function(){ return false }); 


//Login form on homepage - handles default values of text fields.
if ($('.multiple_callback').example) {
	$('.multiple_callback').example(function() {
	 return $(this).attr('title'); 
	});
};


//Showing glossary providers

$("a.glossaryletter").click(function(e){
    // stop normal link click
    e.preventDefault();
	var target = $(this).attr('title');
//alert(target);
	//clear active styles
	$(this).parent().parent().find("li").each(function() {
		$(this).removeClass('active');
	});
	//now set the class on this item
	$(this).parent().addClass('active');
    //clear the glossary results
	var glossaryresults = $("ul.glossaryresults[id='glossaryresults_"+target+"']");
    glossaryresults.empty();
    var loadUrl = $("span[id='loadurl_"+target+"']").html();
	var param = $(this).html();
//alert(loadUrl+'='+param);
/*
	var currTime = new Date().getTime();
	$.ajax({
		type: "GET",
		url: loadUrl,
		data: ({glossaryitem : param, nt: currTime}),
		success: function(responseText) {
alert(responseText);
			var responseJSON = eval( '(' + responseText + ')'); 
alert(responseJSON.glossaryresults.length);			
			if (responseJSON.error) glossaryresults.append('<li class="instructions"><p>'+responseJSON.error+'</p></li>');
			else
			{
				for (var i=0;i<responseJSON.glossaryresults.length;i++)
				{
//alert(glossaryresults[i].name);				
					glossaryresults.append('<li><a href="#" class="glossaryresult" id="'+target+'-'+responseJSON.glossaryresults[i].id+'">'+responseJSON.glossaryresults[i].name+'</a></li>');
				}
			}
		}
	});
*/
	var currTime = new Date().getTime();
	$.get(
		loadUrl,
		{glossaryitem: param, nt: currTime },
		function(responseText){
			if (responseText.error) glossaryresults.append('<li class="instructions"><p>'+responseText.error+'</p></li>');
			else
			{
				for (var i=0;i<responseText.glossaryresults.length;i++)
				{
//alert(glossaryresults[i].name);				
					glossaryresults.append('<li><a href="#" class="glossaryresult" id="'+target+'-'+responseText.glossaryresults[i].id+'">'+responseText.glossaryresults[i].name+'</a></li>');
				}
			}
		},
		"json"
	);	
	return false;
});

function updateDropZoneItem(dropzone,id,name)
{
//alert(id+'='+name);
	//we always empty the drop zone first because it can only have one item which is the one we are adding
	dropzone.empty();
	//add it to the drop zone
	var elemName = dropzone.attr('id');
//alert(elemName);	
	var newLi = '<li>';
	newLi += '<label>';
	newLi += '<input type="checkbox" class="jcheckbox" name="'+elemName+'" value="'+id+'" checked><span>'+name+'</span>';
	newLi += '</label>';
	newLi += '</li>';
	dropzone.append(newLi);
}

function updateDropZoneList(dropzone,id,name)
{
//alert(id+'='+name);
	//if the id already exists in the drop zone
	var elemFound = false;
	dropzone.find("li label input").each(function() {
//alert(id);
//alert($(this).attr('value'));	
		if ($(this).attr('value')==id)
		{
			elemFound = true;
			//if it is not checked, check it
			if (!$(this).attr('checked')) $(this).attr('checked',true);
		}
	});
//alert(elemFound);	
	if (!elemFound)
	{
		//else add it to the drop zone
		var elemName = dropzone.attr('id');
//alert(elemName);	
		var newLi = '<li>';
		newLi += '<label>';
		newLi += '<input type="checkbox" class="jcheckbox" name="'+elemName+'[]" value="'+id+'" checked><span>'+name+'</span>';
		newLi += '</label>';
		newLi += '</li>';
		dropzone.append(newLi);
	}	
}

$("ul.glossaryresults").click(function(e){
	var $tgt = $(e.target);
	if ($tgt.is('a')) 
	{
	    // stop normal link click
	    e.preventDefault();
		var target = $tgt.attr('id');
		if (target)
		{ 
			var target_components = target.split('-');
			var model = target_components[0];
			var fieldname = target_components[1];
			var id = target_components[2];
		}
		var dropzoneid = model+'-'+fieldname;
		var name = $tgt.html();
//alert(target);
//alert(model+' '+fieldname+' '+id+'='+name);
		var dropzone = $("ul.dropzonelist[id='"+dropzoneid+"']");
		//for placement agents, only one item can be selected at one time
		if (model=='transactions' && fieldname=='placementagentproviders_id') updateDropZoneItem(dropzone,id,name);
		else updateDropZoneList(dropzone,id,name);
	}
});

// SUBSCRIPTIONS - attach JS to subscription listings so that admin can select them for application when adding or editing subscriptions for a user
$("a[id^='subscriptions']").click(function(e){
    // stop normal link click
    e.preventDefault();
	var $tgt = $(e.target);
	//find id
	var target = $tgt.attr('id');
	if (target)
	{ 
		var target_components = target.split('-');
		var id = target_components[1];
	}
	
	var title = $("span[id='title-"+id+"']").text();
	var cost = $("span[id='cost-"+id+"']").text();
	var validuntil = $("span[id='validuntil-"+id+"']").text();
	
	$("input[name='usersubscriptions-title']").val(title);
	$("input[name='usersubscriptions-cost']").val(cost);
	$("input[name='usersubscriptions-validuntil']").val(validuntil);
	
	return false;
});

// PRIVATE DATA SUBSCRIPTIONS - attach JS to private data subscription listings so that admin can select them for application when adding or editing subscriptions for a user
$("a[id^='privatedatasubscriptions']").click(function(e){
    // stop normal link click
    e.preventDefault();
	var $tgt = $(e.target);
	//find id
	var target = $tgt.attr('id');
	if (target)
	{ 
		var target_components = target.split('-');
		var id = target_components[1];
	}
	
	var title = $("span[id='title-"+id+"']").text();
	var cost = $("span[id='cost-"+id+"']").text();
	var validuntil = $("span[id='validuntil-"+id+"']").text();
	
	$("input[name='userprivatedatasubscriptions-title']").val(title);
	$("input[name='userprivatedatasubscriptions-cost']").val(cost);
	$("input[name='userprivatedatasubscriptions-validuntil']").val(validuntil);
	
	return false;
});

// MARKET SEGMENT SUBSCRIPTIONS - attach JS to market segment subscription listings so that admin can select them for application when adding or editing subscriptions for a user
$("a[id^='marketsegmentsubscriptions']").click(function(e){
    // stop normal link click
    e.preventDefault();
	var $tgt = $(e.target);
	//find id
	var target = $tgt.attr('id');
	if (target)
	{ 
		var target_components = target.split('-');
		var id = target_components[1];
	}
	
	var title = $("span[id='title-"+id+"']").text();
	var cost = $("span[id='cost-"+id+"']").text();
	var validuntil = $("span[id='validuntil-"+id+"']").text();
	
	$("input[name='users_marketsegments-subscriptiontitle']").val(title);
	$("input[name='users_marketsegments-subscriptioncost']").val(cost);
	$("input[name='users_marketsegments-subscriptionvaliduntil']").val(validuntil);
	
	return false;
});

//TOGGLE GEOGRAPHIC REGIONS DIVS ON PROVIDER ADD AND ADVSEARCH PAGES
$("input[id='byregion']").click(function(){
	var geographiccoverage = $("input[id='byregion']").val();
	toggleGeographicCoverageRegions($("input[id='byregion']").is(":checked"),geographiccoverage);
});
$("input[id='bystate']").click(function(){
	var geographiccoverage = $("input[id='bystate']").val();
	toggleGeographicCoverageRegions($("input[id='bystate']").is(":checked"),geographiccoverage);
});
$("input[id='bycountry']").click(function(){
	var geographiccoverage = $("input[id='bycountry']").val();
	toggleGeographicCoverageRegions($("input[id='bycountry']").is(":checked"),geographiccoverage);
});
$("select[name='providers-geographiccoverage']").change(function(){
	var geographiccoverage = $("select[name='providers-geographiccoverage'] option:selected").val();
	$("div[id^='providers-geographiccoverage_']").hide();
	$("div[id='providers-geographiccoverage_"+geographiccoverage+"']").show();
});

//DIFFERENT TRANSACTION FIELDS BASED ON DIFFERENT TRANSACTION TYPES
//hard coding the ids for debt and equity transactions here
//yucky but other solutions are intensive at this stage
//do this upon initialization of transaction add or edit
if ($("select[name='transactions-transactiontypes_id']").length) {
//alert(transactiontype_id);
	var transactiontype = $("select[name='transactions-transactiontypes_id'] option:selected").val();
//alert(transactiontype);	
	if (transactiontype!=undefined) toggleTransactionFieldsByTransactionType(transactiontype);
}
//also do this when user selects a different transaction type
$("select[name='transactions-transactiontypes_id']").change(function(){
	var transactiontype = $("select[name='transactions-transactiontypes_id'] option:selected").val();
	toggleTransactionFieldsByTransactionType(transactiontype);
	//also product types are based on transaction types so if the selection changes uncheck any selected product types
	$("input[name='transactions-producttypes_id']").attr("checked",false); 
});

//PROVIDER RATINGS: DIFFERENT PRODUCT TYPE BASED ON DIFFERENT TRANSACTION TYPES
//hard coding the ids for debt and equity transactions here
//yucky but other solutions are intensive at this stage
//do this upon initialization of transaction add or edit
if ($("select[name='providerratings-transactiontypes_id']").length) {
//alert(transactiontype_id);
	var transactiontype = $("select[name='providerratings-transactiontypes_id'] option:selected").val();
	if (transactiontype!=undefined) toggleTransactionFieldsByTransactionType(transactiontype);
}
//also do this when user selects a different transaction type
$("select[name='providerratings-transactiontypes_id']").change(function(){
	var transactiontype = $("select[name='providerratings-transactiontypes_id'] option:selected").val();
	toggleTransactionFieldsByTransactionType(transactiontype);
	//also product types are based on transaction types so if the selection changes uncheck any selected product types
	$("input[name='providerratings-producttypes_id']").attr("checked",false); 
});

//PROVIDERS - DIFFERENT INDUSTRIES BASED ON DIFFERENT MARKET SEGMENTS
//do this upon initialization of transaction add or edit
//$("input[name='providers_marketsegments-marketsegments_id[]']").each(function(index) {
//});
if ($("input[name='providers_marketsegments-marketsegments_id[]']").length) {
	toggleProviderIndustryFieldsByMarketSegment();
}
//also do this when user selects a different marketsegment
$("input[name='providers_marketsegments-marketsegments_id[]']").click(function(){
	toggleProviderIndustryFieldsByMarketSegment(); //$(this)
});
$("input[id='industries_selectall']").click(function() {
	if ($(this).attr('checked')) {
		$("li[id^='industries_marketsegments-']:visible").children('label').children('input').attr('checked', true);
	}
	else {
//		$("li[id^='industries_marketsegments-']:visible").each(function(index) {
//			$(this).attr('checked', false);
//		});
		$("li[id^='industries_marketsegments-']:visible").children('label').children('input').attr('checked', false);
	}
});

function toggleProviderIndustryFieldsByMarketSegment() {
//alert(elem_marketsegment.val());
//	var marketsegment = elem_marketsegment.val();
//	var selected = elem_marketsegment.attr('checked');
//alert(selected);
	//make a list of all checked market segments
	//make sure none of them belong to a checked market segment
	var checkedmarketsegments = new Array();
	$("input[name='providers_marketsegments-marketsegments_id[]']:checked").each(function(index) {
		checkedmarketsegments[checkedmarketsegments.length] = $(this).val();
	});
	
	//toggle select all option
	if (checkedmarketsegments.length>0) $("span[id='industries_selectall_container']").show(); else $("span[id='industries_selectall_container']").hide();
//alert(checkedmarketsegments);

	$("[id^='industries_marketsegments-']").each(function(index) {
		var temp = $(this).attr('id').split('-');
		var marketsegments = temp[1].split(',');

//alert(marketsegment);
//alert(marketsegments);
		//if any of the industries' assigned market segments are in the checked market segments list
		//show it, else hide it	
		//check if it's in the array
		var marketsegmentchecked = false;
		for (var i=0;i<marketsegments.length;i++) {
			for (var j=0;j<checkedmarketsegments.length;j++) {
				if (jQuery.trim(marketsegments[i])==checkedmarketsegments[j]) {
					marketsegmentchecked = true;
					break;
				}
			}
		}
		if (marketsegmentchecked) {
//alert('hurrah!');
			$(this).show();
		} else {
//alert('hiding ');
			$(this).hide();
		}
	});
}

//MEMBERS - DIFFERENT INDUSTRIES BASED ON DIFFERENT MARKET SEGMENTS
//do this upon initialization of transaction add or edit
if ($("select[name='users_marketsegments-marketsegments_id']").length) {
//alert($("select[name='users_marketsegments-marketsegments_id']"));
	var selectedmarketsegment = $("select[name='users_marketsegments-marketsegments_id'] option:selected").val();
//alert(selectedmarketsegment);	
	if (selectedmarketsegment!=undefined) toggleUserIndustryFieldsByMarketSegment($("select[name='users_marketsegments-marketsegments_id']"));
}
//also do this when user selects a different marketsegment
$("select[name='users_marketsegments-marketsegments_id']").change(function(){
	toggleUserIndustryFieldsByMarketSegment($(this));
});

function toggleUserIndustryFieldsByMarketSegment(elem_marketsegment) {
//alert(elem_marketsegment.val());
	var selectedmarketsegment = elem_marketsegment.val();
//alert('yes');

	$("[id^='industries_marketsegments-']").each(function(index) {
		var temp = $(this).attr('id').split('-');
		var marketsegments = temp[1].split(',');

//alert(marketsegment);
//alert(marketsegments);
		//if any of the industries' assigned market segments are in the checked market segments list
		//show it, else hide it	
		//check if it's in the array
		var marketsegmentchecked = false;
		for (var i=0;i<marketsegments.length;i++) {
			if (jQuery.trim(marketsegments[i])==selectedmarketsegment) {
				marketsegmentchecked = true;
				break;
			}
		}
		if (marketsegmentchecked) {
//alert('hurrah!');
			$(this).show();
		} else {
//alert('hiding ');
			$(this).hide();
		}
	});
}

function toggleTransactionFieldsByTransactionType(transactiontype)
{
//alert(transactiontype);
	//hide all
	$(".transactiontype_debt").hide();
	$(".transactiontype_equity").hide();
	$(".transactiontype_iposervices").hide();
	$(".transactiontype_insurance").hide();
	$(".transactiontype_retirementmgmt").hide();
	$(".transactiontype_tradefinancing").hide();
	//now show as necessary
	if (transactiontype=='2') {
		//show debt
		$(".transactiontype_debt").show();
	}
	else if (transactiontype=='3') {
		//show equity
		$(".transactiontype_equity").show();
	}
	else if (transactiontype=='8') {
		//show
		$(".transactiontype_iposervices").show();
	}
	else if (transactiontype=='9') {
		//show
		$(".transactiontype_insurance").show();
	}
	else if (transactiontype=='10') {
		//show
		$(".transactiontype_retirementmgmt").show();
	}
	else if (transactiontype=='11') {
		//show
		$(".transactiontype_tradefinancing").show();
	}
}

function toggleGeographicCoverageRegions(checked,geographiccoverage)
{
//alert(geographiccoverage);	
	if (checked) $("div[id='providers-geographiccoverage_"+geographiccoverage+"']").show();
	else $("div[id='providers-geographiccoverage_"+geographiccoverage+"']").hide();
}
		//Hide div w/class stateslist
/*		
	   $(".stateslist").hide();

		// Add onclick handler to checkbox w/id bystate
	   $("#bystate").click(function(){
		// If checked
		if ($("#bystate").is(":checked"))
		{
			//show the hidden div
			$(".stateslist").show("fast");
		}
		else
		{	   
			//otherwise, hide it 
			$(".stateslist").hide("fast");
		}
	  });
*/	  

/*
	//Hide div w/id extra
	   $("#extra").css("display","none");

		// Add onclick handler to checkbox w/id checkme
	   $("#checkme").click(function(){
		
		// If checked
		if ($("#checkme").is(":checked"))
		{
			//show the hidden div
			$("#extra").show("fast");
		}
		else
		{	   
			//otherwise, hide it 
			$("#extra").hide("fast");
		}
	  });

*/

// Third way == UPDATE jQuery 1.3
//$("input[type=checkbox][checked]").each( 
//    function() { 
//       $("input[type=checkbox][checked]").parent().addClass("selected");
//    } 
//);

    // Inserts arrow next to side navigation when active
    $('span.error').append('<img src="/app/templates/img/error-arrow.gif" class="errorarrow">'); 
    //$('<img src="http://vqs104.pair.com/vfhub/app/templates/img/error-arrow.gif" class="errorarrow">').append('span.error');
    
    // Inserts arrow on subscription error
    $('div.subscription-expired-error').append('<img src="/app/templates/img/error-arrow-up.gif" class="errorarrow">'); 
     

});


