//Global scripts: By Human Factors International
//Copyright 2008 Human Factors International (http://www.humanfactors.com)
//Description: All global functions (show/hide, menus etc.) are in this file.
//Author(s): Kavita Kawade, Sunil Rout
//Department: UIDT - User Interface Development Team
//Last update: July 25th, 08

// JavaScript Document

/**/
var tabCont_div;
var tabCont;
function showpop(obj,lyr)
{
	//alert(lyr);
	var coors = findPos(obj)	
	var x = document.getElementById(lyr);
	if (x.style.display == "block")
	{
		x.style.display = "none";
		document.getElementById('helpmetxt').className = "helpme";
	}
	else
	{
		x.style.display = "block";
	x.style.top = coors[1] + 23 + 'px';	
	x.style.left = coors[0] + -1 + 'px';	                             //alert(document.getElementByClassName('popup').nodeName);
	document.getElementById('helpmetxt').className = "helpmeup";
	}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	//alert(curleft)
	return [curleft,curtop];
}
	/*for toggle tabs*/
function setTab(tabName)
{
		
	tab = tabName
	tabCont = tab + "_desc"
}

function toggle(obj,tabnm){	
	//alert(obj.parentNode.className);
	//alert(tabnm)
	document.getElementById(tab).className = "";	
	document.getElementById(tabCont).style.display = 'none';
	obj.parentNode.className = "current";
	tab = tabnm;
	tabCont = tabnm + "_desc";
	//alert(tabCont);	
	document.getElementById(tabCont).style.display = "block";
	
}
/*Content_toggle*/
function set_DIV(val)
{
	tab_div = val;
	tabCont_div = "toggle_" + val;
}

function toggle_DIV(obj,id)
{
		if(document.getElementById(id).value != "sel")
		{
			document.getElementById(tabCont_div).style.display = 'none';
			tab_div = obj.value;
			tabCont_div = "toggle_" + obj.value;
			document.getElementById(tabCont_div).style.display = "block";
			//document.getElementById(tabCont).style.display = 'none';
			//tab = 'for_ex_'+obj.selectedIndex;
			//tabCont = tab + "_cont";
		//	document.getElementById(tab).className = "current";	
			//document.getElementById(tabCont).style.display = 'block';
		}
		else
		{
			//show blank page
			document.getElementById('toggle_custom').style.display = 'none';
			document.getElementById('toggle_raise').style.display = 'none';	
		}
}


function faq(val,number)
{	
		divCont_div = "q" + number + "_content";	
		divimage_img = "img_" + number;
	
	if(document.getElementById(divCont_div).style.display == "none")
	{
		document.getElementById(divimage_img).src = "";
		document.getElementById(divimage_img).src = "images/cont_twisty_down.gif";
		document.getElementById(divCont_div).style.display = "block";
		document.getElementById(divCont_div).className = "padding25";

	}
	else
	{
		document.getElementById(divimage_img).src = "";
		document.getElementById(divimage_img).src = "images/cont_twisty_right.gif";
		document.getElementById(divCont_div).style.display = "none";
	}
}
/**/
/* Table sort */

var lastcol, lastseq;
function f_sort( ao_table, ai_sortcol, ab_header )
{
	
	//alert(ao_table.rows.length);
    var ir, ic, is, ii, id; // ir = "Number of rows" , ic = "Number of cols"
	// ab_header = "if True than table do have header else False"
	// ai_sortcol = "Sort column"
	//alert(ao_table + ai_sortcol + ab_header);
    ir = ao_table.rows.length;
	//alert(ir);
    if( ir < 1 ) return;
	//alert(ao_table.rows[1].cells.length);
    ic = ao_table.rows[1].cells.length;
	
    // if we have a header row, ignore the first row
	  if( ab_header == true ) is=1; else is=0;
	    // take a copy of the data to shuffle in memory
    var row_data = new Array( ir );
    ii=0;
    for( i=is; i < ir; i++ )
    {
        var col_data = new Array( ic );
        for( j=0; j < ic; j++ )
        {
            col_data[j] = ao_table.rows[i].cells[j].innerHTML;
			//alert(col_data[j]);
        }
        row_data[ ii++ ] = col_data;
    }

    // sort the data
    var bswap = false;
    var row1, row2;
    //alert(ai_sortcol)
	//Follwing section to define same column hit or new column "A" stand for Ascending and "D" stand for Descending
    if( ai_sortcol != lastcol )
        lastseq = 'A';
    else
    {
        if( lastseq == 'A' ) lastseq = 'D'; else lastseq = 'A';
    }
	//alert(lastseq)

    // if we have a header row we have one less row to sort
    if( ab_header == true ) id=ir-1; else id=ir;
	//alert(ab_header);
    for( i=0; i < id; i++ )
    {
        bswap = false;
        for( j=0; j < id - 1; j++ )
        {
            // test the current value + the next and
            // swap if required.
			// alert(row_data[j]);
            row1 = row_data[j];
            row2 = row_data[j+1];			
            if( lastseq == "A" )
            {
				/*change 13mar write extra code*/
				//if( lastseq == "A" ){
				//document.getElementById("dsort").style.display = "block";
				//document.getElementById("asort").style.display = "none";							
				//}
                if( row1[ ai_sortcol ] > row2[ ai_sortcol ] )
                {
                    row_data[j+1] = row1;
					//alert()
                    row_data[j] = row2;
                    bswap=true;
                }
            }
            else
            {
				/*change 13mar write extra code*/
				//document.getElementById("dsort").style.display = "none";
				//document.getElementById("asort").style.display ="block" ;
                if( row1[ ai_sortcol ] < row2[ ai_sortcol ] )
                {
                    row_data[j+1] = row1;
                    row_data[j] = row2;
                    bswap=true;
                }
            }
        }
        if( bswap == false ) break;
    }

    // load the data back into the table
    ii = is;
    for( i=0; i < id; i++ )
    {
        row1 = row_data[ i ];
        for( j=0; j < ic; j++ )
        {
            ao_table.rows[ii].cells[j].innerHTML = row1[j];
        }
        ii++;
    }	
    lastcol = ai_sortcol;
	//alert("done");
}
var valObj=new Array();
var valObjHTML=new Array();
function setSorted(obj,colName,tbl_num)
{	
	valObj[tbl_num] = obj;
	valObjHTML[tbl_num] = colName;
	alert(valObjHTML[tbl_num])
}
var currimage = "sorteduparrow.gif";
function changecolor1(obj,tbl_num,tblname,clmno)
{
	//Setting previous cloumnn as not selected
	alert(valObjHTML[tbl_num])
	/*if (valObj[tbl_num].innerHTML != obj.innerHTML)
	{
		//valObj[tbl_num].className = "";
		valObj[tbl_num].innerHTML = valObjHTML[tbl_num];
		currimage = "sorteduparrow.gif";		
	}
	else
	{
		
	}*/
	//valObj[tbl_num].innerHTML = valObjHTML[tbl_num];
		if (currimage == "sorteduparrow.gif")
			currimage = "sorteddownarrow.gif";
		else
			currimage = "sorteduparrow.gif";
	//alert();
	//Setting new column as selected or sorted
	//obj.className = "onClck";
	valObjHTML[tbl_num] = obj.innerHTML ;
	obj.innerHTML = valObjHTML[tbl_num] + ' <img src="images/' + currimage + '" alt="" width="9" height="7" />';
	valObj[tbl_num] = obj;
	
	//Calling sort function
	f_sort( document.getElementById(tblname), clmno, true );
}
/*end of sorting*/
function position_title()
{
		document.getElementById('pt').style.display = "block";
}
function changeTBL(obj)
{
		document.getElementById(tabCont_divrates).style.display = 'none';
		tab_divrates = obj.value;
		//alert(obj.value);
		tabCont_divrates = "toggle_" + obj.value;
		//alert(tabCont_div);
		document.getElementById(tabCont_divrates).style.display = "block";
		//document.getElementById(tabContrates).style.display = 'none';
	}
	function set_DIVrates(val)
{
		//alert();
	tab_divrates = val;
	tabCont_divrates = "toggle_" + val;
	
}
function filter()
{
	if(document.getElementById('filter').style.display == "none")
	{
		document.getElementById('filter').style.display = "block";
		
	}
	else{
		document.getElementById('filter').style.display = "none";
		}

}

valimg=0;
function arrowsort()
{
	
	if (valimg==0)
	{document.getElementById('sortimg').src = "images/sorteduparrow.gif";
	valimg =1;
	}
	else
	{document.getElementById('sortimg').src = "images/sorteddownarrow.gif";
	valimg=0;
	}

}
function arrowsort1()
{
	
	if (valimg==0)
	{document.getElementById('sortimg1').src = "images/sorteduparrow.gif";
	valimg =1;
	}
	else
	{document.getElementById('sortimg1').src = "images/sorteddownarrow.gif";
	valimg=0;
	}
	

	
}
function timeframe()
{
	document.getElementById('toggle_annual').style.display = "none";
	document.getElementById('toggle_quarterly').style.display = "block";
}
function timeframeq()
{
	document.getElementById('toggle_annual').style.display = "block";
	document.getElementById('toggle_quarterly').style.display = "none";
}
function forgotpsw()
{
	document.getElementById('forgotpsw').style.display = "block";}

function chngsrc(val1,val2)
{
	for( i=1;i<27; i++ )
    {
		if (i==val2)
		{
			 document.getElementById(val2).className ="current";
		}
		else
		{
			 document.getElementById(i).className =""
		}
     }
	pagepath =	val1 + ".html";
	document.getElementById('gloss').src=pagepath;  	
	
}

function showDescription(id)
{
	document.getElementById(id).style.visibility = 'visible';	
}

function hideDescription(id)
{
	document.getElementById(id).style.visibility = 'hidden';	
}

function showNextList()
{
		document.getElementById('productList').style.visibility = 'visible';
}

function showNextButton()
{
		document.getElementById('next_bt').style.visibility = 'visible';
}

function openModalDialogWindow(){

	emailwindow=dhtmlmodal.open('EmailBox', 'iframe', 'request_call.html', 'Request a call', 'width=520px,height=300px,center=1,resize=0,scrolling=0')
} 

function jumpToURL() 
{
	document.location.href = jumpToURLValue;
}
//hides tooltip
function hide_tip()
{
	if (ns6||ie)
	{
//disable tip
		enabletip=false;
//hide all objects
		tipobj.style.visibility="hidden";
		pointerobj.style.visibility="hidden";
		tipobj.style.left="-1000px";
	}
}

function openModalDialogWindowemail(){

	emailwindow=dhtmlmodal.open('EmailBox', 'iframe', 'emailus.html', 'E-mail Us','width=520px,height=365px,center=1,resize=0,scrolling=0')
}

function openModalDialogWindowpassword(){

	emailwindow=dhtmlmodal.open('EmailBox', 'iframe', 'forgotpassword.html', '','width=520px,height=190px,center=1,resize=0,scrolling=0')
} 

function showRegion()
{
	var address = location.href;
	searchVar = address.indexOf("?");
	if(searchVar != -1)
	{
		reg = address.split("?")[1].split("=")[1];
		if(reg !='')
		{
			var list = document.getElementById('startpage');
			document.forms[0].startpage.options[reg].selected = true;
			
		}
	}
}

function changePageFromLogin()
{
	selOpt = document.loginform.select_account.selectedIndex;
	switch(selOpt)
	{
		case 1:
				window.location = "bk_onlinebk.html";
				break;
		case 2:
				window.location = "hl_mymortgage_overview.html";
				break;
	}
}

var icon;
var cm_map;
var cm_mapMarkers = [];
var cm_mapHTMLS = [];
var geocoder = null;
var locate = 0;
var searchaddressMarker
/* Google Functions */

function generateMap()
{
	document.getElementById('cm_mapsTABLE').style.display = 'block';
	icon = new GIcon();
  	icon.image = 'images/custom_logo.gif';
	icon.iconSize = new GSize(49, 37);
	icon.shadowSize = new GSize(36, 34);
	icon.iconAnchor = new GPoint(3, 23);
 	icon.infoWindowAnchor = new GPoint(5, 2);
 
	cm_map = new GMap2(document.getElementById("map_canvas"));
	cm_map.addControl(new GSmallMapControl());
	cm_map.setCenter(new GLatLng(34.049495, -118.202424), 10);
	geocoder = new GClientGeocoder();
}

function getMapData()
{
		generateMap();
	
		for (var i = 0; i < markers.length; i++) 
		{
			var point = new GLatLng(markers[i]['latitude'],markers[i]['longitude']);	
			var html = "<div class='mapheaderbreak'>";
			html += markers[i]['name'];
			html += "</div><div class='mapfont'>";
			html += markers[i]['addr'];
			html += "</div><div class='mapbreak'>";
			html += markers[i]['contact'];
			html += "</div><div class='mapbreak'>";
			html += markers[i]['hours'];
			html += "</div><div class='mapbreak'>";
			html += markers[i]['features'];
			html += "</div>";
			
			// create the marker
			var marker = cm_createMarker(point,html);
			cm_map.addOverlay(marker);
			cm_mapMarkers.push(marker);
			cm_mapHTMLS.push(html);
		}
}

function cm_createMarker(point,html) 
{
  var markerOpts = {};

  markerOpts = {
			"icon": icon,
			"clickable": true,
			"labelOffset": new GSize(-6, 10)
		  };

  var newPoint = point;
  var marker = new LabeledMarker(newPoint, markerOpts);

  GEvent.addListener(marker, "click", function() {
    marker.setImage('images/custom_logo.gif');
    marker.openInfoWindowHtml(html);
  });

  GEvent.addListener(marker, "mouseover", function() {
    marker.setImage('images/custom_logo.gif');
  });

  GEvent.addListener(marker, "mouseout", function() {
    marker.setImage('images/custom_logo.gif');
  });

  GEvent.addListener(marker, "infowindowclose", function() {
    marker.setImage('images/custom_logo.gif');
  });

  return marker;
}

function cm_markerClicked(markerNum) 
{
	cm_mapMarkers[markerNum].openInfoWindowHtml(cm_mapHTMLS[markerNum]);
}

function showAddress() 
{
	selectedState = document.form1.location.selectedIndex;
	if(selectedState == '')
	{
		selectedState = city;	
	}
	if(selectedState != 0)
	{
		address = markers[selectedState-1]['zip'];
		stat = true;
	}
	else
	{
		address = document.form1.zip_code.value;
		if(address == '')
		{
			address = zipCode;
			stat = true
		}
		else
			stat = checkZipCode();
	}
	if(stat == true)
	{
		if (geocoder) 
		{
			geocoder.getLatLng(address,
			function(point) 
			{
				if (!point) 
				{
					alert(address + " does not exist");
				} 
				else 
				{
					if(searchaddressMarker)
					{
						cm_map.removeOverlay(searchaddressMarker);
					}
					var searchicon = new GIcon();
					searchicon.image = 'images/mark.gif';
					searchicon.iconSize = new GSize(16, 16);
					searchicon.iconAnchor = new GPoint(16, 16);
					searchicon.infoWindowAnchor = new GPoint(25, 7);
					searchopts = {
								"icon": searchicon,
								"clickable": true,
								"labelOffset": new GSize(-6, -10)
								};
					searchaddressMarker = new LabeledMarker(point, searchopts);
					cm_map.setCenter(point,11);
					cm_map.addOverlay(searchaddressMarker);

				}
			});

			maxZipCode = parseInt(address) + parseInt(10);			//for +10 and -10 range
			minZipCode = address - 10;

			document.getElementById('cm_sidebarDIV').innerHTML = '';
			for (var i = 0; i < markers.length; i++)
			{
				if(markers[i]['zip'] <= maxZipCode && markers[i]['zip'] >= minZipCode)
				{
					var sidebarText= "";
					sidebarText += markers[i]['name'];

					var addrText= "";
					addrText += markers[i]['addr'];
					var markerA = "<a href=javascript:cm_markerClicked('" + i + "')><b>" + sidebarText + "</b></a>";
					markerA += "<br>" + addrText + "<br><br>";
					
					document.getElementById('cm_sidebarTD').className="mapTD2"
					document.getElementById('cm_sidebarDIV').innerHTML += markerA;
				}
			}
			if(document.getElementById('cm_sidebarDIV').innerHTML == '')
			{
				document.getElementById('cm_sidebarTD').className="";
			}

		}
	}
} 


/* EOF */


function checkZipCode()
	{
		address = document.form1.zip_code.value;
		if(address.length < 5)
		{
			alert("ZIP cannot be less than 5 digits");
			return false;
		}
		else
		{
			//showLocation(address);
			if(address< 90001 || address> 95864)
			{
				alert("Please enter a valid ZIP for California State")
				return false;
			}
			else
			{
				return true;	
			}	
		}
	}
	
	function addAddressToMap(response)
	{
		place = response.Placemark[0];
		if (!response || response.Status.code != 200) 
		{
			alert("Sorry, we were unable to geocode that address");
		} 
		else 
		{
			latitude = place.Point.coordinates[1];
			longitude = place.Point.coordinates[0];
			if(!(latitude >= 32.44 && latitude <= 41.46) && !(longitude <= -114.37 &&	longitude >= -124.6))
			{
				alert("Please enter a zipcode within California");	
				return false;
			}
			else
				return true;
			
		}
    }

    function showLocation(zip) 
	{
      	geocoder.getLocations(zip, addAddressToMap);
    }
	
	function checkResults()
	{
		var address = location.href;
		searchVar = address.indexOf("?");
		if(searchVar != -1)
		{
			status = address.split("&")[0].split("?")[1].split("=")[1];
			if(status == "show")
			{
				document.getElementById('search_results').style.display = 'block';	
			}
			
			// show all the selected fields in the form
			proptype = address.split("&proptype=")[1].split("&")[0];
			document.getElementById('prop_type').selectedIndex = proptype;
			city = address.split("&city=")[1].split("&")[0];
			document.getElementById('city').value  = city;
			state = address.split("&state=")[1].split("&")[0];
			document.getElementById('state').selectedIndex = state;
			zip = address.split("&zip=")[1].split("&")[0];
			document.getElementById('zip').value  = zip;
			bedroom = address.split("&bedroom=")[1].split("&")[0];
			document.getElementById('bedroom').selectedIndex = bedroom;
			maxbedroom = address.split("&maxbedroom=")[1].split("&")[0];
			document.getElementById('bedroom_max').selectedIndex = maxbedroom;
			bathroom = address.split("&bathroom=")[1].split("&")[0];
			document.getElementById('bathroom').selectedIndex = bathroom;
			maxbathroom = address.split("&maxbathroom=")[1].split("&")[0];
			document.getElementById('bathroom_max').selectedIndex = maxbathroom;
			minprice = address.split("&minprice=")[1].split("&")[0];
			document.getElementById('price_min').selectedIndex = minprice;
			maxprice = address.split("&maxprice=")[1].split("&")[0];
			document.getElementById('price_max').selectedIndex = maxprice;
		}
	}
	
	function showPropertyDetails(LinkDetail)
	{
		detailswindow=dhtmlmodal.open('Property Details', 'iframe', LinkDetail, 'Property Details', 'width=740px,height=562px,center=1,resize=0,scrolling=0')
	} 
	
	function showJobCategory()
	{
		var address = location.href;
		searchVar = address.indexOf("?");
		if(searchVar != -1)
		{
			cat = address.split("?")[1].split("=")[1];
			document.getElementById('jobcategory').selectedIndex = cat;
		}
	}

	function showListingDetail(LinkDetail)
	{
		showPropertyDetails(LinkDetail);
		
	} 
	