// Html encoding for input

function htmlEncode(s)
{
    var str = new String(s);
    
    str = str.replace(/&/g, "&amp;");
    str = str.replace(/"/g, "&quot;");
    str = str.replace(/'/g, "&#039;");
    str = str.replace(/</g, "&lt;");
    str = str.replace(/>/g, "&gt;");
    
    return str;
}

// BOOKMARK //
function bookmarkPage() {
	var url = document.location // get location of the site
	var title = document.title // get title of the site
	var txt = "bookmark this site"; 
  if (window.sidebar) { 
    // Mozilla Firefox Bookmark		
    window.sidebar.addPanel(title, url,"");	
  } 
  else if( window.external ) { 
    // IE Favorite		
    window.external.AddFavorite( url, title); 
  }	
  else if(window.opera && window.print) { 
    // Opera Hotlist		
		txt += "using (Ctrl+T)"; 
		window.alert(txt);
  } 
	else
	{ 
	// if its netscape then pop up a alert message for the time being
		txt += "using (Ctrl+D)"; 
		window.alert(txt);
	} 
}


//POPUP//
function popup(mylink, windowname)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
   href=mylink;
else
   href=mylink.href;
window.open(href, windowname, 'width=500,height=550,scrollbars=no');
return false;
}

function popupLarge(mylink, windowname)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
   href=mylink;
else
   href=mylink.href;
window.open(href, windowname, 'width=700,height=700,scrollbars=no');
return false;
}

// TOOLTIP
this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$(".tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<span id='tooltip'>"+ this.t +"</span>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
		$("#tooltip").bind('tooltipChanged', function(e, ttString)
		{
		    $('#tooltip').text(ttString);
		});		
    },
	function(){
		this.title = this.t = $('#tooltip').text();
		$("#tooltip").remove();
    });	
	$(".tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};




// JQUERY 

$(document).ready(function() {
	
	$('a.newWindow').click(function(){
		window.open(this.href);
		return false;	
	});
	
	/*$('.siteSearch').before('<div id="textSizer"><a href="#" class="small" title="Small font size">A</a><a href="#" class="medium" title="Medium font size">A</a><a href="#" class="large" title="Large font size">A</a></div>');*/
	$('#textSizer').show();
		$('.small').click(function(){
			setActiveStyleSheet('default');
		});
		$('.medium').click(function(){
			setActiveStyleSheet('medium');
		});
		$('.large').click(function(){
			setActiveStyleSheet('large');
		});
	
	
	$('#emailTool').before('<li id="printTool"><a href="#" class="styleswitch" rel="print">Print page</a></li>');
	$('#questionTool').before('<li id="bookmarkTool"><a href="#">Bookmark this page</a></li>');
	$('#bookmarkTool a').click(function(){
		bookmarkPage();
		return false;
	});
	$('#printTool a').click(function(){
		print();
		return false;
	});
	
	tooltip();	
	
	$('.listing[class!="listing multi"] li:odd, table.listing tr:odd, .listDisplay li:odd, ul.multi li:nth-child(4n-2), ul.multi li:nth-child(4n-1), table.list tr:odd td, .searchResults .searchListing:odd').addClass('alt');
	
	$('a[rel=download]').addClass('new-window');
	$('a.new-window').click(function(){
		window.open(this.href);
		return false;	
	});
	
	/*
	$('.faq li div').hide();
	$('.faq li a').click(function(){
		$(this).siblings('div').slideToggle('fast');	
	});
	*/
	
	// Form field clear/re-populate
	function resetFields(){
	$(':input[class=searchField], :input[class=textField]').focus(function(){
		if (this.value == this.defaultValue && this.value == "Type keyword here"){
			this.value = '';
		}
	});
	$(':input[class=searchField], :input[class=textField]').blur(function(){
		if (this.value == ''){
			this.value = this.defaultValue;
			}
		});
	};
	$(function(){
		resetFields();	
	});
		
/*	$('.errorMssg').hide();
	function errorMessage(){
		$('.submitBtn').click(function(){
			if ($('#searchFAQ').val() == "Type keyword here") {
				$('.errorMssg').show();
				return false;
			}
			else
				return true;
		});
	}
	$(function(){
		errorMessage();	
	});
*/

    // SAP - Tooltip
	$('.tip ul').hide();
	
	function InsertToolTip(checkbox){
		if ($(checkbox).is(':checked'))
		{
			$(checkbox).siblings('label').addClass('selected').siblings('ul').slideDown('3000');
		}
		else if ($(checkbox).not(':checked'))
		{
			$(checkbox).siblings('label').removeClass('selected').siblings('ul').slideUp('3000');
		}
	};
	$('.tip input:checkbox').click(function(){
		InsertToolTip($(this));
	})
	InsertToolTip($('.tip input:checkbox:checked'));
	
	// SAP - Popup
	$('.surveyBuilder.display div.tip').hide().prepend('<span class="popup-header"><a href="#" title="Close window" class="icon-close"><img src="http://www.commissioningsupport.org.uk/cs/Themes/boxwood/images/common/close.gif" title="close" alt="Close window" /></a></span>');
	$('a.tip').addClass('icon-popup');
	$('.popup h6 img').hide();
	
	function ShowPopup(icon){
		$('div' + icon.attr('href') + ':hidden').slideDown();  // This pulls the href from the link (#tip1) and adds it to the div as it's id		
	};
	function ClosePopup(icon){
		$(icon).parents().parents('div.popup:visible').slideUp('fast');
	}
	function ClosePopupIcon(icon){
		$(icon).next().next('div.popup:visible').slideUp('fast');
	}
	
	$('a.tip').mouseover(function(){
		ShowPopup($(this));
		return false;
	})
	$('a.icon-close, a.tip').click(function(){
		ClosePopup($(this));
		return false;
	})	
	$('a.tip').click(function(){
		ClosePopupIcon($(this));
		return false;
	})

	// Registration Form
	
	// If central government checkbox is selected on load, hide mandatory asterisks for region and childrens trust
	
	if ($('#organisation .centralGovt:checked').length > 0)
	{
	    $('#region .regionLabel span.mandatory').hide();
	    $('#trusts .trustLabel span.mandatory').hide();
	}
	
	// If a user selects central government in the organisation section, hide mandatory asterisks for region and childrens trust fields
	
	$('#organisation .centralGovt').click(function()
	{
	    $('#region .regionLabel span.mandatory').toggle();
	    $('#trusts .trustLabel span.mandatory').toggle();
	});
	
	$('#organisation .textField, #region .textField, #role .textField').hide();
	
	// Open textfields if textboxes already clicked on page load
	$('#organisation li input[type=checkbox]:checked, #region li input[type=checkbox]:checked, #role li input[type=checkbox]:checked').siblings('.textField').toggle();
	
	// Open textfields on textbox click
	$('#organisation li input[type=checkbox], #region li input[type=checkbox], #role li input[type=checkbox]').click(function(){
		$(this).siblings('.textField').toggle();
	});	
	
	 $('#organisation .notApplicable').click(function(){
		if ($('#organisation :input[class=checkbox]').attr('disabled') != '') 
		{
			$('#organisation :input[class=checkbox]').attr('disabled', '');
			$('#organisation label').removeClass('disabled');
		}
		else 
		{
			$('#organisation :input[class=checkbox]').attr('checked', '').attr('disabled', 'disabled');
			$('#organisation label').addClass('disabled');
			$('.textField').hide();
		}
	});
	
	/*$('#trusts').hide();
	$('#submitRegion').click(function(){
		$('#trusts').show();
		return false;
	});
	
	$('.trustList').hide();
	$('#region li input[@type=checkbox]').click(function(){
		$(this).next().next('.trustList').toggle();
	});
	*/
	
	$('#trusts').hide();
	
	$('span.checkboxSelectAllContainer').replaceWith('<input type="submit" value="select all" class="submitBtn checkboxSelectAll" />');
	$('span.selectAllContainer').replaceWith('<input type="submit" value="select all" class="submitBtn selectAll" />');
	$('span.checkboxSelectAllInterestsContainer').replaceWith('<input type="submit" value="select all" class="submitBtn checkboxSelectAllInterests" />');
	
	$('.selectAll').click(function(){
		if ($(this).parent().children('select').attr('disabled') == '') {
			var values = [];
			$(this).parent().children('select').children().each(function(){
				if ($(this).is('option')) 
				{
					values.push($(this).val());
				}
				else if ($(this).is('optgroup')) 
					$(this).children().each(function(){
						values.push($(this).val());
					});
			});
			$(this).parent().children('select').val(values);
			$(this).parent().children('select').trigger('click');
		}
		return false;
	});
	
	$('.checkboxSelectAll').click(function(){
		if (!$(this).parent().parent().find('.notApplicable').is(':checked'))
		{
			$(this).parent().parent().find("[class!='checkbox notApplicable'][class!='checkbox other']:checkbox").not(':checked').each(function() {
				$(this).trigger('click');
			});
		}
		return false;
	});
	
	$('.checkboxSelectAllInterests').click(function(){
		$(this).parent().parent().parent().find(":checkbox").not(':checked').each(function() {
			$(this).trigger('click');
		});
		return false;
	});
	
	 $('#region .next').remove();
	 $('.notApplicable').click(function(){
		if ($(this).parent().siblings().children('select').attr('disabled') != '') 
		{
			$(this).parent().siblings().children('select').attr('disabled', '');
		}
		else 
		{
			$(this).parent().siblings().children('select').val([]);
			$(this).parent().siblings().children('select').attr('disabled', 'disabled');
		}
	});
	
	$('.regionList').click(function() {
	    if ($('.regionList').attr('disabled') == '') {
			$('#trusts').slideDown();
		}
		return false;
		
	});
	
	$('.subSelect').hide();
	$('.select').children('li').children('.checkbox').click(function(){
		$(this).siblings('label').toggleClass('selected');
		$(this).parents('li').children('.subSelect').slideToggle();
	});
	
    // PR addition - code to display appropriate Children's Trusts depending on selected region
    
    function addTrustsToSelect()
    {
        $('.trustList').empty();
        $('.regionList option:selected').each(function()
        {
            for (var i = 0; i < trustRegions.length; i++)
            {
                if (trustRegions[i].name == $(this).text())
                {
                    $('.trustList').append("<optgroup label='" + trustRegions[i].name + "'></optgroup>");
                    for (var j = 0; j < trustRegions[i].trusts.length; j++)
                    {
                        $(".trustList optgroup[label=" + trustRegions[i].name + "]").append("<option value='" + trustRegions[i].trusts[j].value + "'>" + trustRegions[i].trusts[j].text + "</option>");
                    }
                }
            }
        });
    }
    
    if (!($.browser.msie && ($.browser.version == "6.0" || $.browser.version == "5.5" || $.browser.version == "5.0")))
    {
        var trustRegions = [];
        
        $('.trustList optgroup').each(function()
        {
            var thisRegionName = $(this).get(0).label;
            var thisRegionTrusts = [];
            
            $(this).children().each(function()
            {
                thisRegionTrusts.push({text: $(this).text(), value: $(this).val()});
            });
            
            trustRegions.push({name: thisRegionName, trusts: thisRegionTrusts});
        });
        
        addTrustsToSelect();
        $('.regionList').click(addTrustsToSelect);
    }
    
    /* Cleaner, less well supported (IE :() version
    function addTrustsToSelect()
    {
        $('.trustList optgroup').hide();
        $('.regionList option:selected').each(function()
        {
            for (var i = 0; i < trustRegions.length; i++)
            {
                if (trustRegions[i].name == $(this).text())
                {
                    $('.trustList optgroup[label=' + trustRegions[i].name + ']').show();
                }
            }
        });
    }
    */
    
    // End PR addition
    
    // PR addition to Create Event page - clear/select all
    
    $('input.selectAll').click(function()
    {
        if ($(this).val() == "Clear All")
        {
            $(this).val("Select All");
            $(this).parent().next().find('input[type=checkbox]').each(function()
            {
                if ($(this).is(':checked'))
                    $(this).trigger('click');
            });
        }
        else
        {
            $(this).val("Clear All");
            $(this).parent().next().find('input[type=checkbox]').each(function()
            {
                if (!$(this).is(':checked'))
                    $(this).trigger('click');
            });
        }   
    });
    
    /**
     * SAPM
     *
     * Permissions section
     */
    
    var toolTipTextSelect = 'select all';
    var toolTipTextUnselect = 'unselect all';
    
    if ($('#tableBody span.chkSubmit input').size() == $('#tableBody span.chkSubmit input:checked').size())
    {
        $('input#submitSelectAll').attr('checked', true);
        $('#submitSelectAllLabel').text(toolTipTextUnselect);
    }
    
    if ($('#tableBody span.chkView input').size() == $('#tableBody span.chkView input:checked').size())
    {
        $('input#viewSelectAll').attr('checked', true);
        $('#viewSelectAllLabel').text(toolTipTextUnselect);
    }
    
    $('input#submitSelectAll').click(function()
    {
        var doCheckBoxes = false;
        if ($(this).is(':checked'))
            doCheckBoxes = true;
        
        $('#tableBody').find('span.chkSubmit input').each(function()
        {
            if (doCheckBoxes)
            {
                if (!$(this).is(':checked'))
                {
                    $(this).attr('checked', true);
                    $('#submitSelectAllLabel').text(toolTipTextUnselect);
                }
            }
            else
            {
                if ($(this).is(':checked'))
                {
                    $(this).attr('checked', false);
                    $('#submitSelectAllLabel').text(toolTipTextSelect);
                }
            }
        });
    });
    
    $('#tableBody span.chkSubmit input').click(function()
    {
        if (!$(this).is(':checked'))
        {
            $('input#submitSelectAll').attr('checked', false);
            $('#submitSelectAllLabel').text(toolTipTextSelect);
        }
        else
        {
            if ($('#tableBody span.chkSubmit input').size() == $('#tableBody span.chkSubmit input:checked').size())
            {
                $('input#submitSelectAll').attr('checked', true);
                $('#submitSelectAllLabel').text(toolTipTextUnselect);
            }
        }
    });
    
    $('input#viewSelectAll').click(function()
    {
        var doCheckBoxes = false;
        if ($(this).is(':checked'))
            doCheckBoxes = true;
        
        $('#tableBody').find('span.chkView input').each(function()
        {
            if (doCheckBoxes)
            {
                if (!$(this).is(':checked'))
                {
                    $(this).attr('checked', true);
                    $('#viewSelectAllLabel').text(toolTipTextUnselect);
                }
            }
            else
            {
                if ($(this).is(':checked'))
                {
                    $(this).attr('checked', false);
                    $('#viewSelectAllLabel').text(toolTipTextSelect);
                }
            }
        });
    });
    
    $('#tableBody span.chkView input').click(function()
    {
        if (!$(this).is(':checked'))
        {
            $('input#viewSelectAll').attr('checked', false);
            $('#viewSelectAllLabel').text(toolTipTextSelect);
        }
        else
        {
            if ($('#tableBody span.chkView input').size() == $('#tableBody span.chkView input:checked').size())
            {
                $('input#viewSelectAll').attr('checked', true);
                $('#viewSelectAllLabel').text(toolTipTextUnselect);
            }
        }
    });
    
    /**
     * End permissions section
     */
    
});



