﻿/*
JTILITIES.JS
------------------
Utilities and functions for @Ford which rely on JQuery.

Last Modified:
	2009-05-01 sshepar3:
		Consolidated FordUserProfile.js into jtilities.js.
----------------------------------------------------------------------
Description : Commented out array.filter due to conflicts with SharePoints wpadder.js file. This prevents IE from being able to "Add Web Parts"
Last modified Date: 2011-11-22
Last modified By: slittl31
Last modified By : vkamara2 (Message: Object doesn't support this property or method - Line: 1368)
----------------------------------------------------------------------


/*---------------------------------------------------------------------------- 
			[START] - Taken from Mootools 1.11
---------------------------------------------------------------------------- */

/*
FUNCTION: (Array) $keys
	Returns an array containing all the keys in the object passed.  Taken from Mootools 1.11

Returns:
	An array containing all the values of the hash
*/
var $keys = function(obj){
	var keys = [];
	for (var property in obj) keys.push(property);
	return keys;
}

/*
FUNCTION: (Array) $values
	Returns an array containing all the values, in the same order as the keys returned by <Hash.keys>.  Taken from Mootools 1.11

Returns:
	An array containing all the values of the hash
*/
var $values = function(obj){
	var values = [];
	for (var property in obj) values.push(obj[property]);
	return values;
}

/* 
FUNCTION (Object) $defined
-------------------------
Determines if a variable has been defined and is not null.
*/
function $defined(obj) {
	return (obj != undefined && obj != null) ? true : false;
}

/* 
FUNCTION (Object) $choose
-------------------------
Returns the first object with a value.
*/
function $choose(){
	for (var i=0,len=arguments.length;i<=len; i++){
		var arg = arguments[i];
		if ($defined(arg)) return arg;
	}
	return null;
};

/*
FUNCTION $type
-----------------------
Returns the type of the object passed.  Borrowed from Mootools 1.11.  
*/
function $type(obj){
	if (obj == undefined) return false;
	if (obj.htmlElement) return 'element';
	var type = typeof obj;
	if (type == 'object' && obj.nodeName){
		switch(obj.nodeType){
			case 1: return 'element';
			case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
		}
	}
	if (type == 'object' || type == 'function'){
		switch(obj.constructor){
			case Array: return 'array';
			case RegExp: return 'regexp';
		}
		if (typeof obj.length == 'number'){
			if (obj.item) return 'collection';
			if (obj.callee) return 'arguments';
		}
	}
	return type;
};

/*
Class: Class 
	The base class object of the <http://mootools.net> framework.
	Creates a new class, its initialize method will fire upon class instantiation.
	Initialize wont fire on instantiation when you pass *null*.

Arguments:
	properties - the collection of properties that apply to the class.

Example:
	(start code)
	var Cat = new Class({
		initialize: function(name){
			this.name = name;
		}
	});
	var myCat = new Cat('Micia');
	alert(myCat.name); //alerts 'Micia'
	(end)
*/

var Class = function(properties){
	var klass = function(){
		return (arguments[0] !== null && this.initialize && $type(this.initialize) == 'function') ? this.initialize.apply(this, arguments) : this;
	};
	$extend(klass, this);
	klass.prototype = properties;
	klass.constructor = Class;
	return klass;
};
var $extend = function(){
	var args = arguments;
	if (!args[1]) args = [this, args[0]];
	for (var property in args[1]) args[0][property] = args[1][property];
	return args[0];
};
Function.prototype.bind = function(bind, args){
	return this.create({'bind': bind, 'arguments': args});
}
Function.prototype.create = function(options){
	var fn = this;
	options = $.extend({
		'bind': fn,
		'event': false,
		'arguments': null,
		'delay': false,
		'periodical': false,
		'attempt': false
	}, options);
	if ($defined(options.arguments) && $type(options.arguments) != 'array') options.arguments = [options.arguments];
	return function(event){
		var args;
		if (options.event){
			event = event || window.event;
			args = [(options.event === true) ? event : new options.event(event)];
			if (options.arguments) $.extend(args, options.arguments);
		}
		else args = options.arguments || arguments;
		var returns = function(){
			return fn.apply($choose(options.bind, fn), args);
		};
		if (options.delay) return setTimeout(returns, options.delay);
		if (options.periodical) return setInterval(returns, options.periodical);
		if (options.attempt) try {return returns();} catch(err){return false;};
		return returns();
	};
}

/*---------------------------------------------------------------------------- 
			[END] - Taken from Mootools 1.11
---------------------------------------------------------------------------- */


/*---------------------------------------------------------------------------- 
			[START] - Additional basic utility methods
---------------------------------------------------------------------------- */
/*
FUNCTION: (String) getClassSuffix
--------------------------------------
Returns the end of a class name of a given element and class name prefix.

PARAMETERS:
=============
	el (Element, jQuery wrapper): The element tag to look at.
	prefix (String): The beginning of the class whose suffix we are interested in.
	
USAGE:
=======
<textarea class="limival255">text goes here</textarea>
var maxchars = getClassSuffix($('textarea').get(0), 'limitval');
*/
function getClassSuffix(el, prefix){
	el = ($type(el) == 'object') ? ($type(el.get(0)) == 'element') ? el.get(0) : el : el;
	var classes = el.className.split(" ");
	var suffix = ""; 
	
	for (var i=0, klass; klass = classes[i]; i++) {
	
		if (klass.indexOf(prefix) == 0) {
			try {
				suffix = klass.slice(prefix.length);
				break;
			} catch (e) { }
		}
	}
	return suffix;
}

/*
FUNCTION: (String) trimMore
--------------------------------
Removes beginning and ending whitespace as well as any "&nbsp;".  
JQuery .trim() does not strip &nbsp;, but Sharepoint seems to add &nbsp; when a field is empty.

PARAMETERS:
============
	str (String) - The string to trim.
*/
function trimMore(str){
	return (str || "").replace(/[^a-zA-Z0-9]/g,"");
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");	
}

function ISODateString(d){
  function pad(n){return n<10 ? '0'+n : n}
  return d.getUTCFullYear()+'-'
      + pad(d.getUTCMonth()+1)+'-'
      + pad(d.getUTCDate())+'T'
      + pad(d.getUTCHours())+':'
      + pad(d.getUTCMinutes())+':'
      + pad(d.getUTCSeconds())+'Z'
}

function htmlEscape(commentsContent) {      
return String(commentsContent)
.replace(/&/g, '&amp;')             
.replace(/"/g, 'quot;')             
.replace(/'/g, '&#39;');               
/*.replace(/</g, '&lt;')             
.replace(/>/g, '&gt;');*/
} 

/*
* Special event for image load events
* Needed because some browsers does not trigger the event on cached images.

* MIT License
* Paul Irish | @paul_irish | www.paulirish.com
* Andree Hansson | @peolanha | www.andreehansson.se
* 2010.
*
* Usage:
* $(images).bind('load', function (e) {
* // Do stuff on load
* });
*
* Note that you can bind the 'error' event on data uri images, this will trigger when
* data uri images isn't supported.
*
* Tested in:
* FF 3+
* IE 6-8
* Chromium 5-6
* Opera 9-10
*/
(function ($) {
	$.event.special.load = {
		add: function (hollaback) {
			if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
				// Image is already complete, fire the hollaback (fixes browser issues were cached
				// images isn't triggering the load event)
				if ( this.complete || this.readyState === 4 ) {
					hollaback.handler.apply(this);
				}
				
				// Check if data URI images is supported, fire 'error' event if not
				else if ( this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0 ) {
					$(this).trigger('error');
				}
				
				else {
					$(this).bind('load', hollaback.handler);
				}
			}
		}
	};
}(jQuery));
/*---------------------------------------------------------------------------- 
			[END] - Additional basic utility methods
---------------------------------------------------------------------------- */


/*---------------------------------------------------------------------------- 
			[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
---------------------------------------------------------------------------- */


/* allow window to behave like an extendable object */
$.extend(window,{});

/* detect browser */
if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
else window.ie = false;

/* fix ie6 image caching bug */
if (window.ie6)  document.execCommand("BackgroundImageCache", false, true);


/* The VPN adds extra HTML docs, so we always need to filter for the correct one. */
var thisHtml = $('#ctl00_Html1');

/* use JS class to display or hide elements using CSS when javascript is loaded. */
$(thisHtml).addClass('JS');


/*---------------------------------------------------------------------------- 
			[START] - ford refresh
---------------------------------------------------------------------------- */

/*
FUNCTION: (void) addSearchWrapper
---------------------------------
Sets the dynamic search form in header.
*/
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" class="buttonPrimary"/>');	
		
		//interpret Enter key to initiate search
		$('#fedsearch_k').keypress(function(e){ if (e.which == 13) { fedsearch(true); } });
	
	    $('#extSearch_wrapper').hide();	
	 	$('#search_wrapper').show();
	} else {
		$('#google_search').hide();
		$('#extSearch_wrapper').show();

	}
	fedsearch(true);
}




/*
FUNCTION: (void) fedsearch
---------------------------------
Sets the fedsearch action based on the type of search.
*/
function fedsearch(suppressErrors){
	//var userName = $('#user_li div[id$="_Menu_t"] a[id$="_Menu"] span').text();
	var welcomeHTML = $('#navglobal_primary').html();
	
	switch ($('#fedsearch_s').val()){
		case 'All Sites': 
		     if(welcomeHTML.indexOf('text="My Links"') > -1)
		     {	     
	  		  	$('#fedsearch').get(0).action = "https://search.sp.ford.com/Pages/Results.aspx"; 		     
		     }
		     else
		     {
		     	$('#fedsearch').get(0).action = "/Search/Results.aspx"; 		     		     
		     }

			break;
		case 'This Site': 
	       	 $('#fedsearch').get(0).action = "/Search/Results.aspx"; 
			 //*$('#fedsearch_s').val('All Sites');
			 break;
		case 'People': 
   			 $('#fedsearch').get(0).action = "https://search.sp.ford.com/Pages/peopleresults.aspx"; 
      		 break;
	}
	if (!suppressErrors && trimMore($('#fedsearch_k').val()).length == 0) {
		alert('Please enter one or more search words.');
		return false;
	}
	return true;
}


/*
FUNCTION: (String (url)) vpnUrl
------------------------------------
Augments the passed URL to allow it to work in the VPN.
*/
function vpnUrl(filePath, fileName){
	var sampleUrlArr = $('head link').get(0).href.split(',');
	var len = sampleUrlArr.length;
	if (len < 2) return filePath + fileName;
	for (var i=0; i<len; i++){
		if (/^DanaInfo=/.test(sampleUrlArr[i])) {
			return filePath + ',' + sampleUrlArr[i] + '+' + fileName;
		}
	}
	return filePath + fileName;
}


/*
FUNCTION (void) soapCall
----------------------------
Calls the User Profile Service and extracts values to place on the page.
Last Updated: 2008-11-13 sshepar3 - creation.

INPUTS:
===============
	fieldTitles (Array[String]): The titles of the fields to be updated.  
		Normally we'd use ID, but this is sharepoint...
	propertyNames (Array[String]): The name of the properties from the XML Response 
		to look for the values in. 
*/
function soapCall(fieldTitles, propertyNames, callback){
	return $.ajax({
		type: "POST", 
		url: vpnUrl("/_vti_bin/", "userprofileservice.asmx"),
		data: '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GetUserProfileByName xmlns="http://microsoft.com/webservices/SharePointPortalServer/UserProfileService"><AccountName></AccountName></GetUserProfileByName></soap:Body></soap:Envelope>',
		contentType: "text/xml; charset=utf-8",
		dataType: "xml", 
		cache: false,
		success: function(xml){ 
			try {
				var propertyNodes = $("PropertyData", xml);
				if (!propertyNodes || propertyNodes.length == 0) return;
				
				for (var i=0, field; field = fieldTitles[i];i++){
					field = $('input[title*="'+field+'"]');
					/* skip this field if it does not exist or it already has a value */
					if (!field || field.length == 0 || field.val().length>0) continue;
					
					/* Iterate each PropertyData node for the Name of the property we want.
					Once found, the value of the property is in /Values/ValueData/Value */
					for (var j=0, property;property=propertyNodes[j];j++){
						if ($('Name', property).text() == propertyNames[i]) {
							field.val($('Values>ValueData>Value', property).text());
						}
					}
				}
				
				/* run callback */
				if (callback) callback(xml);
			} catch (e) {  }
		}
	});
}


/*
CLASS NAME: CharacterCounter
----------------------------------------------------------------------
Finds character counter components in the HTML and initializes them.  For text fields, use the maxlength attribute.  
For textarea fields, use a class name like limitis255, where "limitis" is the class name prefix and the number is the max length.

USAGE:
============
<script>
$(function({
	var charlimitEls = $('.charlimit');
	var charlimitReadouts = $('.charlimit_readout');
	charlimitEls.each(function(i, charEl){
		try {
			new CharacterCounter(charEl, charlimitReadouts[i]);
		} catch (e) {}
	});
});
</script>

<label for="charlimit_demo">Character Limit Demo (text):</label>
<input type="text" id="charlimit_demo" class="charlimit" maxlength="50" />
<div class="charlimit_readout">max: 50 char | 50 char remain</div>

<!-- or -->

<label for="charlimit_demo2">Character Limit Demo (textarea):</label>
<textarea id="charlimit_demo2" class="charlimit limitis255" />
<div class="charlimit_readout">max: 255 char | 255 char remain</div>

*/
var CharacterCounter = new Class({
	
	note_class: 'ms-formdescription',
	limit_class_prefix: 'limitis',
	
	initialize: function(field, readoutEl, maxlength, activeLimit){
		field = $(field);
		if (field.length == 0) return;
		
		if (maxlength) this.maxlength = maxlength;
		else {
			if (field.attr('maxlength')) this.maxlength = field.attr('maxlength');
			else this.maxlength = getClassSuffix(field, this.limit_class_prefix);
			if (!this.maxlength) return;
		}
		
		this.field = field;
		this.readoutEl = this.createReadout(readoutEl);
		this.activeLimit = activeLimit;
		this.updateReadout();
		this.events();
		return this;
	},
	
	createReadout: function(readoutEl){
		if (!readoutEl || readoutEl.length == 0){
			var readoutEl = document.createElement('p');
			readoutEl.className = this.note_class;
			$(this.field.parent()).append(readoutEl);
		}
		return $(readoutEl);
	},
		
	updateReadout: function(){
		var currentLength = this.field.val().length;
		var remaining = this.maxlength-currentLength;
		if (this.activeLimit && remaining < 0) {
			this.field.val(this.field.val().substring(0,this.maxlength ));
			currentLength = this.maxlength ;
			remaining = 0;
		}

//		this.readoutEl.html('(max: ' + this.maxlength + ' char | ' + remaining + ' char remaining)');

/* Mahanth start */				
		var mxlength = this.maxlength + "";
		var remain   = remaining + "";

		if(mxlength.length == 4)
		{
			mxlength = mxlength.substring(0,1) + "," + mxlength.substring(1);
		}
		
		if(remain.length == 4)
		{
			remain = remain.substring(0,1) + "," + remain.substring(1);
		}
		this.readoutEl.html('(max: ' + mxlength + ' char | ' + remain + ' char remaining)');
/* Mahanth  end */		

		if (remaining < 0) this.readoutEl.addClass('error');
		else this.readoutEl.removeClass('error');
	},
	
	events: function(){
		/* keydown might be too agressive 
		this.field.keydown(function(){ this.updateReadout() }.bind(this) );*/
		this.field.keyup(function(){ this.updateReadout() }.bind(this) );
	}
	
});


/*
CLASS NAME: navMain
----------------------------------------------------------------------
The behavior logic for the primary navigation menus.

USAGE:
============
<script>
$(document).ready(function(){
	$(window).load(function () {		
		$('.nav_primary').navMenu();
	});
});
</script>

<ul class="nav_primary">
	<li id="tab_01" class="menu fbaHide"> <a href="/Tools">Tools</a>
		<ul class="subnav">
			<li><a href="/Tools/JobTools">Job-Related Tools</a></li>							
			<li><a href="/Tools/learning">Learning &amp; Development</a></li>
			<li><a href="/Tools/forms">Frequently Used Forms</a></li>														
			<li><a href="http://www.digitalworker.ford.com" target="_blank">Digital Worker</a></li>	
			<li><a href="https://comm.sp.ford.com/sites/digitalworker/Pages/HomeiWork.aspx" target="_blank">How iWork</a></li>						
			<li><a href="/Tools/EventsCalendar">Events Calendar</a></li>
			<li><a href="http://www.ideaplace.ford.com">Submit an Innovative Idea</a></li>							
		</ul>
	</li>	
	<li id="tab_02" class="menu fbaHide"> <a href="/resourcecenter">Resources &amp; Organizations</a>
		<ul class="subnav">
			<li><a href="/resourcecenter/GeneralResources">General Resources</a></li>
			<li><a href="/resourcecenter/human">Human Resources</a></li>
			<li><a href="/resourcecenter/policies">Policies &amp; Legal</a></li>
			<li><a href="/resourcecenter/safety">Safety &amp; Security</a></li>
			<li><a href="/resourcecenter/empresource">Employee Resource Groups</a></li>							
			<li><a href="/resourcecenter/countries">Countries &amp; Organizations</a></li>	
			<li><a href="/B2B/Pages/RetireeLandingPage.aspx">U.S. Retirees</a></li>							
			<li><a target="_blank" href="http://www.itcn.ford.com">IT Portal</a></li>
			<li><a href="https://www.ga.ford.com/main/index.html" target="_blank">Government Affairs</a></li>								
		</ul>
	</li>
</ul>
*/
$.widget("ui.navMenu", {
	options: {
	},
	
	_create: function() {
		var this_ = this;
		
		this.element.addClass('JS');

		this.element.find('li').hover(function(){
			$(this).addClass("open");
			$('ul:first',this).css('visibility', 'visible');
		}, function(){
			$(this).removeClass("open");
			$('ul:first',this).css('visibility', 'hidden');
		}); 
	},
	
	destroy: function() {
		$.Widget.prototype.destroy.apply(this, arguments); // default destroy
	}
});


/*
CLASS NAME: carousel
----------------------------------------------------------------------
The behavior logic for the carousel slideshow.

USAGE:
============
<script>
$(document).ready(function(){
	$(window).load(function () {		
		if($('#carousel').length > 0) {
			$('#carousel').carousel();
		}
	});
});
</script>
*/
$.widget("ui.carousel", {
	// default options
	options: {
		startSlideIndex: 0
	},
	
	// creation code for mywidget
	// can use this.options
	// and this.element
	_create: function() {
		var this_ = this;
		
		this.element.addClass('JS');

        this.slides = this.element.find('.carouselBody');
        this.previousLink = this.element.find('.carouselPrevNext .carouselPrev');
        this.nextLink = this.element.find('.carouselPrevNext .carouselNext');
        this.shortcutContainer = this.element.find('.carouselDirectLinks');
        this.shortcutContainerList = this.element.find('.carouselDirectLinks ul');
		
		this.index = this.options.startSlideIndex;
		this.length = this.slides.length;


        //Hide all slides that don't have the current index
        this.slides.each(function(index, slide) {
            if (index != this_.index) {
                $(slide).hide();
            } else {
				$(slide).show();
			}
        });

        //Make shortcut links
        for(var i = 1; i <= this.length; i++) {
        	var slideNumber = (i < 10) ? '0' + i : i;
        	$(this.shortcutContainerList).append('<li><span><a class="carouselShortcut" href="#slide_'+ slideNumber +'" id="Link_'+ slideNumber +'">Link_'+ slideNumber +'</a></span></li>'); 
        }
		this.shortcutLinks = this.element.find('.carouselShortcut');
       
        
        //Calculate the width of the 
        //Add the click event to each shortcut link
        //If we aren't always showing the shortcut links, hide all shortcut links that don't have the current index
        //Otherwise make the shortcut link that has the current index the 'active' link
		var shortcutContainerListWidth = 0;
        this.shortcutLinks.each(function(index, linkElement) {
         	var listItemElement = $(linkElement).closest('li');
         	var marginLeft = $(listItemElement).css('margin-left').replace('px', '');
        	var marginRight = $(listItemElement).css('margin-right').replace('px', '');
        	var width = $(listItemElement).css('width').replace('px', '');
        	shortcutContainerListWidth += parseInt(width) + parseInt(marginLeft) + parseInt(marginRight); 
			
			$(linkElement).bind('click', function(event) {
				event.preventDefault();
				this_.clickTo(index);
			});
			linkElement.href = 'javascript:;';

            if (index == this_.index) {
                $(linkElement).addClass('active');
            }
        });
		$(this.shortcutContainerList).css('width', shortcutContainerListWidth + 'px');
		
        //Add the click event to the next / previous links
        $(this.previousLink).bind('click', function(event) {
				event.preventDefault();
				this_.previous();
		});
		this.previousLink.href = 'javascript:;';
		
        $(this.nextLink).bind('click', function(event) {
				event.preventDefault();
				this_.next();
		});
		this.nextLink.href = 'javascript:;';
	},
	
    next: function() {
        var index = (this.index < this.length - 1) ? this.index + 1 : 0;

        this.slideTo(index);
    },

    previous: function() {
        var index = (this.index > 0) ? this.index - 1 : this.length - 1;

        this.slideTo(index);
    },

    clickTo: function(index) {

        this.slideTo(index);
    },

    slideTo: function(index) {
        var oldIndex = this.index;
        this.index = index;

        if (this.index != oldIndex) {

            //Start the animation
			//Hide the previous slide and show the current slide
			$(this.slides[oldIndex]).hide();
			$(this.slides[this.index]).show();

            //Update which link is now active
            $(this.shortcutLinks[oldIndex]).removeClass('active');
            $(this.shortcutLinks[this.index]).addClass('active');
        }
    },
	
	destroy: function() {
		$.Widget.prototype.destroy.apply(this, arguments); // default destroy
		// now do other stuff particular to this widget
	}
});


/* FUNCTION: (String) getQueryStringVariable
----------------------------------------------------
Gets the value of the requested query string variable

PARAMETERS
=============
queryStringVariable(String): The string name of the variable to look for.
*/
function getQueryStringVariable(queryStringVariable) {
	var query = decodeURIComponent(window.location.search.substring(1));
	var queryStrings = query.split("&");

	var queryString = $.grep(queryStrings, function(element, index) {
		return element.indexOf(queryStringVariable+'=') != -1;
	});
	
	if(queryString != '') {
		var pair = String(queryString[0]).split("=");
		return pair[1];
	} else {
		return '';
	}
}

/*
FUNCTION (void) moveContents()
---------------------------------------
Moves contents of sourceElement in the context of rootElement to destinationElement.
*/
function moveFormContents(sourceElement, destinationElement, rootElement, toTopOrBottom){
	if (rootElement == null) rootElement = document;
	var sourceContent = $(sourceElement, rootElement).find('td');
	if (sourceContent.length > 1){
//		sourceContent = sourceContent.eq(1).children();
//		sourceContent = sourceContent.get(1).childNodes;
		sourceContent = sourceContent.eq(1).contents();
	} else {
		sourceContent = $(sourceElement);
	}
	
	$('script', sourceContent).remove();
	
	if(toTopOrBottom == null || toTopOrBottom == 'bottom') {
		$(destinationElement).append(sourceContent);
	} else {
		$(destinationElement).prepend(sourceContent);
	}
	
	return sourceContent;
}

function updateLabelForAttribute(formField, label) {
	if(formField && label) {
		label.attr('for', formField.attr('id'));
	}
}

function displayFormErrors() {
	/* move errors */
	var errorsContainer = $('.validationErrors');
	$('.ms-formvalidation').each(function(index, errorElement){
		if (errorElement.innerHTML.length > 5) {
			var listItemElement = document.createElement('li'); 
			var fieldName = $(errorElement).parent().attr('id').replace('_', ' ');
			$(errorElement).prepend(fieldName + ': ');
			$(errorElement).appendTo(listItemElement);
			$(listItemElement).appendTo($('ul', errorsContainer).get(0));
		}		
	});
	if ($('li', errorsContainer).length > 0) {
		errorsContainer.show();
	}
}

/*
FUNCTION: (Object) fileNameParser
-------------------------------------
extracts name, prefix, suffix and path from a file.
*/
function fileNameParser(src){
	var file = {};
	var fileParts = src.split('.');
	file.name = fileParts[fileParts.length-2]+'.'+fileParts[fileParts.length-1];
	file.suffix = fileParts[fileParts.length];
	file.basename = fileParts[fileParts.length-2];
	file.extension = fileParts[fileParts.length-1];
	return file;
}


/*---------------------------------------------------------------------------- 
			[START] - Text Pager
---------------------------------------------------------------------------- */

/* 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+$/,''); }

/*---------------------------------------------------------------------------- 
			[END] - ford refresh
---------------------------------------------------------------------------- */


