var maxNumServices = 5;
var maxNumCandidates = 3;
var changeZipCodeMsg = "Changing your zip code may result in companies that are a better match than those currently in your list and Final Candidates.";
var confirmChangeServicesMsg = "Changing your service selections may result in companies that are a better match than those currently in your list and Final Candidates.";
var confirmResetMsg = "This action will clear all service selections, and all companies in your list and Final Candidates.";
var zipCodeRequiredMsg = "Zip Code must be specified.";
var PortfolioImages = new Array();
var CurrImageIndex = 0;

function getSearchResults1()
{
	form = document.forms['contentForm'];
	if ( form.ZipCode.value != "" )
	{
		form.Action.value='getResults';
		form.submit();
	}
	else
		alert( 'Please enter your zip code.' );
	
}

function getSearchResultsCity()
{
	//alert('made it here');
	form = document.forms['activityTracker'];
	form2 = document.forms['contentForm'];
	//if ( form.ZipCode.value != "" )
	if (form2.selectCityZipCodes.selectedIndex != 0)
	{
		form2.ZipCode.value = form.ZipCode.value;
		form2.Action.value='getResults';
		form2.submit();
	}else{
		alert( 'Please choose a zip code from the selection box above.' );
	}
	
}

function quickSearch()
{
	var form = document.forms['quicksearch'];
	if ( form.quicksearchLocation.value != "" )
	{
//		document.location.href="CompanySelection.php?service=" + form.quicksearchService.value;
		form.submit();
	}
	else
		alert( 'Please enter your zip code.' );
}

function serviceSearch( ServiceID )
{
	var form = document.forms['activityTracker'];
	if ( form.ZipCode.value != "" )
		document.location.href="/CompanySelection.php?service=" + ServiceID;	
	else
		alert( 'Please enter your zip code.' );
}

function reset()
{
	if ( confirm( confirmResetMsg ) )
	{
		var form = document.forms['activityTracker'];
		form.action = '/index.php';
		form.Action.value = 'reset';
		form.submit();
	}
}

function checkout()
{
	var form = document.forms['activityTracker'];
	form.action = '/Checkout.php';
	form.Action.value = 'checkout';
	if ( form.numCandidates.value > 3 )
		alert("Only 3 Final Candidates may be submitted.");
	else if ( form.numCandidates.value == 0 )
		alert("At least one Final Candidate is required.");
	else if ( form.ZipCode.value == '' )
		alert("Zip Code is required");
	else
		document.location.href="Checkout.php";
//		form.submit();	
}

function submitAction( formName, action )
{
	var form = document.forms[formName];
	form.Action.value = action;
	form.submit();
}

function updateActivity( url, formName )
{
	var form = document.forms[formName];
	form.Action.value = 'ajaxUpdate';
	ajax.submitFormPost( url, formName );
}

function changeLocation( zipCode )
{
	var url = 'AjaxResults.php?key=changeLocation';
	var form = document.forms['activityTracker'];
	var contentForm = document.forms['contentForm'];
	var quickSearchForm = document.forms['quicksearch'];
		
	if ( pageID == 'Checkout' )
		return;

	var existingValue = form.ZipCode.value;
	if ( typeof contentForm != 'undefined' && contentForm != null && typeof contentForm.ZipCode != 'undefined' && contentForm.ZipCode != null && contentForm.ZipCode.value == '' )
		existingValue = '';
	else if ( typeof quickSearchForm != 'undefined' && quickSearchForm != null && typeof quickSearchForm.quicksearchLocation != 'undefined' && quickSearchForm.quicksearchLocation != null && quickSearchForm.quicksearchLocation.value == '' )
		existingValue = ''; 

	if ( zipCode == '' && pageID != 'Checkout' )
	{
		var zipVal = "";
		
		alert( zipCodeRequiredMsg );

		if ( typeof contentForm != 'undefined' && contentForm != null )
		{
			var zipCodeElm = form.ZipCode;
			if ( typeof zipCodeElm != 'undefined' && zipCodeElm != null )
			{
				if ( zipCodeElm.value != "" )
					zipVal = zipCodeElm.value;
			}
		}

		if ( typeof contentForm != 'undefined' && contentForm != null )
		{
			var zipCodeElm = contentForm.ZipCode;
			if ( typeof zipCodeElm != 'undefined' && zipCodeElm != null )
			{
				if ( zipVal == "" )
					zipVal = zipCodeElm.value;
			}
		}

		if ( typeof quickSearchForm != 'undefined' && quickSearchForm != null )
		{
			var zipCodeElm = quickSearchForm.quicksearchLocation;
			if ( typeof zipCodeElm != 'undefined' && zipCodeElm != null )
			{
				if ( zipVal == "" )
					zipVal = zipCodeElm.value;
			}
		}

		form.ZipCode.value = zipVal;

		if ( typeof contentForm != 'undefined' && contentForm != null )
		{
			var zipCodeElm = contentForm.ZipCode;
			if ( typeof zipCodeElm != 'undefined' && zipCodeElm != null )
				contentForm.ZipCode.value = zipVal;
		}
	
		if ( typeof quickSearchForm != 'undefined' && quickSearchForm != null )
		{
			var zipCodeElm = quickSearchForm.quicksearchLocation;
			if ( typeof zipCodeElm != 'undefined' && zipCodeElm != null )
				quickSearchForm.quicksearchLocation.value = zipVal;
		}

		return;
	}
		
	form.zipCode.value = zipCode;
	ajax.submitFormPost( url, form.id );

	if ( typeof contentForm != 'undefined' && contentForm != null )
	{
		var zipCodeElm = contentForm.ZipCode;
		if ( typeof zipCodeElm != 'undefined' && zipCodeElm != null )
			zipCodeElm.value = zipCode;
	}

	if ( typeof quickSearchForm != 'undefined' && quickSearchForm != null )
	{
		var zipCodeElm = quickSearchForm.quicksearchLocation;
		if ( typeof zipCodeElm != 'undefined' && zipCodeElm != null )
			zipCodeElm.value = zipCode;
	}
	
	if ( ( numWishlist > 0 || numCandidates > 0 ) && pageID != 'Checkout' && existingValue != ''  )
		alert( changeZipCodeMsg );
	
	if ( pageID == 'CompanySelection' )
		document.location.href = pageID + ".php";
}

function toggleServicesString(checkbox){
	if ( checkbox.checked )
		checkbox.checked = false;
	else
		checkbox.checked = true;
	toggleServices( checkbox );
	
}

function toggleServices( checkbox )
{
	//alert('made to toggleServices.');
	if ( checkbox.checked )
		addToServices( checkbox.value );
	else
		deleteFromServices( checkbox.value );
}

function addToServices( serviceID )
{
	//alert('made it to addToServices');
	if ( numServices < maxNumServices && ( ( numCandidates == 0 && numWishlist == 0 ) || confirm( confirmChangeServicesMsg ) ) )	
	{
		//alert('Inside if');
		var url = 'AjaxResults.php?key=addToServices';
		var form = document.forms['activityTracker'];
		form.toggleServiceID.value = serviceID;
		ajax.submitFormPost( url, form.id );
			
		var contentForm = document.forms['contentForm'];
		if ( typeof contentForm != 'undefined' && contentForm != null )
		{
			var checkboxElm = document.getElementById( 'cfsv' + serviceID );
			if ( typeof checkboxElm != 'undefined' && checkboxElm != null )
				checkboxElm.checked = true;
		}
		numServices++;
		if ( numServices == 0 && pageID != 'index' ){
			document.location.href = "/index.php";
		}else if (pageID == 'CompanySelection2'){
			//do nothing
		}else {( pageID != 'index' )
			//document.location.href = pageID + ".php";
                        //do nothing
		}
	}
	else
	{
		if ( numServices >= maxNumServices )
			alert( "Only " + maxNumServices + " services may be selected." ); 
		var contentForm = document.forms['contentForm'];
		if ( typeof contentForm != 'undefined' && contentForm != null )
		{
			var checkboxElm = document.getElementById( 'cfsv' + serviceID );
			if ( typeof checkboxElm != 'undefined' && checkboxElm != null )
				checkboxElm.checked = false;
		}
	}
}

function deleteFromServices( serviceID )
{
	if ( ( numCandidates == 0 && numWishlist == 0 ) || confirm( confirmChangeServicesMsg ) )
	{
		var url = 'AjaxResults.php?key=deleteFromServices';
		var form = document.forms['activityTracker'];
		form.toggleServiceID.value = serviceID;
		ajax.submitFormPost( url, form.id );

		var contentForm = document.forms['contentForm'];
		if ( typeof contentForm != 'undefined' && contentForm != null )
		{
			var checkboxElm = document.getElementById( 'cfsv' + serviceID );
			if ( typeof checkboxElm != 'undefined' && checkboxElm != null )
				checkboxElm.checked = false;
		}
		numServices--;
		if ( numServices == 0 && pageID != 'index' )
			document.location.href = "/index.php";
		else if ( pageID != 'index' && pageID == 'CompanySelection' )
			document.location.href = pageID + ".php";
	}
	else
	{
		var contentForm = document.forms['contentForm'];
		if ( typeof contentForm != 'undefined' && contentForm != null )
		{
			var checkboxElm = document.getElementById( 'cfsv' + serviceID );
			if ( typeof checkboxElm != 'undefined' && checkboxElm != null )
				checkboxElm.checked = true;
		}
		var activityForm = document.forms['activityTracker'];
		if ( typeof activityForm != 'undefined' && activityForm != null )
		{
			var checkboxElm = document.getElementById( 'atsv' + serviceID );
			if ( typeof checkboxElm != 'undefined' && checkboxElm != null )
				checkboxElm.checked = true;
		}
	}
}

function toggleWishlist( checkbox )
{
	if ( checkbox.checked )
		addToWishlist( checkbox.value );
	else
		deleteFromWishlist( checkbox.value );
}

function addToWishlist( companyID )
{
	var url = 'AjaxResults.php?key=addToWishlist';
	var form = document.forms['activityTracker'];
	form.companyID.value = companyID;
	ajax.submitFormPost( url, form.id );
	numWishlist++;
}

function deleteFromWishlist( companyID )
{
	var url = 'AjaxResults.php?key=deleteFromWishlist';
	var form = document.forms['activityTracker'];
	form.companyID.value = companyID;
	ajax.submitFormPost( url, form.id );

	var contentForm = document.forms['contentForm'];
	if ( typeof contentForm != 'undefined' && contentForm != null )
	{
		var checkboxArray = document.getElementsByName( 'WishlistCompany[]' );

		if ( typeof checkboxArray != 'undefined' && checkboxArray != null )
		{
			var checkboxElm = findCheckbox( checkboxArray, companyID );
			if ( typeof checkboxElm != 'undefined' && checkboxElm != null )
				checkboxElm.checked = false;
		}
	}
	numWishlist--;
}

function toggleFinalCandidates( checkbox )
{
	if ( checkbox.checked )
		addToFinalCandidates( checkbox.value );
	else
		deleteFromFinalCandidates( checkbox.value );
}

function addToFinalCandidates( companyID )
{
	if ( numCandidates < maxNumCandidates )
	{
		var url = 'AjaxResults.php?key=addToFinalCandidates';
		var form = document.forms['activityTracker'];
		form.companyID.value = companyID;
		ajax.submitFormPost( url, form.id );
	
		var contentForm = document.forms['contentForm'];
		if ( typeof contentForm != 'undefined' && contentForm != null )
		{
			var checkboxArray = document.getElementsByName( 'SelectedCompany[]' );
	
			if ( typeof checkboxArray != 'undefined' && checkboxArray != null )
			{
				var checkboxElm = findCheckbox( checkboxArray, companyID );
				if ( typeof checkboxElm != 'undefined' && checkboxElm != null )
					checkboxElm.checked = true;
			}
		}
		numCandidates++;
	}
	else
	{
		alert( "Only " + maxNumCandidates + " candidates may be selected." );
		var contentForm = document.forms['contentForm'];
		if ( typeof contentForm != 'undefined' && contentForm != null )
		{
			var checkboxArray = document.getElementsByName( 'SelectedCompany[]' );
	
			if ( typeof checkboxArray != 'undefined' && checkboxArray != null )
			{
				var checkboxElm = findCheckbox( checkboxArray, companyID );
				if ( typeof checkboxElm != 'undefined' && checkboxElm != null )
					checkboxElm.checked = false;
			}
		}
	}
}

function deleteFromFinalCandidates( companyID )
{
	var url = 'AjaxResults.php?key=deleteFromFinalCandidates';
	var form = document.forms['activityTracker'];

	form.companyID.value = companyID;
	ajax.submitFormPost( url, form.id );

	var contentForm = document.forms['contentForm'];
	if ( typeof contentForm != 'undefined' && contentForm != null )
	{
		var checkboxArray = document.getElementsByName( 'SelectedCompany[]' );

		if ( typeof checkboxArray != 'undefined' && checkboxArray != null )
		{
			var checkboxElm = findCheckbox( checkboxArray, companyID );
			if ( typeof checkboxElm != 'undefined' && checkboxElm != null )
				checkboxElm.checked = false;
		}
	}
	numCandidates--;
}

function addToImages( imageXref )
{
	var url = 'AjaxResults.php?key=addToImages';
	var form = document.forms['activityTracker'];
	form.imageXref.value = imageXref;
	ajax.submitFormPost( url, form.id );
	numImages++;
	if ( showImageAlert )
	{
		alert( 'This image will remain in your Activity Tracker until you close your browser.  To make this image available for future sessions, please sign in.' );
		showImageAlert = false;
	}
}

function deleteFromImages( imageXref )
{
	var url = 'AjaxResults.php?key=deleteFromImages';
	var form = document.forms['activityTracker'];
	form.imageXref.value = imageXref;
	ajax.submitFormPost( url, form.id );

	numImages--;
}

function saveSettings()
{
	ajax.calloutReplace( 'AjaxResults.php?key=saveAllSettings', document.getElementById('SaveAndUpdateMessage'), document.getElementById('SaveAndUpdateMessage'), 0, 0 );
}

function findCheckbox( checkboxArray, value )
{
	for ( i = 0; i < checkboxArray.length; i++ )
	{
		if ( checkboxArray[i].value == value )
			return checkboxArray[i];
	}
	
	return null;	// nothing matched.	
}

function PortfolioImage( companyID, imageID, imageIndex ) 
{
	this.getCompanyID = function() { return companyID; }
	this.getImageID = function() { return imageID; }
	this.getImageIndex = function() { return imageIndex; }

	return this;
}

function getPortfolioImage( companyID, imageID, imageIndex, directory )
{
	var galleryDiv = document.getElementById( 'GalleryDiv' );
	galleryDiv.scrollLeft = (81 * imageIndex) - 81;
	var imageNameDiv = document.getElementById( 'ImageNameDiv' );
	var img = document.getElementById( 'PortfolioImage' );
	img.src=directory + companyID + '-' + imageID + '.jpg';
	imageNameDiv.innerHTML=companyID + '-' + imageID;
	ajax.calloutReplace( 'AjaxResults.php?key=getImageInfo&companyid=' + companyID + '&imageID=' + imageID, document.getElementById('ImageInfoDiv'), document.getElementById('ImageInfoDiv'), 0, 0 );
	ajax.calloutReplace( 'AjaxResults.php?key=getImageXref&companyid=' + companyID + '&imageID=' + imageID, document.getElementById('SaveImageDiv'), document.getElementById('SaveImageDiv'), 0, 0 );
	ajax.calloutRestore('ProfileDiv', 'ImageDiv');
	CurrImageIndex = imageIndex - 1;
	setPortfolioNavArrows();
}

function setGalleryThumbnailPosition()
{
	var galleryDiv = document.getElementById( 'GalleryDiv' );
	galleryDiv.scrollLeft = (81 * (CurrImageIndex+1) ) - 81;
}

function setPortfolioNavArrows()
{
	// Now define the current image index, and set visibility on the nav arrows.
	var navLeftDiv = document.getElementById( 'navArrowLeft' );
	var navRightDiv = document.getElementById( 'navArrowRight' );
	var navLeftDivGray = document.getElementById( 'navArrowLeftGray' );
	var navRightDivGray = document.getElementById( 'navArrowRightGray' );

	if ( CurrImageIndex == 0 || PortfolioImages.length == 1 )
	{
		navLeftDiv.style.display = "none";
		navLeftDivGray.style.display = "";
	}
	else
	{
		navLeftDiv.style.display = "";
		navLeftDivGray.style.display = "none";
	}
			
	if ( CurrImageIndex == ( PortfolioImages.length - 1 ) || PortfolioImages.length == 1 )
	{
		navRightDiv.style.display = "none";
		navRightDivGray.style.display = "";
	}
	else
	{
		navRightDiv.style.display = "";
		navRightDivGray.style.display = "none";
	}
}

function getRatingInfo( hrefElmId, xOffset, yOffset )
{
	var hrefElm = document.getElementById( hrefElmId );
	var ratingInfoDiv = document.getElementById( 'RatingInfoDiv' );
	ajax.callout( 'AjaxResults.php?key=getRatingInfo', hrefElm, ratingInfoDiv, yOffset, xOffset );
}
function getDollarInfo( hrefElmId, xOffset, yOffset ){	var hrefElm = document.getElementById( hrefElmId );	var ratingInfoDiv = document.getElementById( 'DollarInfoDiv' );	ajax.callout( 'AjaxResults.php?key=getDollarInfo', hrefElm, ratingInfoDiv, yOffset, xOffset );}
function openPopup( sWhichOne, width, height )
{
	var width = width;
	var height = height;
	var topPosition = (screen.height - height)/2 - 20;
	var leftPosition = (screen.width - width)/2;
	var windowID = "infoWindow";
	var url = "";
	
	switch ( sWhichOne )
	{
		case "terms":
			url = "TermsAndConditions.php";
			break;
		case "privacy":
			url = "Privacy.php";
			break;
		case "referralFees":
			url = "referralFeesPrintable.php";
			break;
		case "privacyContractor":
			url = "privacyPolicy.html";
			break;
		case "trackerMerge":
			url = "TrackerMerge.php";
			break;
		default:
			url = sWhichOne;
			break;
	}

	window.infoWindow = window.open( url, windowID,'width=' + width + ',height=' + height + ',left=' + leftPosition + ',top=' + topPosition + ',scrollbars=yes,resizable=no,status=no,directories=no,toolbar=no,menubar=no',true);
	if (window.infoWindow != null)
	{	
		window.infoWindow.focus();
	}
	return;
}

function findFocusField( formName ) 
{
	var form = document.forms[formName];
	for (i = 0; i < form.length; i++) 
	{
		if ( (form.elements[i].type != "hidden") )
		{
			form.elements[i].focus();
			break;
		 }
	 }
}

function findFirstButton( formName ) 
{
	var form = document.forms[formName];
	for (i = 0; i < form.length; i++) 
	{
		if ( (form.elements[i].type == "button") )
		{
			return form.elements[i];
			break;
		 }
	 }
	 return null;
}

// Key handler function to make the form submit when the user presses "Return".
function setKeystrokeHandler()
{
	document.onkeypress = keyhandler;
}

function keyhandler(keystroke) {

    if ( document.all )
        keyCode = window.event.keyCode;
    else if (document.layers || document.getElementById)
        keyCode = keystroke.which;

    if (keyCode == 13)
	{	
		if ( ( button = findFirstButton( 'contentForm' ) ) != null )
			button.click();
		return false;
	}
}

function copyField( formName, srcField, destField )
{
	src = document.getElementById( srcField );
	dest = document.getElementById( destField );
	dest.value = src.value;
	findNextFocus( formName, destField );
}

function findNextFocus( formName, fieldName ) 
{
	var form = document.forms[formName];
	for (i = 0; i < form.length; i++) 
	{
		if ( (form.elements[i].id == fieldName) )
			break;
	 }
	for (i = i+1; i < form.length; i++) 
	{
		if ( (form.elements[i].type != "hidden") )
			break;
	 }
	form.elements[i].focus();

}

/*---------------------------------------
 Creates select list options from a 
 delimiter-separated string.
----------------------------------------*/
function createSelectListFromString( selectListElm, strValue, fieldDelimiter )
{
	var strArray = strValue.split( fieldDelimiter );
	if ( strArray.length > 0 )
	{
		for ( i = 0; i < strArray.length; i++ )
		{
			var strVal = strArray[i];
			var strText = strArray[i];
			addToSelectList( selectListElm, strVal, strText );
		}
	}
}
	
/*---------------------------------------
 Creates a delimiter-separated string 
 from select list options
----------------------------------------*/
function createStringFromSelectList( selectListElm, fieldDelimiter )
{
	var strValue = "";
	if ( selectListElm.options.length > 0 )
	{
		strValue = selectListElm.options[0].value;	
		for ( var i = 1; i < selectListElm.options.length; i++ )
			strValue += fieldDelimiter + selectListElm.options[i].value;
	}
	return strValue;
}

/*---------------------------------------
 Add an option to a select list
----------------------------------------*/
function addToSelectList( selectListElm, strValue, strText )
{
    var newOption = document.createElement('OPTION');
    newOption.text = strText;
    newOption.value = strValue;
  	try 
  	{
    	selectListElm.add(newOption, null); // non-IE
  	}
  	catch(ex) 
  	{
    	selectListElm.add(newOption); // IE only
  	}

	selectListElm.className = "";
	if ( selectListElm.length > selectListElm.size )
		selectListElm.size++;
}
	
/*---------------------------------------
 Remove selected options from a 
 select list
----------------------------------------*/
function deleteFromSelectList( selectListElm )
{
	for(var i = selectListElm.options.length-1; i>=0; i-- )
	{
		if(selectListElm.options[i].selected)
		{
			selectListElm.remove(i);
		}
	}
	
	if (selectListElm.length == 0)
		selectListElm.className = "empty";

	selectListElm.size = selectListElm.length >= 7 ? selectListElm.length : 7; 	
}

function checkMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}

function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

function updateCitySelectParams(){
	document.forms[0].quicksearchLocation.value=document.forms[0].selectOptionCity.options[document.forms[0].selectOptionCity.selectedIndex].value;	
	document.forms[0].citySelectText.value = document.forms[0].selectOptionCity.options[document.forms[0].selectOptionCity.selectedIndex].text;
}

function getContentServiceSelection(){
	var valid = "0123456789";
	var zip = document.forms['contentServiceSearch'].zip_code.value;
	if (zip.length!=5) {
		alert("Please enter your 5 digit zip code in the box labeled zip code.");
		return;
	}
	
	for (var i=0; i < zip.length; i++) {
		temp = "" + zip.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") {
			alert("Invalid characters in your zip code.  Please try again.");
			return;
		}
	}
	
	document.forms['contentServiceSearch'].submit();	
}function getContractorSearchTip(tipID){	//alert("buttlick");	cn = document.getElementById( "conttip" );	var strText = "";	switch (tipID){	case 1: 		strText = "Unique identification number representing a specific contractor.";		break;			case 2:		strText = "Click the image to visit a contractor's professional portfolio.";		break;			case 3:		strText = "Click to view contractor's price range for your selected service.";		break;			case 4:		strText = "Click to view contractor's average service rating.";		break;			case 5:		strText = "Click the Possible Candidates check box if you would like to mark a contractor for further consideration while browsing additional contractors.";		break;			case 6:		strText = "Click the Final Candidates check box if you would like this contractor to contact you regarding your project.";		break;			default:		strText = "<i>(Mouse over the text for a brief explanation)</i>";	}		cn.innerHTML = strText;}

function showHideByID(vid){	if (vid == 1){		x=document.getElementById("tooltiphelp1");		x.style.display = "";		y=document.getElementById("tooltiphelp2");		y.style.display = "";		z=document.getElementById("HelpLink");		z.innerHTML = "Hide";		z.href = "javascript:showHideByID(2);";		u=document.getElementById("conttip");		u.innerHTML = "<i>(Mouse over the text for a brief explanation)</i>";	}else{		x=document.getElementById("tooltiphelp1");		x.style.display = "none";		y=document.getElementById("tooltiphelp2");		y.style.display = "none";		z=document.getElementById("HelpLink");				z.innerHTML= "How to use this page";		z.href = "javascript:showHideByID(1);";		u=document.getElementById("conttip");		u.innerHTML = "<i>(Mouse over the text for a brief explanation)</i>";	}}
