//**************************
// EXTEND jQuery
//**************************
//**************************
//Global functions
//**************************
var tSizes = new Array( "text1", "text2", "text3", "text4");
var default_tSize=tSizes[1];
var default_tStyle="widthNormal";
var cookieoptions = { path: '/', expires: 10 };

function switchStylestyleText(styleName)
{
	var cookiestyleName=$.cookie('styletext');
	if (styleName=="less" || styleName=="more")
	{
		var i1=parseInt(cookiestyleName.replace(/text/gi, ''));
		var pos=i1-1;
		if (styleName=="less") pos=(pos==0)?pos:pos-1;
		if (styleName=="more") pos=(pos==tSizes.length-1)?pos:pos+1;
		var endstyleName=tSizes[pos];
	}
	else if (styleName=="start")
	{
		if (cookiestyleName==null) endstyleName=default_tSize;
		else var endstyleName=cookiestyleName;
	}
	$('link[rel*=style][title*=text]').each(function(i)
	{
			this.disabled = true;
			if (this.getAttribute('title') == endstyleName) this.disabled = false;
	});
	$.cookie('styletext', endstyleName,cookieoptions);

	return endstyleName;
};

function switchStylestyle(styleName)
{
		if (styleName=="start") styleName=$.cookie('stylewidth');
		if (styleName==null) styleName=default_tStyle;
		$('link[rel*=style][title*=width]').each(function(i)
		{
			this.disabled = true;
			if (this.getAttribute('title') == styleName) this.disabled = false;
		});
		$.cookie('stylewidth', styleName,cookieoptions);
};

function indexOf(needle, haystack)
{
	for (var i=0;i<haystack.length;i++)
		if (haystack[i] == needle) return i;
	return false;
};

function cokSession()
{
	var cookieName=$.cookie('ALEPH_SESSION_ID');

	if (cookieName!=$('#sessid').text())
	{
		$.cookie('ALEPH_SESSION_ID', $('#sessid').text(),cookieoptions);
	}
};

function open_window (loc)
{
	self.name="main";
	if ((navigator.appVersion.indexOf("MSIE 5.0") != -1) && (navigator.appName.indexOf("Explorer") != -1))
	{
		var w = window.open ("","win1","height=550,width=770,toolbar=no,scrollbars=yes,resizable=yes,status=yes");
		w.document.write("<html>\n");
		w.document.write('<body onLoad="window.location.href=');
		w.document.write("'" + loc + "';\n"); 
		w.document.write('"'); 
		w.document.write("</body>\n");
		w.document.write("</html>\n");
		w.document.close();
    }
	else { var w = window.open (loc,"win1","height=550,width=770,toolbar=no,scrollbars=yes,resizable=yes,status=yes"); }
	w.focus();
};

function open_window_medium (loc)
{
	self.name="main";
	if ((navigator.appVersion.indexOf("MSIE 5.0") != -1) && (navigator.appName.indexOf("Explorer") != -1))
	{
		var w = window.open ("","win1","height=350,width=450,toolbar=no,scrollbars=yes,resizable=yes,status=yes");
		w.document.write("<html>\n");
		w.document.write('<body onLoad="window.location.href=');
		w.document.write("'" + loc + "';\n"); 
		w.document.write('"'); 
		w.document.write("</body>\n");
		w.document.write("</html>\n");
		w.document.close();
    }
	else { var w = window.open (loc,"win1","height=350,width=450,toolbar=no,scrollbars=yes,resizable=yes,status=yes"); }
	w.focus();
};


function open_window_small (loc)
{
	self.name="main";
	if ((navigator.appVersion.indexOf("MSIE 5.0") != -1) && (navigator.appName.indexOf("Explorer") != -1))
	{
		var w = window.open ("","win1","height=225,width=208,toolbar=no,scrollbars=yes,resizable=yes,status=yes");
		w.document.write("<html>\n");
		w.document.write('<body onLoad="window.location.href=');
		w.document.write("'" + loc + "';\n"); 
		w.document.write('"'); 
		w.document.write("</body>\n");
		w.document.write("</html>\n");
		w.document.close();
    }
	else { var w = window.open (loc,"win1","height=225,width=208,toolbar=no,scrollbars=yes,resizable=yes,status=yes"); }
	w.focus();
};

function open_window_confirm (loc,frame)
{
	self.name=frame; 
	if ((navigator.appVersion.indexOf("MSIE 5.0") != -1) && (navigator.appName.indexOf("Explorer") != -1))
	{
		var w = window.open ("","win1","height=220,width=450,scrollbars,resizable");
		w.document.write("<html>\n");
		w.document.write('<body onLoad="window.location.href=');
		w.document.write("'" + loc + "';\n");
		w.document.write('"');
		w.document.write("</body>\n");
		w.document.write("</html>\n");
		w.document.close();
    }
	else { var w = window.open (loc,"win1","height=220,width=450,scrollbars,resizable"); }
	w.focus();
}

function googleTranslateElementInit()
{
	new google.translate.TranslateElement(
	{
		pageLanguage: 'pt',
		includedLanguages: 'de,es,fr,en'
	},
	'google_translate_element');
}

function mensagemCC(what,selector, elementid, msgtype, msgimage,msgwith, msghtml)
{
	if (elementid!="") { $('#'+elementid).remove(); elementid='id="'+elementid+'" '; }
	if (msgwith!="100%" && msgwith!="") msgwith='width:'+msgwith+';';
	else msgwith="";
	if (msghtml!='')
	{
		if (what=="prepend") $(selector).prepend('<div '+elementid+'class="'+msgtype+' ui-corner-all" style="'+msgwith+'padding: 0.4em;"><p><span class="'+msgimage+'" style="float: left;margin-right: 0.3em;"></span>'+msghtml+'</p></div>');
		else if (what=="append") $(selector).append('<div '+elementid+'class="'+msgtype+' ui-corner-all" style="'+msgwith+'padding: 0.4em;"><p><span class="'+msgimage+'" style="float: left;margin-right: 0.3em;"></span>'+msghtml+'</p></div>');
		else if (what=="before") $(selector).before('<div '+elementid+'class="'+msgtype+' ui-corner-all" style="'+msgwith+'padding: 0.4em;"><p><span class="'+msgimage+'" style="float: left;margin-right: 0.3em;"></span>'+msghtml+'</p></div>');
		else if (what=="after") $(selector).after('<div '+elementid+'class="'+msgtype+' ui-corner-all" style="'+msgwith+'padding: 0.4em;"><p><span class="'+msgimage+'" style="float: left;margin-right: 0.3em;"></span>'+msghtml+'</p></div>');
		else if (what=="html") $(selector).html('<div '+elementid+'class="'+msgtype+' ui-corner-all" style="'+msgwith+'padding: 0.4em;"><p><span class="'+msgimage+'" style="float: left;margin-right: 0.3em;"></span>'+msghtml+'</p></div>');
	}
};


function gera_MODAL()
{
	if ($("#dialog-message").length==0)
	{
		var r_message=	"<div id=\"dialog-message\" title=\"\">\n"+
						"	<p>\n"+
						"	</p>\n"+
						"</div>\n";
		$("#catalog").prepend(r_message);
	}
	else $("#dialog-message").dialog("destroy");
};


/* resto */
function isValidEmailAddress(emailAddress)
{
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function isValidCodigopostal(codigopostal)
{
	var pattern = new RegExp(/^([0-9]{4})(|\-([0-9]{3}))$/i);
	return pattern.test(codigopostal);
}

function isValidTelefone(telefone)
{
	var pattern = new RegExp(/^(|00([0-9]{2,3})( |)|\+([0-9]{2,3})( |)|\(([0-9]{2,3})\)( |))([0-9]{7,})$/i);
	return pattern.test(telefone);
}

function isValidUserPass(userpass)
{
	userpass=userpass.replace(/\@ciejd\.pt/,"");
	var pattern = new RegExp(/^[A-Za-z\d\.\-_@]{4,20}$/i);

	return pattern.test(userpass);
}

function limpacamposformulario(LNG,lang,pagina)
{
	$.each(LNG[lang][pagina], function(indice, valor)
	{
		if (indice!="page_title" && indice!="page_title2")
		{
			if ($("#"+indice).val() == valor) { $("#"+indice).val(""); }
		}
	});
}

function toTitleCaseCC(str)
{
	str=str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});

	//Particulas apassivantes
	str=str.replace(/ Se /g, " se ");
	str=str.replace(/\-Se /g, "-se ");

	//Preposições - http://gramaticaportuguesa.blogs.sapo.pt/5865.html
	str=str.replace(/ A /g, " a ");
	str=str.replace(/ Ante /g, " ante ");
	str=str.replace(/ Após /g, " após ");
	str=str.replace(/ Até /g, " até ");
	str=str.replace(/ Com /g, " com ");
	str=str.replace(/ Conforme /g, " conforme ");
	str=str.replace(/ Contra /g, " contra ");
	str=str.replace(/ Consoante /g, " consoante ");
	str=str.replace(/ De /g, " de ");
	str=str.replace(/ Desde /g, " desde ");
	str=str.replace(/ Durante /g, " durante ");
	str=str.replace(/ Em /g, " em ");
	str=str.replace(/ Excepto /g, " excepto ");
	str=str.replace(/ Entre /g, " entre ");
	str=str.replace(/ Mediante /g, " mediante ");
	str=str.replace(/ Para /g, " para ");
	str=str.replace(/ Perante /g, " perante ");
	str=str.replace(/ Por /g, " por ");
	str=str.replace(/ Salvo /g, " salvo ");
	str=str.replace(/ Sem /g, " sem ");
	str=str.replace(/ Segundo /g, " segundo ");
	str=str.replace(/ Sob /g, " sob ");
	str=str.replace(/ Sobre /g, " sobre ");
	//str=str.replace(/ Trás /g, " trás ");

	//Artigos definidos - http://gramaticaportuguesa.blogs.sapo.pt/5865.html
	str=str.replace(/ O /g, " o ");
	str=str.replace(/ A /g, " a ");
	str=str.replace(/ Os /g, " os ");
	str=str.replace(/ As /g, " as ");

	//Contração de preposições com artigos definidos - http://gramaticaportuguesa.blogs.sapo.pt/5865.html
	str=str.replace(/ Ao /g, " ao ");
	str=str.replace(/ À /g, " à ");
	str=str.replace(/ Aos /g, " aos ");
	str=str.replace(/ Às /g, " às ");
	str=str.replace(/ Do /g, " do ");
	str=str.replace(/ Da /g, " da ");
	str=str.replace(/ Dos /g, " dos ");
	str=str.replace(/ Das /g, " das ");
	str=str.replace(/ No /g, " no ");
	str=str.replace(/ Na /g, " na ");
	str=str.replace(/ Nos /g, " nos ");
	str=str.replace(/ Nas /g, " nas ");
	str=str.replace(/ Pelo /g, " pelo ");
	str=str.replace(/ Pela /g, " pela ");
	str=str.replace(/ Pelos /g, " pelos ");
	str=str.replace(/ Pelas /g, " pelas ");

	//Artigos indefinidos - http://gramaticaportuguesa.blogs.sapo.pt/5865.html
	str=str.replace(/ Um /g, " um ");
	str=str.replace(/ Uma /g, " uma ");
	str=str.replace(/ Uns /g, " uns ");
	str=str.replace(/ Umas /g, " umas ");

	//Contração de preposições com artigos indefinidos - http://gramaticaportuguesa.blogs.sapo.pt/5865.html
	str=str.replace(/ Dum /g, " dum ");
	str=str.replace(/ Duma /g, " duma ");
	str=str.replace(/ Duns /g, " duns ");
	str=str.replace(/ Dumas /g, " dumas ");
	str=str.replace(/ Num /g, " num ");
	str=str.replace(/ Numa /g, " numa ");
	str=str.replace(/ Nuns /g, " nuns ");
	str=str.replace(/ Numas /g, " numas ");

	//Conjunções subordinativas - http://www.prof2000.pt/users/drfilipeaz/PagsParali/FuncLing/conjuncao.htm
	str=str.replace(/ Que /g, " que ");
	str=str.replace(/ Quando /g, " quando ");
	str=str.replace(/ Porque /g, " porque ");

	//Conjunções coordenativas - http://www.prof2000.pt/users/drfilipeaz/PagsParali/FuncLing/conjuncao.htm
	str=str.replace(/ E /g, " e ");
	str=str.replace(/ Ou /g, " ou ");
	str=str.replace(/ Mas /g, " mas ");

    return str;
}

function criacampodata(fieldid) 
{
	var d = new Date();
	var curr_year = d.getFullYear();

	$("#"+fieldid).datepicker({
		dateFormat: 'yy-mm-dd',
		prevText: 'Anterior',
		nextText: 'Seguinte',
		monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
		monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
		dayNamesMin: ['Do', 'Se', 'Te', 'Qu', 'Qu', 'Se', 'Sá'],
		dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
		dayNames: ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'],
		showAnim: 'blind',
		yearRange: '1900:'+curr_year,
		changeMonth: true,
		changeYear: true
	});
}

function criacampodata_pequeno(fieldid) 
{
	var d = new Date();
	var curr_year = d.getFullYear();
	var end_year = curr_year+10;

	$("#"+fieldid).datepicker({
		dateFormat: 'yy-mm-dd',
		prevText: 'Anterior',
		nextText: 'Seguinte',
		monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
		monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
		dayNamesMin: ['Do', 'Se', 'Te', 'Qu', 'Qu', 'Se', 'Sá'],
		dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
		dayNames: ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'],
		showAnim: '',
		yearRange: '1900:'+end_year,
		changeMonth: true,
		changeYear: true
	});
}

function forms_predefined_value(LNG,what,formid)
{
	$.each(LNG[lang][what], function(indice, valor)
	{
		if (indice!="page_title" && indice!="page_title2")
		{
			if ($("#"+indice).val()==valor) { $("#"+indice).removeClass("inactive").addClass("inactive");}
			else if ($("#"+indice).val()=='') {$("#"+indice).addClass("inactive");$("#"+indice).val(valor); }
			else $("#"+indice).removeClass("inactive");
			$("#"+indice).bind("focus", function() { if ($(this).val()==valor) { $(this).val(""); $(this).removeClass("inactive");} })
			             .bind("blur", function() { if ($(this).val()=='') {$(this).addClass("inactive");$(this).val(valor); } });
		}
	});

	$("#"+formid).bind("submit", function(e)
	{
		if (formid!="fPe" && formid!="formCCLSpecial")
		{
			$.each(LNG[lang][what], function(indice, valor)
			{
				if (indice!="page_title" && indice!="page_title2")
				{
					if ($("#"+indice).val() == valor) { $("#"+indice).val(""); }
				}
			});
		}
		//Pesquisa catalogos
		else if (formid=="formCCLSpecial")
		{
			if (what=="Financial support")
			{
				$('#ccl_term').val('alldocuments');
				if ($('#partccl1').val()!="" && $("#partccl1").val()!=LNG[lang][what]["partccl1"]) $('#ccl_term').val($('#ccl_term').val()+" AND "+$('#partccl1').val())
				if ($('#partccl2').val()!="") $('#ccl_term').val($('#ccl_term').val()+" AND "+$('#partccl2').val())
				if ($('#partccl3').val()!="") $('#ccl_term').val($('#ccl_term').val()+" AND "+$('#partccl3').val())
			}
			else if (what=="Bibliographic")
			{
				if ($('#partccl1').val()!="" && $("#partccl1").val()!=LNG[lang][what]["partccl1"] && $('#partccl2').val()=="") $('#ccl_term').val($('#partccl1').val());
				else if ($('#partccl1').val()!="" && $("#partccl1").val()!=LNG[lang][what]["partccl1"] && $('#partccl2').val()!="") $('#ccl_term').val($('#partccl1').val()+" AND "+$('#partccl2').val());
				else if (($('#partccl1').val()=="" || $("#partccl1").val()==LNG[lang][what]["partccl1"]) && $('#partccl2').val()!="") $('#ccl_term').val($('#partccl2').val());
				else if (($('#partccl1').val()=="" || $("#partccl1").val()==LNG[lang][what]["partccl1"]) && $('#partccl2').val()=="") $('#ccl_term').val('WDT=(19790101->20201231)');
			}
			else
			{
				if ($("#ccl_term_cat").val() == "" || $("#ccl_term_cat").val() == LNG[lang][what]["ccl_term_cat"] || $("#ccl_term_cat").val().length < 3)
				{
					if ($('#caterr_search').length == 0) mensagemCC('append','label[for=ccl_term_cat]', 'caterr_search', 'ui-state-error ui-corner-all', 'ui-icon ui-icon-alert','46.8em', 'Tem de preencher o campo \'Expressão de pesquisa\' com mais de 3 caracteres.<br/>Exemplo: europa.');
					//alert(LNG_FillSearch);
					return false;
				}
			}
		}
		//Pesquisa geral
		else
		{
			if ($("#cPe").val() == "" || $("#cPe").val() == LNG[lang][what]["cPe"])
			{
				alert(LNG_FillSearch);
				return false;
			}
			else if ($("#cPe").val().length < 3 )
			{
				alert(LNG_FillSearchWord);
				return false;
			}
		}
		return true;
	});
}

function isSet( variable )
{
return( typeof( variable ) != 'undefined' );
}


function url_encode_text(str) {
return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function urldecode(str) {
str = unescape(str).replace(/\+/g, ' ');
return str;
}

/*
String.prototype.titleCase 1.0

An implementation of John Gruber's TitleCase.pl in JavaScript.
(http://daringfireball.net/projects/titlecase/TitleCase.pl)

TitleCase.pl Documentation:

    #   This filter changes all words to Title Caps, and attempts to be clever
    #   about *un*capitalizing small words like a/an/the in the input.
    #
    #   The list of "small words" which are not capped comes from
    #   the New York Times Manual of Style, plus 'vs' and 'v'. 
    #
    #   John Gruber
    #   http://daringfireball.net/
    #   10 May 2008
    #
    #   License: http://www.opensource.org/licenses/mit-license.php
    #


Usage:
  js> "Sub-Phrase With a Small Word in Quotes: 'a Trick, Perhaps?'".toTitleCase()
  "Sub-Phrase With a Small Word in Quotes: 'A Trick, Perhaps?'"



Uses Steven Levithan's Cross-Browser Split (note: this replaces your
hosts's native split method).

By Jon Hohle <http://hohle.net>
21.May.2008
MIT Licence <http://www.opensource.org/licenses/mit-license.php>

*/


/*
    Cross-Browser Split 0.2.1
    By Steven Levithan <http://stevenlevithan.com>
    MIT license
*/

var nativeSplit = nativeSplit || String.prototype.split;

String.prototype.split = function (s /* separator */, limit) {
    // If separator is not a regex, use the native split method
    if (!(s instanceof RegExp))
        return nativeSplit.apply(this, arguments);

    /* Behavior for limit: If it's...
     - Undefined: No limit
     - NaN or zero: Return an empty array
     - A positive number: Use limit after dropping any decimal
     - A negative number: No limit
     - Other: Type-convert, then use the above rules */
    if (limit === undefined || +limit < 0) {
        limit = false;
    } else {
        limit = Math.floor(+limit);
        if (!limit)
            return [];
    }

    var flags = (s.global ? "g" : "") + (s.ignoreCase ? "i" : "") +
        (s.multiline ? "m" : ""),
        s2 = new RegExp("^" + s.source + "$", flags),
        output = [],
        lastLastIndex = 0,
        i = 0,
        match;

    if (!s.global)
        s = new RegExp(s.source, "g" + flags);

    while ((!limit || i++ <= limit) && (match = s.exec(this))) {
        var zeroLengthMatch = !match[0].length;

        // Fix IE's infinite-loop-resistant but incorrect lastIndex
        if (zeroLengthMatch && s.lastIndex > match.index)
            s.lastIndex = match.index; // The same as s.lastIndex--

        if (s.lastIndex > lastLastIndex) {
            // Fix browsers whose exec methods don't consistently
            // return undefined for non-participating capturing groups
            if (match.length > 1) {
                match[0].replace(s2, function () {
                    for (var j = 1; j < arguments.length - 2; j++) {
                        if (arguments[j] === undefined)
                            match[j] = undefined;
                    }
                });
            }

            output = output.concat(
                this.slice(lastLastIndex, match.index),
                (match.index === this.length ? [] : match.slice(1)));
            lastLastIndex = s.lastIndex;
        }

        if (zeroLengthMatch)
            s.lastIndex++;
    }

    return (lastLastIndex === this.length) ?
        (s.test("") ? output : output.concat("")) :
        (limit      ? output : output.concat(this.slice(lastLastIndex)));
};



// give a hoot, don't pollute
var __TitleCase = {
    __smallWords: ['a', 'an', 'and', 'as', 'at', 'but',
        'by', 'en', 'for', 'if', 'in', 'of', 'on', 'or',
        'the', 'to', 'v[.]?', 'via', 'vs[.]?',
	     'a', 'as', 'os', 'os',
	     'um', 'uns', 'uma', 'umas', 
	     'de', 'do', 'dos', 'da', 'das', 
	     'e', 'por', 'com',
	     'à', 'às', 'aos'

	],

    init: function() {
        this.__smallRE = this.__smallWords.join('|');
        this.__lowerCaseWordsRE = new RegExp(
            '\\b(' + this.__smallRE + ')\\b', 'gi');
        this.__firstWordRE = new RegExp(
            '^([^a-zA-Z0-9 \\r\\n\\t]*)(' + this.__smallRE + ')\\b', 'gi');
        this.__lastWordRE = new RegExp(
            '\\b(' + this.__smallRE + ')([^a-zA-Z0-9 \\r\\n\\t]*)$', 'gi');
    },

    toTitleCase: function(string) {
        var line = '';

        var split = string.split(/([:.;?!][ ]|(?:[ ]|^)["“])/);

        for (var i = 0; i < split.length; ++i) {
            var s = split[i];

            s = s.replace(
                /\b([a-zA-Z][a-z.'’]*)\b/g,
                this.__titleCaseDottedWordReplacer);

            // lowercase the list of small words
            s = s.replace(this.__lowerCaseWordsRE, this.__lowerReplacer);

            // if the first word in the title is a small word then capitalize it
            s = s.replace(this.__firstWordRE, this.__firstToUpperCase);

            // if the last word in the title is a small word, then capitalize it
            s = s.replace(this.__lastWordRE, this.__firstToUpperCase);

            line += s;
        }

        // special cases
        line = line.replace(/ V(s?)\. /g, ' v$1. ');
        line = line.replace(/(['’])S\b/g, '$1s');
        line = line.replace(/\b(AT&T|Q&A)\b/ig, this.__upperReplacer);

        return line;
    },

        
    __titleCaseDottedWordReplacer: function (w) {
        return (w.match(/[a-zA-Z][.][a-zA-Z]/)) ? w : __TitleCase.__firstToUpperCase(w);
    },

    __lowerReplacer: function (w) { return w.toLowerCase() },

    __upperReplacer: function (w) { return w.toUpperCase() },

    __firstToUpperCase: function (w) {
        var split = w.split(/(^[^a-zA-Z0-9]*[a-zA-Z0-9])(.*)$/);
        split[1] = split[1].toUpperCase();
        return split.join('');
    },

    test: function() {
        var testStrings = [
            "Q&A With Steve Jobs: 'That's What Happens In Technology'",
            "What Is AT&T's Problem?",
            "Apple Deal With AT&T Falls Through",
            "this v that",
            "this vs that",
            "this v. that",
            "this vs. that",
            "The SEC's Apple Probe: What You Need to Know",
            "'by the Way, small word at the start but within quotes.'",
            "Small word at end is nothing to be afraid of",
            "Starting Sub-Phrase With a Small Word: a Trick, Perhaps?",
            "Sub-Phrase With a Small Word in Quotes: 'a Trick, Perhaps?'",
            'Sub-Phrase With a Small Word in Quotes: "a Trick, Perhaps?"',
            '"Nothing to Be Afraid of?"',
            '"Nothing to Be Afraid Of?"',
            'a thing'];


        var validStrings = [
            "Q&A With Steve Jobs: 'That's What Happens in Technology'",
            "What Is AT&T's Problem?",
            "Apple Deal With AT&T Falls Through",
            "This v That",
            "This vs That",
            "This v. That",
            "This vs. That",
            "The SEC's Apple Probe: What You Need to Know",
            "'By the Way, Small Word at the Start but Within Quotes.'",
            "Small Word at End Is Nothing to Be Afraid Of",
            "Starting Sub-Phrase With a Small Word: A Trick, Perhaps?",
            "Sub-Phrase With a Small Word in Quotes: 'A Trick, Perhaps?'",
            'Sub-Phrase With a Small Word in Quotes: "A Trick, Perhaps?"',
            '"Nothing to Be Afraid Of?"',
            '"Nothing to Be Afraid Of?"',
            'A Thing'];

        for (var i = 0; i < testStrings.length ; ++i)
        {
            var s = testStrings[i].toTitleCase();
            if (s != validStrings[i])
            {
                alert(s + '\ndoes not match\n' + validStrings[i]);
                return false;
                break;
            }
        }    
        return true;
    }
};

__TitleCase.init();

function toTitleCase(string) { return __TitleCase.toTitleCase(string); }

String.prototype.toTitleCase = function() { return toTitleCase(this); }

