// JavaScript for displaying pages Detailed Home Information *Maple Homes*
// updated July 28, 2005 - added height element to "divHouseImage", cleaned up v2.0 arvin
// updated March 2, 2006 - revised to suit New Neighborhood collection v3.0  arvin
// updated March 7, 2006 - fine-tuning functions loadCollection() v3.01  arvin
// updated March 9, 2006 - added more functions, rework of logic, cleaned up code v3.10 arvin
// updated March 10, 2006 - added function to calculate totals, display images v3.11 arvin
//=================================================================================

// Initialize variables
//========================
var arrQS = new Array(11);
var fn = "";
//========================

// MAIN FUNCTIONS
// loads the _floor plan_ page
function loadPlanDetail()
{   
    //alert("Performing loadPlanDetail()...")
	// retreives the query string (home detail)
	//getQueryString();	
	// evaluate whether the values contain empty values
	//evaluateQSValue( arrQS );
	// loads collection e.g. titles, links, images, house sizes
	loadCollection( arrQS );
	// calculate values for Total Living and Total Finished areas
	// does not interact with the array since it is now empty
	calculateTotal();
	// display images
	displayImages(arrQS[1][1]);
	// clear variables here
	fn="";
	hn=""
}

// HELPER FUNCTIONS
// retrieves the query string from the links in the _collection_ page
function getQueryString()
{
	// retrieve qs and save in the array
	var querystring = "";	

	if ( parent.location.search == "" )
	{
		querystring = location.search.substring( 1, location.search.length );	
	}
	else 
	{
		querystring = parent.location.search.substring( 1, parent.location.search.length ); 
	}
	// grabs the querystrings and puts them in an array (arrQS)
	var qryArr = querystring.split( '&' );
	for( var i=0;i<qryArr.length;i++ )
	    // split the label from the value
		arrQS[i] = qryArr[i].split('=');   
}

// helper function: takes params from the _collection_ page links via query strings.
function loadCollection( arrQS )
{
    //txtPath = "M_neighborhood_new.htm";
    
	// display links and labels on the page
	document.getElementById( 'lblColl' ).innerHTML          = makeLink( arrQS[0][1] );
	document.getElementById( 'lblHouseName' ).innerHTML     = evaluateHN2( arrQS[1][1] );	
	document.getElementById( 'lblMain' ).innerHTML          = arrQS[2][1];
	document.getElementById( 'lblUpper' ).innerHTML         = arrQS[3][1];
	document.getElementById( 'lblGarage' ).innerHTML        = arrQS[4][1];
	document.getElementById( 'lblCovEntry' ).innerHTML      = arrQS[5][1];
	document.getElementById( 'lblCovPatio' ).innerHTML      = arrQS[6][1]; 
	// the covered deck is optional thus placed into a separate function arrQS[7][1]
	document.getElementById( 'lblWidthFeet' ).innerHTML     = arrQS[8][1];
	document.getElementById( 'lblWidthInches' ).innerHTML   = arrQS[9][1];
	document.getElementById( 'lblDepthFeet' ).innerHTML     = arrQS[10][1];
	document.getElementById( 'lblDepthInches' ).innerHTML   = arrQS[11][1];
	
	// clear the array		
	arrQS = "";						
}

// display images and pdf link
// use the global var fn (folder name) and clear it after use
function displayImages(b)
{
	// display the house and plan images
	document.getElementById('houseImage').innerHTML = '<img src="'+fn+'/img' + b + '.jpg"><br /><br />';		
	document.getElementById('planImage').innerHTML = '<a href="'+fn+'/' + b + '.pdf"><img src="'+fn+'/fp' + b + '.jpg"></a>';		
	//alert (document.getElementById('planImage').innerHTML)
	// construct pdf link
	document.getElementById('pdfLink').innerHTML = '<a href="'+fn+'/' + b + '.pdf">.pdf</a>';
}

function evaluateQSValue( array )
{
    //alert("Calling evaluateQSValue()...")
    // evaluate if the value is empty (isNaN=not a number)
    for(var j=0;j<=10;j++)
    {
        if (isNaN( array[j][1] )||array[j][1]!="" )
        {
            continue
        }
        else
        {
            // when item isNaN, then change the value to "n/a"
            // for readability
            array[j][1] = "n/a"
        }
    }
    return array;
}

function evaluateHN2( hn )
{
	// if the house contains a number
	if ( (hn.lastIndexOf('2')) != -1 || (hn.lastIndexOf('1')) != -1 || hn.lastIndexOf('3') != -1 )
	{
		var str = changeToTitle2( hn );
		return str;
	}
	// if id does NOT contain a number
	// simply return the string
	else
	{
	    fn=hn;
	    return hn;
	}
}
// if it has a substring of 1, 2 or 3 then prepare it to form a title
function changeToTitle2( hn )				
{
    var str = hn;
	var index = "";
	var txt = "";
	var strTitle = "";

	if (str.lastIndexOf("1") != -1)
	{
		index = str.lastIndexOf("1")
	}
	else if (str.lastIndexOf("3") != -1)
	{
		index = str.lastIndexOf("3")
	}
	else if (str.lastIndexOf("2") != -1)
	{
		index = str.lastIndexOf("2")
	}
	else
	{
		index = str
		return index;
	}
	
	txt = str.substr(0,index)
	// assign string to global var fn
	fn = txt;
	strTitle = txt + ' ' + "#" + str.substr(index,(index-1));
	// return the 'fixed' string
	return strTitle;
}  
/* helper function: converts a house name to the folder name */
function changeToFolderName2( hn )	// if the name has a number e.g. "Willow2" it will be split to "willow_2"
{
	var str = hn;
	var index = "";
	var txt = "";
	
	// this is the index
	index = str.lastIndexOf( "2" );	    
	// return string less the last number
	txt = str.substr( 0, index );
	// this is currently set to change the case to lower...
	txt += txt.toLowerCase() + '_' + str.substr( index,(index-1) );
	return txt;
}  

// helper function: evaluates the house name to check if it has a numeral in the name
// req: y=house name
// req: n=left or right
function evaluateHN(y,n)
{
	// does house name have a number?
	if ( (y.lastIndexOf('2')) != -1 || (y.lastIndexOf('1')) != -1 || y.lastIndexOf('3') != -1 )
	{
		if ( n == 'right' )
		{ changeToTitle( y ); }
		changeToFolderName( y );
	}
	else
	{	
		if (n == 'right')
		{ str5 = y; }
		Depth = y.toLowerCase();
	}
}

// helper function: loads the title
// req: ttl=title
function loadTitle( x )
{
	document.getElementById( 'divTitle' ).innerHTML = '<p align="center"><b><font face="Verdana" size="2" color="#FFFFFF">' + x + '</font></b>';
}

/* helper function: converts a house name to the folder name */
function changeToFolderName( y )	// if the name has a number e.g. "Willow2" it will be split to "willow_2"
{
	var str = y;
	var index = "";
	var txt = "";
	
	index = str.lastIndexOf( "2" );	// this is the index
	txt = str.substr( 0, index );		// return string less the last number
	Depth = txt.toLowerCase() + '_' + str.substr( index,(index-1) );
	return Depth;
}

// helper function: converts a house name to a title
// if the name has a number e.g. "Willow2" it will be split to "Willow 2"
function changeToTitle(y)				
{
	var str = y;
	var index = "";
	var txt = "";

	if (str.lastIndexOf("1") != -1)
	{
		index = str.lastIndexOf("1")
	}
	else if (str.lastIndexOf("3") != -1)
	{
		index = str.lastIndexOf("3")
	}
	else if (str.lastIndexOf("2") != -1)
	{
		index = str.lastIndexOf("2")
	}
	else
	{
		index = str
		return index;
	}
	
	txt = str.substr(0,index)
	str5 = txt + ' ' + str.substr(index,(index-1));
	return str5;
}                        

// TESTING FUNCTIONS

// function for viewing array values | ENABLE WHEN TESTING
//========================================================
//function showArrayValues( arr, num )
//{
//    for(var i=0;i<=parseInt(num);i++)
//        alert("Array values are..."+arr[i][1])
//}
//========================================================


function  checkForOptionsToLoad()
{
    var coveredDeck, coveredPatio;
    
    getQueryString();
    evaluateQSValue( arrQS );
    // specifically retrieves covered deck value
    coveredDeck = arrQS[7][1];
    
    //alert("arrQS[7][1]="+coveredDeck)
    return coveredDeck;
}
// i can probably consolidate the function above checkForOptionsToLoad() and addCovDeckToPage( value ) but not now...
function addCovDeckToPage( value )
{
    // if the value is not present (n/a) then 
    if(value!="n/a")
    {
        document.write('<tr>')
        document.write('<td>Covered Deck</td>')
        document.write('<td>'+value+'</td>')
        document.write('</tr>')	  
    }   
}

// taken from script_ots.js =], changed element id names to suit
// contains a check whether there is a Basement element if so it considers this in the processing
function calculateTotal()
{
    var mainFloor;
    var upperFloor;
    var basement;
    var garage;
    var totalLiv;
    var totalFin;
    
    // retreive string-values from the HTML document, assign to variables
    mainFloor = document.getElementById( 'lblMain' ).innerHTML;
    upperFloor = document.getElementById( 'lblUpper' ).innerHTML;
    garage = document.getElementById( 'lblGarage' ).innerHTML;  
    
    // perform a check if the basement element exists
    if (document.getElementById( 'lblBasement' ) != null)
    {
        basement = parseInt(document.getElementById( 'lblBasement' ).innerHTML);
    }
    else
    {
        //alert('The basement element does not exist.\n'+'Continuing calculations...');
    }
    
    // process garage's value
    if (upperFloor != "n/a")
    {
        totalLiv = parseInt(mainFloor) + parseInt(upperFloor);
    }
    else if (mainFloor != "n/a")
    {
        totalLiv = parseInt(mainFloor);
    }    
    else
    {
        totalLiv = 0;
    }
    
    //alert('Performing preliminary calculations \n'+'totalLiv = '+totalLiv);

    if (basement == null || isNaN(basement)) // if basement IS empty or NotANumber add its value to total living
    {
        //alert('basement has NO value or '+basement+'\nLeaving decision structure and calculating total Finished Area... ');
    }
    else
    {
        //alert('basement has value of '+basement+'\n Calculating totalLiv + basement...');
        totalLiv = totalLiv + basement;
        //alert('Success! result is ='+totalLiv);
    }
    
    // process garage's value
    if (garage != "n/a")
    {
        totalFin = totalLiv + parseInt(garage);
    }
    else
    {
        totalFin = totalLiv;
    }
    
    // write the result to the page | did not parse result because HTML does not distinguish ints from strings
    document.getElementById( 'lblTotalLiving' ).innerHTML = totalLiv;
    document.getElementById( 'lblTotalFinished' ).innerHTML = totalFin;
}    

function makeLink( coll )
{
    var link = '<a href="javascript:history.go(-1)">'+coll+'</a>';
    return link;
}

// function to load contact us page
function loadContactUs()
{
    //alert ("in Load Contact Us function")
    
    var Link = "Home";
    var txtPath = "2006%20maple%20bottom2.htm";
    
    // display links and labels on the page
	document.getElementById( 'lblLink' ).innerHTML          = makeLink( Link, txtPath );   
	   
}

function doIt(passMe)
{
    toggleLayer( passMe );    
}

// code courtesy of http://www.netlobo.com/div_hiding.html
function toggleLayer(whichLayer)
{
    if (document.getElementById)
    {
    // this is the way the standards work
    var style2 = document.getElementById(whichLayer).style;
    style2.display = style2.display? "":"block";
    }
    else if (document.all)
    {
    // this is the way old msie versions work
    var style2 = document.all[whichLayer].style;
    style2.display = style2.display? "":"block";
    }
    else if (document.layers)
    {
    // this is the way nn4 works
    var style2 = document.layers[whichLayer].style;
    style2.display = style2.display? "":"block";
    }
}

function refresh()
{
    window.location.reload();
}