/**
 * Shorthand for document.getElementById
 */
function $(elem) { return document.getElementById(elem); }

/**
 * This function creates a loading queue for the page and adds events to it. 
 * Using this function is a good idea when you need to load a lot of different
 * things along side the page.
 */
function addLoadEvent(func) {
	var oldonload = window.onload;

	if (typeof window.onload != 'function')
		window.onload = func;
	else
		window.onload = function() {
			oldonload();
			func();
		}
}

/**
 * Open links in new windows using XHTML standards compliant markup.
 */
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
			anchor.getAttribute("rel") == "external")
		anchor.target = "_blank";
	}
}

/**
 * Checks the value of a cookie
 */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/**
 * Adds text to a text box until it is clicked.
 */
function addPreClickText(box, text) {
	var thebox = $(box);
	
	thebox.value = text;
	thebox.defaultValue = text;
	
	thebox.onfocus = function() {
		if (this.value == this.defaultValue)
			this.value = '';
	}
	
	thebox.onblur = function() {
		if (this.value == '' || this.value == this.defaultValue )
			this.value = this.defaultValue;
	}
}

function dateConfirm() {
	var failed = false;

	// Prompt for value and set the docsdate to that value
	n = $('docsdate').value = 
		prompt("PLEASE ENTER SHIPMENT DELIVERY DATE: (mm/dd/yyyy +/- 30 days)\n" + 
				"(Images are available for online viewing 365 days after the date of delivery)\n");

	// Check for basic date format (m/d/yyyy or mm/dd/yyyy)
	if (/^[0-1]?[0-9]\/[0-3]?[0-9]\/[0-9]{4}$/.test(n)) {
		var adate = n.split('/');
		
		// Is the month in a valid range?
		if (adate[0] < 1 || adate[0] > 12)
			var failed = true;
		
		// Is the date roughly valid?
		if (adate[1] < 1 || adate[1] > 31)
			var failed = true;
	} else
		var failed = true;
	
	// Alert the user if the validation failed.
	if (failed) {
		alert("Please enter a valid date using mm/dd/yyyy format.");
		return false;
	} else
		return true;
}

/**
 * Check if the user is logged in. 
 */
function getLoggedIn() {
	if (document.getElementById('loggedin')) return true
	else return false
}


/* This function is used by the Fuel Surcharge link in the Quick Tips sidebar */
function centerWin() {
	if (document.all) {
        var xMax = screen.width, yMax = screen.height; 
    }else{ 
        if (document.layers) {
            var xMax = window.outerWidth, yMax = window.outerHeight; 
        } else {
            var xMax = 640, yMax=480;
    	}
    }
    var xOffset = (xMax - 200)/2, yOffset = (yMax - 200)/2;
    window.open('/shipment_resources/fuel_popup.html','surcharge','width=390,height=50,titlebar=no,menubar=no,toolbar=no,screenX='+xOffset+',screenY='+yOffset+', top='+yOffset+',left='+xOffset+'');

	return false;
}


addLoadEvent(function() {
	// Load the zip code from a cookie if the right form field and cookie exist
	if (document.getElementById('zip_code') && readCookie('light').split('%2C')[2])
		document.getElementById('zip_code').value = readCookie('light').split('%2C')[2];

	// Load the link-fixer
	externalLinks();

	// Do what needs a doin' when the page loads. This varies if they are logged in
	// or not.
	if (getLoggedIn()) {
		// Note that we remove the + character from the string and replace it 
		// with a space. We could also proper-case it with CSS by appending 
		// .toLowerCase()
		if ($('marcom_name') && readCookie('marcom_name'))
			$('marcom_name').innerHTML = readCookie('marcom_name').replace(/\+/,' ');
		
		// Reads the cctphone cookie and sets the label correctly. Falls back to
		// a sane default.
		if ($('mt_cctphone') && readCookie('marcom_customercarephone')) {
			var phone = readCookie('marcom_customercarephone').match(/(\d{3})(\d{3})(\d*)/);
			$('mt_cctphone').innerHTML = phone ? phone[1]+'-'+phone[2]+'-'+phone[3] : '888-550-9800';
		}
		
		// Sets the CCT email link
		if ($('mt_email_link') && readCookie('marcom_customercareemail'))
			$('mt_email_link').href = readCookie('marcom_customercareemail') ? 'mailto:'+readCookie('marcom_customercareemail') : 'mailto:customersat@yrc.com';
	} else {
		// Make sure the litecolumn is never shorter than the bodycopy, normally
		// this is only ever run by IE.
		try {
			if ($('litecolumn')){
				if($('bodycopy').offsetHeight < $('litecolumn').offsetHeight) {
					if(!window.ActiveXObject||parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf('MSIE')+5))>6){
						$('bodycopy').style.height = $('litecolumn').offsetHeight+'px';	
					}else{
						// IE6
						$('bodywrap').style.height = $('litecolumn').offsetHeight+'px';	
						$('bodycopy').style.height = $('litecolumn').offsetHeight+'px';	
						$('homeWrap').style.height = $('litecolumn').offsetHeight+'px';	
						
					}
				}else{ 
					if(!window.ActiveXObject){
						$('litecolumn').style.height = $('bodycopy').offsetHeight-43+'px';
					}else if(parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf('MSIE')+5))>6){
						$('litecolumn').style.height = $('bodycopy').offsetHeight-41+'px';	
					}else{
						$('litecolumn').style.height = $('bodycopy').offsetHeight-32+'px';	
					}
				}
				//ie was not happy with out below
				$('ad1').style.margin = "0";
			}
		} catch (e) {}
		
		// Add text to the tracking fields
		addPreClickText('track_number','enter PRO#');
		addPreClickText('track_docs','enter PRO# for POD');
		addPreClickText('O_ZIP','origin zip');
		addPreClickText('D_ZIP','dest zip');
		addPreClickText('track_servicec','enter zip/postal code');
		
		// Attach the form validation routines to the tracking forms
		$('shippingdocs').onsubmit = dateConfirm;

		
		// Fix the enter key for IE so that it submits the form
		try {
			$('password').onkeyup = function(e) {
				if (!e) var e = window.event;			
				if (e.keyCode == 13) $('login').submit();
			};
		} catch (e) {}
	}
	
	// Remember my credentials code.
	//
	// Must check that the login form exists otherwise this throws errors. Added 
	// during CRC page changes (10/3/07 - MEC)
	if (document.cookie.length > 0 && !!($('login'))) {
		begin = document.cookie.indexOf("MR_PUBLIC_REMEMBERME=");
		if (begin != -1) {
			begin += 21;
			end = document.cookie.indexOf(";", begin);
			
			if (end == -1) end = document.cookie.length;
			user_id = unescape(document.cookie.substring(begin, end));
			
			if (user_id != "") {
				$('username').value = user_id; 
				$('password').value = 'REMEMBERME';
				$('REMEMBERME').checked = 'checked';
			}
		}
	}
});

sfHover = function() {
	if(document.getElementById("nav")){
		var sfEls = document.getElementById("nav").getElementsByTagName("li");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
				showHideForms('hidden');
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(/sfHover/gi, "");
				showHideForms('visible');
			}
			t=sfEls[i].getElementsByTagName("ul");
			if(t.length&&!sfEls[i].id){
				sfEls[i].className+=" submenu";
				t[0].style.marginTop = "-"+(sfEls[i].offsetHeight)+"px";	
			}
		}
	}
}

function showHideForms(type){
	// this hides select boxes (for now) in ie6 or earlier, since they interfere with the menus
	if(window.ActiveXObject&&parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf('MSIE')+5))<7){
		forms = document.getElementsByTagName("select");
		formsL = forms.length;
		for(x=0;x<formsL;x++){
			if(forms[x].id != "menuSearchSelect"){
				forms[x].style.visibility = type;
			}
		}
	}
}

function showHide(ele){
	$(ele).style.display=($(ele).style.display=="block")?"none":"block";
	if((ele=="myroadwayform")&&($(ele).style.display=="block")){
		$('username').focus();
	}
	return false;
}

function switchSearchMenu(){
	var searchMenu = document.getElementById("searchMenu");
	if(searchMenu.className.search(/sfclick/i)>=0){
		searchMenu.className=searchMenu.className.replace(/sfclick/gi, "");
	}else{
		searchMenu.className+=" sfclick";
	}
	return false;
}

addLoadEvent(sfHover);

// Pop-Up menu function
function MM_openBrWindow(u,n,f) { window.open(u,n,f); }

// YRC Search
function submitSend() {
	document.sendSearch.submit();
}
function submitSend2() {
        document.sendSearch2.submit();
}

function serviceDaySubmit(form){
	window.name="main";
	err = 0;
	pat = /\D/;
	orig = form['servicedays.inquiry.originzip'].value;
	dest = form['servicedays.inquiry.destinationzip'].value;
	if(!orig) err++
	if(orig.length<5) err++
	if(orig=="origin zip") err++;
	if(!dest) err++
	if(dest.length<5) err++
	if(dest=="dest zip") err++;
	
	if(pat.test(orig)){form['servicedays.inquiry.origincountry'].value="CAN";}else{form['servicedays.inquiry.origincountry'].value="USA";}
	if(pat.test(dest)){form['servicedays.inquiry.destinationcountry'].value="CAN";}else{form['servicedays.inquiry.destinationcountry'].value="USA";}
	
	if(err){
		alert("There is a problem with the data that you have entered:\nOrigin Postal Code: "+orig+"\nDestination Postal Code: "+dest);
		return false;
	}else{
		return true;
	}
}

function make2dig(s){
 s=s.toString();
 if(s.length==1){
  s="0"+s;
 }
 return s;
}

function datePrompt(url){
	if (document.all) {
		var xMax = screen.width, yMax = screen.height;
	}else{
		if (document.layers) {
			var xMax = window.outerWidth, yMax = window.outerHeight;
		} else {
			var xMax = 640, yMax=480;
		}
	}
	var xOffset = (xMax - 200)/2, yOffset = (yMax - 200)/2;
	window.open(url,'datePrompt','scrollbars,width=400,height=100,titlebar=no,menubar=no,toolbar=no,screenX='+xOffset+',screenY='+yOffset+', top='+yOffset+',left='+xOffset+'');
	return false;
}
 

