var displayingM2MSelector = false;
var doingValidate = false;

function notImplemented(functionName) {
  alert("\"" + functionName + "\" has not been implemented.");
}


function savePageValues()
{
	// Gemini 3505
	// save any existing data on this screen to BLIS
	if( typeof(getSaveValuesURL) != "undefined" )
	{
			var daURL = getContextPath()+"/prod/my-business-1?cmd=save_search_values"+getSaveValuesURL();
			document.getElementById("hiddenIFRAME").src = daURL;
			//alert("savePageValues SAVED! "+daURL);
	}		
} 
 
var focusedElement = null;
function doOnload() 
{  
   try{
		   if(errorMessage != "")
		   {
		      showErrorMessage("Error", errorMessage);
		   }
	}catch(error)
	{}
	
	try{
	   if(infoMessage != "")
	   {
	      showInfoMessage("Information", infoMessage);
	   }
	}catch(error)
	{}	   
   
   // keep track of who has got focus
   var e, i = 0
   while (e = document.getElementsByTagName ('*')[i++]) 
   {
     try{
       e.onfocus = function () {focusedElement = this;}
     }catch(error)
     {  // ignore
     }
   }   
   
   // call doOnload2 (if exists)
   try{
   	 if( doOnload2 )
   	 {  doOnload2();
   	 }
   }catch(error)
   { // ignore
   }
   
}



function learnMoreAboutBVABenefits()
{
	  window.open("http://business.vic.gov.au/BUSVIC/STANDARD//PC_61593.html");
}

//function verifyLocation(textFieldId)
//{
//		  alert("TODO: verifyLocation("+textFieldId+")");
//}

function doBackToStep1()
{

  //document.getElementById("my_results_form").action = "$!{context-path}/prod/my-business-1";
  //document.getElementById("my_results_requirement_selects").value = getReturnSelectsString();
  //document.getElementById("my_results_form").submit();
  
   if(saveMyWorkReturnPageURL != null)
   {  createCookie("previous_url",saveMyWorkReturnPageURL,1); // Gemini issue 4207 -> save my work return URL is more reliable than document location as sometimes a request to one page will redirect you to another
   }
   else
   {  createCookie("previous_url",document.location,1);
   }
  
   var daURL = "my-business-1";

   var curDate = new Date();
   daURL += "?rand="+curDate.getTime();

  window.location  = daURL;  

}

function doBackToAdvancedSearch()
{

  createCookie("previous_url",document.location,1);
  
   var daURL = "advanced-search";

   var curDate = new Date();
   daURL += "?rand="+curDate.getTime();

  window.location  = daURL;
  

}

  function getRadioValue(idOrName) {
          var value = null;
          var element = document.getElementById(idOrName);
          var radioGroupName = null;  
          
          // if null, then the id must be the radio group name
          if (element == null) {
                  radioGroupName = idOrName;
          } else {
                  radioGroupName = element.name;     
          }
          if (radioGroupName == null) {
                  return null;
          }
          var radios = document.getElementsByTagName('input');
          for (var i=0; i<radios.length; i++) {
                  var input = radios[ i ];    
                  if (input.type == 'radio' && input.name == radioGroupName && input.checked) {                          
                          value = input.value;
                          break;
                  }
          }
          return value;
  }
  

  
function getSelectedOption(daSelectId)
{
		var daSelect = document.getElementById(daSelectId);
		if(daSelect)
	  {
	  	  if(daSelect.selectedIndex > -1)
	  	  {  return daSelect.options[daSelect.selectedIndex].value;
	  	  }
	  }
    return "";
}


function goToStart()
{
   var daURL = "start";

   var curDate = new Date();
   daURL += "?rand="+curDate.getTime();

  window.location  = daURL;
}

function goToStep1()
{
   var daURL = "my-business-1";

   var curDate = new Date();
   daURL += "?rand="+curDate.getTime();

  window.location  = daURL;
}
  
 
// 
// Quick-search from the right-side frame
// 
function doQuickSearch()
{

	var searchText = document.getElementById("quickSearchText").value;
	if(searchText == "")
	{
		  showInfoMessage("Criteria Required", "Please specify some search criteria");
		  //document.getElementById("quickSearchText").focus(); // Gemini issue 3654
		  return;
	}
	else if( searchText.length < 3 )
	{
		  showInfoMessage("Criteria Required", "Your search criteria must be at least 3 characters long");
		  //document.getElementById("quickSearchText").focus(); // Gemini issue 3654
		  return;	
	
	}
	
    var daURL = "advanced-search?cmd=quick_search&text="+searchText;

    var curDate = new Date();
    daURL += "&rand="+curDate.getTime();
	
	window.location = daURL;	
	
	
} 


function refreshUsersBusinesses()
{  //alert("refreshUsersBusinesses");

   var daURL = "my-business-1?cmd=refresh_user_businesses";

   var curDate = new Date();
   daURL += "&rand="+curDate.getTime();

   document.getElementById("refreshUsersBusinessesIFRAME").src = daURL;
}

function resetUsersBusinessesOptions(daOptionsArray)
{
	 var selectedId = getSelectedOption('selected_business_id');
	
   var daSelect = document.getElementById("selected_business_id");
   daSelect.options.length = 0;
   
   // BC 20 Feb 2009 - add blank
   daSelect.options[daSelect.options.length] = new Option("", "-1"); 
   
   for(var i=0; i < daOptionsArray.length; i++)
   {
      var daOpt = new Option(daOptionsArray[i][1], daOptionsArray[i][0]);
      
      if(selectedId == daOptionsArray[i][0])
      {  daOpt.selected = true;
      }
      
      daSelect.options[daSelect.options.length] = daOpt;
   }
   
   // BC 20 Feb 2009 - sort by name
   sortSelect(document.getElementById("selected_business_id"));
    
   // Gemini issue 3657 - user expects the search to also be updated immediately
   setSelectedBusinessIdCookie(true);

}

function showPopupMessage(fieldPrefix, popupPrefix, heading, message, yCoordOverride, widthOverride)
{
         document.getElementById(fieldPrefix+"_heading").innerHTML = heading;
	     document.getElementById(fieldPrefix+"_message").innerHTML = message;
	       
	     showPopup(popupPrefix+"-MESSAGE", yCoordOverride, widthOverride);
     
         // Gemini issue 4198
         if(document.getElementById("cancelButton"+popupPrefix+"-MESSAGE"))
         { document.getElementById("cancelButton"+popupPrefix+"-MESSAGE").focus();
         }

}

function showPopup(popupId, yCoordOverride, widthOverride)
{
		     addNewPopupId(popupId);
	
		     $('body').css({'height': '100%', 'width':'100%'});
		     addOverlay("showPopup "+popupId);
		     
		     var daWidth = 450;
		     if(widthOverride > 0)
		     {  daWidth = widthOverride;
		     }		     
         
		     // center position the popup box
		     var xcoord = Math.max(10, ($(window).width() - (daWidth-20)) / 2);
		     var ycoord = Math.max(10, ($(window).height() - 283) / 2);
		     
		     if(yCoordOverride > 0)
		     {  ycoord = yCoordOverride;
		     }

		     // BC 06 August 2008: show in middle of screen, even if user has scrolled down
		     var topValue = document.documentElement.scrollTop + (document.documentElement.clientHeight - (document.documentElement.clientHeight-ycoord));
		     
		     $("#pop-up"+POPUP_ID).css({'left': xcoord, 'top': topValue});
		     $("#pop-up"+POPUP_ID).css({'width': daWidth});
		     $("#pop-up"+POPUP_ID).css({'visibility': 'visible'});
		     $("#pop-up"+POPUP_ID).removeClass('hide');
		     $("#pop-up"+POPUP_ID).css({'z-index': (9000+OVERLAY_COUNT+1)});
		     
		     $("#pop-up"+POPUP_ID).show();	
		     
					// workaround for IE6 problem with infinite z indexes on dropdown boxes
					if( is_ie6 && document.getElementById("zIndexFixFrame"))
					{
						 document.getElementById("zIndexFixFrame").style.top = 0;
						 document.getElementById("zIndexFixFrame").style.left = 0;
						 document.getElementById("zIndexFixFrame").style.width = "100%";
						 document.getElementById("zIndexFixFrame").style.height = 700;
						 
						 document.getElementById("zIndexFixFrame").style.zIndex = (9000+OVERLAY_COUNT);
						 document.getElementById("zIndexFixFrame").style.display = "inline";
					}						     
		     
}

var SHOWING_PLEASE_WAIT_MESSAGE = false;
var POPPED_UP_PLEASE_WAIT_MESSAGE = false;
var POPPED_UP_PLEASE_WAIT_MESSAGE = false;
var pleaseWaitMessage = null;
function showPleaseWait(message)
{	
	SHOWING_PLEASE_WAIT_MESSAGE = true;
	
	pleaseWaitMessage = message;
	
	/* BC 14 Aug 2009 - Gemini issue 5745 - having a delay can cause problems with 2 overlays appearing so show the please wait message straight away
	// delay actually showing the please wait show don't get a little popup flash
	// we also need the delay so the next "to-be" focussed element can actually get the focus!
  setTimeout ( "showPleaseWait2()", 800 ); // 500 = wait half a second before showing popup
	
}
function showPleaseWait2()
{
*/
	if(!SHOWING_PLEASE_WAIT_MESSAGE)
	{
		  // have been asked to hidePleaseWait() before got a chance to popup
		  return;
	}
	
	POPPED_UP_PLEASE_WAIT_MESSAGE = true;
	showPopupMessage("please_wait", "PLEASE_WAIT", "Please Wait...", pleaseWaitMessage); 
	document.getElementById("please_wait_image").focus();	
	
}
function hidePleaseWait()
{
	  //alert("hidePleaseWait() "+POPPED_UP_PLEASE_WAIT_MESSAGE);
	
	  if(POPPED_UP_PLEASE_WAIT_MESSAGE)
	  {
				removeOverlay();
				$('#pop-up'+POPUP_ID).hide();
				
					// workaround for IE6 problem with infinite z indexes on dropdown boxes
					if( is_ie6 && document.getElementById("zIndexFixFrame"))
					{
						 document.getElementById("zIndexFixFrame").style.display = "none";
					}								
				
		    removeLastPopupId();		 
		    
		    POPPED_UP_PLEASE_WAIT_MESSAGE = false; 	
	  }

    SHOWING_PLEASE_WAIT_MESSAGE = false;
}


function showErrorMessage(heading, message)
{
	       showPopupMessage("error", "ERROR", heading, message);      
}

function showWarningMessage(heading, message)
{
	       showPopupMessage("warning", "WARNING", heading, message); 
}

function showInfoMessage(heading, message)
{
	       showPopupMessage("info", "INFO", heading, message); 
}

function showYesNoPopup(heading, message)
{
	       var popupPrefix = "YES-NO";
	
	       document.getElementById(popupPrefix+"_heading").innerHTML = heading;
	       document.getElementById(popupPrefix+"_message").innerHTML = message;
	       
	       showPopup(popupPrefix);
}



// ********************** START COOKIE FUNCTIONS *****************************//
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
	
	//alert(document.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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}   
// ********************** END COOKIE FUNCTIONS *****************************// 

function setLicenceDetailsPopupId(id)
{
  // got to make the relevant div have an id of "pop-up" (see blis.js)
  addNewPopupId(""+id);
}

function openWindow(daURL)
{
  var windowHeight = 600;
  var windowWidth = 800;
  window.open(daURL, '_blank', 'left=' + ((screen.availWidth - windowWidth) /2 ) + ',top=' + ((screen.availHeight - windowHeight) /2 ) + ',toolbar=no,menubar=no,height=' + windowHeight + ',width=' + windowWidth + ',location=no,directories=no,resizable=no,scrollbars=no'); 
  return false;
}

function openResourcePdf(resourceId)
{
  var daURL = "resource-public?cmd=get_pdf&id="+resourceId;
  openResourceUrl(daURL);

}

function openResourceUrl(daURL)
{  
  var width=930;
  var height=400;
  window.open(daURL, "_resource", "status=yes, resizable=yes, scrollbars=yes, toolbar=no width="+width+", height="+height);
}

            
function openSmartFormsResourceUrl(daURL)
{
	
	// if no agency id is specified in the URL then prompt for a list of 'apply to' agencies
	//alert("getURLParameter( daURL, name ) = "+getURLParameter( daURL, "agency" ));
	
	if(getURLParameter( daURL, "agency" ) == "")
	{
		
		 // prompt user for the agency to assign this form to
		 document.getElementById("SELECT_COUNCIL_FOR_FPP-url").value = daURL;
		 
		 showPopup("SELECT_COUNCIL_FOR_FPP")	 
		 
	}
	else
  {  openResourceUrl(daURL);
  }
	
}

function openSmartFormsResourceUrl2()
{
	var daURL = document.getElementById("SELECT_COUNCIL_FOR_FPP-url").value;
	var selectedCouncil = getSelectedOption("SELECT_COUNCIL_FOR_FPP-councils");
	
	// assume url ends with "agency="
  openResourceUrl(daURL+selectedCouncil);
	
}


function getURLParameter( daURL, name )
{  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	 var regexS = "[\\?&]"+name+"=([^&#]*)";  
	 var regex = new RegExp( regexS );  
	 var results = regex.exec( daURL );  
	 if( results == null )    return "";  
	 else    return results[1];
}

function printDiv(divID)
{
			var a = window.open('','','scrollbars=yes,width=700,height=500');
				
		a.document.open("text/html");
		a.document.write('<html><head><title>BLIS</title>');
        a.document.write('<link rel="stylesheet" type="text/css" href="'+getBVHome()+'/BUSVICWR/ncObjects/ncTableAutoFormatStyles.css" />');
        a.document.write('<style type="text/css" media="screen, print"> ');
	    a.document.write('@import url('+getContextPath()+'/skin/normal/css/style.css); ');
		a.document.write('@import url('+getContextPath()+'/skin/normal/css/colour_sec01.css); ');
		a.document.write('@import url('+getContextPath()+'/skin/normal/css/blis.css);');
        a.document.write('</style>    ');
        a.document.write('<link rel="stylesheet" type="text/css" href="'+getBVHome()+'/BUSVICWR/staticassets/includes/print.css" media="print" />');
        a.document.write('<link rel="alternate stylesheet" type="text/css" href="'+getBVHome()+'/BusVicWR/staticassets/includes/large.css" media="screen" title="Large fonts">');
        a.document.write('<link rel="alternate stylesheet" type="text/css" href="'+getBVHome()+'/BusVicWR/staticassets/includes/medium.css" media="screen" title="Medium-size fonts">');
        a.document.write('<link rel="alternate stylesheet" type="text/css" href="'+getBVHome()+'/BusVicWR/staticassets/includes/small.css" media="screen" title="Small fonts">');
        a.document.write('<link rel="alternate stylesheet" type="text/css" href="'+getBVHome()+'/BusVicWR/staticassets/includes/x-small.css" media="screen" title="Extra-small fonts"> 				');
				a.document.write('</head>    ');
				a.document.write('<body>    ');
				
				var daHTML = document.getElementById(divID).innerHTML;
				
				
				//alert("daHTML="+daHTML);
				
				var temp, temp2;
				var textToRemove = '<div id=buttonsDIV>'.toUpperCase();
				var index = daHTML.toUpperCase().indexOf(textToRemove);
				if(index < 0)
				{
					  // firefox support
					  textToRemove = '<div id="buttonsDIV">'.toUpperCase();
				    index = daHTML.toUpperCase().indexOf(textToRemove);
				}
				
				
				if(index > 0)
				{  temp = daHTML.substring(0, index);
				   temp2 = daHTML.substring(index+textToRemove.length, daHTML.length);
				   
				   temp += temp2.substring(temp2.toUpperCase().indexOf("</DIV>"), temp2.length);
				   
				   daHTML = temp;
				}
				
				a.document.write(  daHTML );
				a.document.write('</body></html>');
				a.document.close();
				a.print();
}

// Force Firefox to open a new window
// Tested in IE 6, 7
// Tested in Firefox 1.5, 2, 3
// www.htmlhelpcentral.com
function winBRopen(theURL, windowName, popW, popH, scroll) 
{ // V 1.0
  var winleft = (screen.width - popW) / 2;
  var winUp = (screen.height - popH) / 2;
  var winProp = 'width='+popW+',height='+popH+',left='+winleft+',top='+winUp+',scrollbars='+scroll;
  var daWindow = window.open(theURL, windowName, winProp);
  if (parseInt(navigator.appVersion) >= 4)
  {
    daWindow.window.focus();
  }
}


function expandTextboxHeightToFit(daTextarea, minHeight) 
{

					  if((daTextarea.scrollHeight > minHeight)
					     && daTextarea.value != "")
					  {  newHeight = daTextarea.scrollHeight;
					  }
					  else
					  {  newHeight = minHeight;
					  }
					  daTextarea.style.height = newHeight+"px";

}


function openRequirementDetailsScreen(reqId)
{  
      var daURL = "my-results?cmd=search-requirement-details&requirement_id="+reqId;
      //window.open(daURL, "BLISRequirement", "toolbar=no,menubar=no,height=800,width=800,location=no,directories=no,resizable=yes,scrollbars=yes");
      winBRopen(daURL, "BLISRequirement", '800',' 700','yes');
}
 
     
Array.prototype.contains = function(obj) {  var i = this.length;  while (i--) {    if (this[i] === obj) {      return true;    }  }  return false;}
     
