﻿/*
INIT.JS 
--------
Functions should run only after the content has loaded.
SEE BOTTOM OF FILE FOR INIT CALLS.

Last modified: 
2009-05-01 sshepar3:
	Consolidated init.js with textpager.js.  
	Moved core.js fixes into here from masterpage.

/* dynamic search form in header. Adding a timeout avoids an error in IE6 */
function addSearchWrapper(){
	if ($('#search_wrapper').length > 0) {
		$('#search_wrapper').append('<form id="fedsearch" method="get"></form>');
		$('#fedsearch').append('<select id="fedsearch_s" name="s"><option>All Sites</option><option>This Site</option><option>People</option></select>');
		$('#fedsearch').append('<input id="fedsearch_k" name="k" type="text"/>');
		$('#fedsearch').append('<input id="fedsearch_search" onclick="return fedsearch()" type="submit" value="Search"/>');	
		
	    $('#extSearch_wrapper').hide();	
	 	$('#search_wrapper').show();
	} else {
		$('#google_search').hide();
		$('#extSearch_wrapper').show();
	}
	fedsearch(true);
}
if (window.ie6) setTimeout(addSearchWrapper, 200);
else addSearchWrapper();



/* [START] repair broken functions in Sharepoint's core.js */
if (typeof AbsLeft == 'function'){
	AbsLeft = function (obj) {
		var x=obj.offsetLeft;
		var parent=obj.offsetParent;
		while (parent.tagName != "BODY" && parent.tagName != "HTML" && parent != null)
		{
			x+=parent.offsetLeft;
			parent=parent.offsetParent;
		}
		x+=parent.offsetLeft;
		return x;
	}
}
if (typeof AbsTop == 'function'){

	function AbsTop(obj, overflown)
	{
		var top = 0, className = obj.className;
		do {
			top += obj.offsetTop || 0;
			obj = obj.offsetParent;
		} while (obj);
		overflown = overflown || (className = 'ms-lookuptypeintextbox') ? [{'scrollTop':130}] : [];
		for (var i=0,len=overflown.length; i<len; i++){
			top -= overflown[i].scrollTop || 0;
		};
		return top;
	}
}
/* [END] repair broken functions in Sharepoint's core.js */



/*
These functions are executed after the page loads.
*/
function initCDUPresentation(){

	/*Rel 2.0 - Added following 3 lines*/
	var todaysDate = new Date();
	var year = todaysDate.getFullYear();
	$("#lbl_Year").text(year);	

	hideEmptyAreas();
		
	/* Secondary Content Toggles */
	new secondaryContentToggle();
		
	/*
	Enable the main navigation menu.
	*/
	$("li.menu", thisHtml).hover(navMain(false), navMain(true));
	$("li.menu ul", thisHtml).css("visibility", "visible");
	$("li.menu ul", thisHtml).hide();
	
	
	/* 
	Set "All" as the default in the Search menu and then hide it. 
	*/
	$('#site_controls select[id$=SBScopesDDL]', thisHtml).val("").hide();
	
	
	/* 
	Create a "set home Page" link for IE users.
	*/
	if (document.all){
		var setHomePageEl = $('#setHomePage');
		setHomePageEl.html('<a href="javascript:;">Make This My Home Page</a>');
		$('a', setHomePageEl).click(function() { 
			this.style.behavior='url(#default#homepage)';
			this.setHomePage('http://www.at.ford.com');
		});
	}
	
	/* fix table heights in IE6 */
	if (document.all){
		$('table.ms-cal-tweekitem, table.ms-cal-tdayitem').each(function(i, tt) {
			var h = $(tt.parentNode.parentNode).attr('scrollHeight') * $(tt.parentNode).attr('rowspan');
			$(tt).css('height', h);
		});
	}

	
	/* 
	Adjust the widths of search functions
	$('#ctl00_PlaceHolderSearchArea_ctl01_SBScopesDDL', thisHtml).css('width','135px');
	$('#search_wrapper input[id*="InputKeywords"]', thisHtml).css('width', '130px');
	$('#ctl00_PlaceHolderSearchArea_ctl01_SBScopesDDL', thisHtml).appendTo($('#search_wrapper input[id*="InputKeywords"]', thisHtml).parent());
	*/
	
	/* soft-insert the Textpager Form so Sharepoint doesn't fail when saving the masterpage */
	var textPagerChildren = $('#send_text_body').children();
	$('<form action="http://vm4.dearborn.ford.com/cgi/textpage" target="_blank" method="post" name="page_754" id="textPagerForm"></form>')
		.appendTo($('#send_text_body'))
		.append(textPagerChildren);
		
	/* Check for Sharepoint logged-in user and set content appropriately. */
	var authorizedUser = $('input[id=isLocal]').length == 0 ? false : true;
	if (authorizedUser) {
		$('.authShow').show();
		$('.authHide').hide();
	} else {
		$('.unAuthShow').show();
		$('.unAuthHide').hide();
	}
	var fbaUser = $('span[id$=MyLinksMenu]').length == 0 && authorizedUser ? true : false;
	if (fbaUser) {
		$('.fbaHide').hide();
		$('.fbaShow').show();
	} 


};



/*
********* TEXTPAGER FUNCTIONS **********
*/

function initTextPager(){

	/* textPagerForm field events */
	$('#textPagerForm_pageto').change(function() {stripSpaces()});
	$('#textPagerForm_addphone_checkbox').click(function(){clearPhone()});
	$('#textPagerForm_phone').click(function(){selectPhone()});
	$('#textPagerForm_send').click(function(){checkTextPagerForm()});
	$('#textPagerForm_clear').click(function(){clearMessage()});

	/*
	Get Field Values from Web Service
	*/
	var editFields = ["Account Name", "Work Phone"];
	var propertyNames = ["AccountName","WorkPhone"]
	soapCall(editFields, propertyNames );
	
};


/* replace leading and trailing spaces */
function stripSpaces(){
    var pageto = $('#textPagerForm_pageto');    
    pageto.val(pageto.val().replace(/^\W+/,'').replace(/\W+$/,''))
}

/* Check "Include phone" and insert work phone if needed */
function selectPhone(){
	$('#textPagerForm_addphone_checkbox').get(0).checked = true;
	if ($('#textPagerForm_phone').val().length == 0) {
		$('#textPagerForm_phone').val($('#textPagerForm_workphone').val());
	}
}	

/* clear phone when "include phone" is unchecked. */
function clearPhone(){
	$('#textPagerForm_phone').val( !$('#textPagerForm_addphone_checkbox').get(0).checked ? 
		"" : $('#textPagerForm_workphone').val()
	);
}

/* Clear CDSIDs and message */
function clearMessage(){
	$('#textPagerForm_pageto').val("");
	$('#textPagerForm_msg').val("");
}

/* open the pager window if WSL is not available. */
function openTextPagerWindow()
{			
	var sendEmail = ($('#textPagerForm_backup_checkbox').get(0).checked) ? 'Y' : 'N';
	var addphone = ($('#textPagerForm_addphone_checkbox').get(0).checked) ? 'N' : 'Y';
	var action = "http://vm4.dearborn.ford.com/cgi/textpage" + 
		"?PAGETO=" + escape($('#textPagerForm_pageto').val()) + 
		"&MSG=" + escape($('#textPagerForm_msg').val()) + 
		"&BACKUP=" + sendEmail  + 
		"&CCNOTE=" + sendEmail + 
		"&NOPHONE=" + addphone + 
		"&PHONE=" + escape($('#textPagerForm_phone').val());
	
	/* 
	If the WSL cookie exists, then post directly, otherwise pop up a window so the user can log in.
	On POST, some other values are used.
	*/
	if (document.cookie.indexOf("WSL-") >= 0) {
		$('#textPagerForm_backup').val( (sendEmail=='Y') ? "on" : "off" );
		$('#textPagerForm_ccnote').val( (sendEmail=='Y') ? "on" : "off" );
		$('#textPagerForm_addphone').val( (addphone=='N') ? "on" : "off" );
		$('#textPagerForm').target = "winpopup";
		$('#textPagerForm').action = "http://vm4.dearborn.ford.com/cgi/textpage";
		$('#textPagerForm').submit();
	} else {
		window.open(action,'winpopup','resizable=yes,menubar=yes,toolbar=no,location=no,directories=no,width=500,height=220,scrollbars=yes');
	}
}

function checkTextPagerForm(){
	var suffixsize,trimsize,trimphone,emsg="";
	var blnSendPage = true;
	if ($('#textPagerForm_pageto').val() == "") {
		emsg += "You must include CDS id(s) to send the page to.\n";
		blnSendPage = false;
	}
		
	$('#textPagerForm_msg').val(trim($('#textPagerForm_msg').val()));
	if ($('#textPagerForm_msg').val() == "") {
		emsg += "You must include the text to be sent";
		blnSendPage = false;
	}
	
		
	if( $('#textPagerForm_addphone_checkbox').get(0).checked == true ) {
	    suffixsize = $('#textPagerForm_phone').val().length + 3;
		if ( suffixsize > 68 ) {
		trimsize = 65 - suffixsize;
		trimphone = $('#textPagerForm_phone').val().slice(0,trimsize);
		emsg += "\nYour from data is greater than 68 characters.";
		emsg += "\nAutomatically truncate the message? ";
		emsg += "\nTruncated from data below:";
		emsg += "\n";
		emsg += "\n" + from.slice(0,34);
		emsg += "\n" + from.slice(34,68);
		blnSendPage = blnSendPage && confirm( emsg );
		$('#textPagerForm_phone').get(0).focus();
			if( blnSendPage == true ) {
			document.page_754.phone.value = trimphone;
			 }
		}
    }
    
    if (blnSendPage == true)
    {
		
		var blnCheckLength; //Boolean value set when text message exceeds 160 char limit
		var intPhNameLabel = 14; //Characters used for Phone and Name Labels
		var strMsgText = $('#textPagerForm_msg').val();
		
		//Look for carriage  returns and newline characters in the message and replace them by a white space
		strMsgText = strMsgText.replace(/\r/g, " ");
		$('#textPagerForm_msg').val(strMsgText.replace(/\n/g, " "));
		//Store the formatted message text in a variable to be used when the user clicks cancel on the confirmation screen
		var strOrigMsgText = $('#textPagerForm_msg').val();
		//Check if the total length of the paged message with the Phone-Name Label and their values is greater than the limit of 160 chars
		if ($('#textPagerForm_msg').val().length > 160){
			// intmsginfo is the length of the From - Phone information and the From - Phone labels appended with the text page message 
			//intFinalTextLength is the length of the message being sent without From and Phone information
			//intNewLimit is the limit on the length after taking out the chars used in From and Phone information
			//trunchar is the number of characters being truncated from the message typed in by the user.
			blnCheckLength = false; 
			var intmsginfo;
			var intNewLimit;
			var intFinalTextLength;
			//intmsginfo = ((document.page_754.pagefrom.value.length) + (document.page_754.phone.value.length) + intPhNameLabel);
			intmsginfo = $('#textPagerForm_msg').val().length;
			intNewLimit = 160 - intmsginfo; 
			inttextlength = $('#textPagerForm_msg').val().length;
			intTrunchar = inttextlength - intNewLimit;
			intFinalTextLength =  inttextlength;/// - intTrunchar;
			//Displays the truncated message in 4 rows on the confirmation screen
			emsg = "\nYour message is greater than 160 characters.";
			emsg += "\nTruncated to 160 characters.";
			emsg += "\n" + $('#textPagerForm_msg').val().slice(intFinalTextLength);
			blnSendPage = blnSendPage && confirm( emsg );
			$('#textPagerForm_msg').get(0).focus();
		}     
    
		/*limit the text message to the 160 char limit*/
		$('#textPagerForm_msg').val($('#textPagerForm_msg').val().slice(0,160)) 
		
             
	    if (blnSendPage == true) {
			openTextPagerWindow();
		} else {
			//The message text box should contain the entire message the user had typed.
			$('#textPagerForm_msg').val(strOrigMsgText);
			$('#textPagerForm_msg').get(0).focus();
		} 		 		
	} else {
		alert(emsg);
	}
	    
} // [END] checkTextPagerForm	


function pagefrom() { 
	var strName = $('#textPagerForm_pagefrom').val();
	if (strName.indexOf("FORDNA1\\") >= 0) return strName.substr(8) ;
	else return $('#textPagerForm_pagefrom').val();
}

function trim(strText) { return strText.replace(/^\s+/,'').replace(/\s+$/,''); }



/*
INIT
*/
initCDUPresentation();
initTextPager()
