﻿/////////////////////////////////////////////////
// 3Fi.dk related JavaScript functions
// 
// !!Please remember to comment your functions!!
//
/////////////////////////////////////////////////


/////////////////////////////////////////////////
//  WebApplication related
/////////////////////////////////////////////////
var webApplicationURL = null;
function registerWebApplicationURL(url) {
  webApplicationURL = url;
}
function getWebApplicationURL() {
  return webApplicationURL;
}


/////////////////////////////////////////////////
//  Messagebox related
/////////////////////////////////////////////////
function ShowMessageBox(text, header, title, button1Action, button1Title, button2Action, button2Title)
{
  Page.Message.setSubject(title);
  Page.Message.setHeader(header);
  Page.Message.addBodyText(text);
  
  if(button2Action != null && button2Action != "" && button2Title != null && button2Title != "")
    Page.Message.addButton(button2Title,button2Action);   
  if(button1Action != null && button1Action != "" && button1Title != null && button1Title != "")
    Page.Message.addButton(button1Title,button1Action);
  
  Page.Message.open();
}

function ShowErrorMessageBox(text, header, title)
{
  Page.Message.setSubject(title);
  Page.Message.setHeader(header);
  Page.Message.addBodyText(text);
  Page.Message.open('error');
}

function DisposeMessageBox()
{
  Page.Message.close();
}


/////////////////////////////////////////////////
//  Tab related
/////////////////////////////////////////////////
function SelectFirstTab() {
  /* Selected the first tab in the Peytz tab control */
  Page.Tabs.init();
  if (Page.Tabs.elements[0] != null)
    Page.Tabs.openTab(Page.Tabs.elements[0]);
}


/////////////////////////////////////////////////
//  TabPanel searches
/////////////////////////////////////////////////
function SubmitSearchCompany() {
  var criteria = document.getElementById("SearchCompanyCriteria").value;
  var text = document.getElementById("SearchCompanyWord").value;
  var url = getWebApplicationURL() + "/fagligt%5Fsystem/search98.asp?" + criteria + "=" + text

  window.open(url, 'Virksomheder', 'width=1024,height=768,resizable=yes,scrollbars=yes,toolbar=yes,location=yes,status=yes,menubar=yes')
}

function SubmitSearchDepartment() {
  var criteria = document.getElementById("SearchDepartmentCriteria").value;
  var text = document.getElementById("SearchDepartmentWord").value;

  var url = "/sitecore modules/forms/fff.Generic_post.aspx";
  url += "?formaction=" + escape(getWebApplicationURL() + "/afdelingsopl/list_afdelinger.asp")
  url += "&submitname=submit"
  url += "&submitvalue=S%F8g%20"
  url += "&formname=soge_afd"
  url += "&afdnr=" + escape((criteria == "afdnr" ? text : ""))
  url += "&afd_navn=" + escape((criteria == "afd_navn" ? text : ""))
  url += "&ledelse=" + escape((criteria == "ledelse" ? text : ""))
  url += "&distrikt=0"
  url += "&RawUrl=1" //Use ASCII encoding /Raw url on generic post
  
  location.href = url;
}

function SubmitSearchPhonebook() {
  var criteria = document.getElementById("SearchPhonebookCriteria").value
  var text = escape(document.getElementById("SearchPhonebookWord").value)

	var url = "http://cm2/ccmuser/directory.asp?findBy=" + criteria + "&match=contains&pattern=" + text + "&rows=25"
  window.open(url, "Telefonbog", "width=1024,height=768,resizable=yes,scrollbars=yes,toolbar=yes,location=yes,status=yes,menubar=yes")
}

// Will redirect to 'redirectToUrl' with text from inputControlID as parameter
function SubmitGenericSearch(inputControlID, redirectToUrl) {
  var text = escape(document.getElementById(inputControlID).value);
	var url = redirectToUrl + '=' + text;
	window.location.href = url;
}


function SubmitSearchMemo() {
  var sSearchTitle = document.getElementById("SearchMemoTitle").value;
  var sSearchContent = document.getElementById("SearchMemoContent").value;
  var sSearchNr = document.getElementById("SearchMemoNumber").value;
  var sSearchSelVal = document.getElementById("SearchMemoSelect").value;  
  var sSearchAar = document.getElementById("SearchMemoYearDropdownList").value;  

  var url = "/sitecore modules/forms/fff.Generic_post.aspx";
  url += "?formaction=" + escape(getWebApplicationURL() + "/cirkulaerer/soegning.asp")
  url += "&formname=dokumentform"
  url += "&submitname=Action"
  url += "&submitvalue=S%f8g"
  
  url += "&Tekst=" + escape(sSearchContent)
  url += "&meta_overskrift=" + escape(sSearchTitle)
  url += "&Ophav=" + escape(sSearchSelVal)
  url += "&udsnr=" + escape(sSearchNr)
  url += "&aar=" +  escape(sSearchAar)
  url += "&RawUrl=1" //Use ASCII encoding /Raw url on generic post
  
  location.href = url;
}

function SubmitSearchUnionRep() {
  var sSearchUnionRepName = document.getElementById("SearchUnionRepName").value;
  var sSearchUnionRepCpr = document.getElementById("SearchUnionRepCpr").value;
  var SearchUnionRepJob = document.getElementById("SearchUnionRepJob").value;
  
  var url = "/sitecore modules/forms/fff.Generic_post.aspx";
  url += "?formaction=" + escape(getWebApplicationURL() + "/Tillidshverv/soegning/MTS_find.asp")
  url += "&formname=SearchForm"
  url += "&submitname=submit"
  url += "&submitvalue=S%f8g"
  
  url += "&medlemsnavn=" + escape(sSearchUnionRepName)
  url += "&cprnr=" + escape(sSearchUnionRepCpr)
  url += "&Hverv=" + escape(SearchUnionRepJob)
  url += "&gruppenr=0"
  url += "&afdnr1=0"  
  url += "&RawUrl=1" //Use ASCII encoding /Raw url on generic post
  
  location.href = url;
    
}

function SubmitSearchLabourAgreement() {
  var sSearchLabourAgreementWords = document.getElementById("SearchLabourAgreementWords").value;
  var sSearchLabourAgreementDecisionType = document.getElementById("SearchLabourAgreementDecisionType").value;
  var sSearchLabourAgreementDecisionUnion = document.getElementById("SearchLabourAgreementDecisionUnion").value;
  var sSearchLabourAgreementDecisionGroup = document.getElementById("SearchLabourAgreementDecisionGroup").value;


  var url = "/sitecore modules/forms/fff.Generic_post.aspx";
  url += "?formaction=" + escape(getWebApplicationURL() + "/FagretsligeAfg/soegning/soegning.asp")
  url += "&formname=dokumentform"
  url += "&submitname=Action"
  url += "&submitvalue=S%f8g"
  
  url += "&Tekst=" + escape(sSearchLabourAgreementWords)
  url += "&Meta_AfgType=" + escape(sSearchLabourAgreementDecisionType)
  url += "&meta_Gruppe=" + escape(sSearchLabourAgreementDecisionGroup)
  url += "&Meta_AfdNr=" + escape(sSearchLabourAgreementDecisionUnion)
  url += "&Meta_ArbgKobNr="
  
  url += "&RawUrl=1" //Use ASCII encoding /Raw url on generic post
  
  location.href = url;

}


/////////////////////////////////////////////////
//  Image functions
/////////////////////////////////////////////////
function MM_swapImgRestore() { //v3.0
		var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
	}

	function MM_findObj(n, d) { //v4.01
		var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
		if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
		for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
		if(!x && d.getElementById) x=d.getElementById(n); return x;
	}

	function MM_swapImage() { //v3.0
		var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
		if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
	}


/////////////////////////////////////////////////
//  General utility functions
/////////////////////////////////////////////////

// Closes the current window
function ClosePopUp(reloadParent)
{  
  if(reloadParent)
    window.opener.document.forms[0].submit();
  window.close();  
}

// Sets the source for an image
function SetImageSource(imagePath,image) 
{   
  if (imagePath != "" && image != null) 
  {     
      image.src = imagePath;      
  }
}

function ShowConfirm(confirmText, functionCall)
{
   if(confirm(confirmText))
      setTimeout(functionCall,0);
}

// Shows a new pop-up window
function ShowPopUp(path,width,height)
{
  window.open(path,null,"height=" + height + ",width=" + width + ",status=yes,toolbar=no,menubar=no,location=no");
}

// Shows a new resizable pop-up window
function ShowResizablePopUp(path,width,height)
{
  window.open(path,null,"height=" + height + ",width=" + width + ",scrollbars=no,resizable=yes,status=yes,toolbar=no,menubar=no,location=no");
}

// Shows a new normal window
function ShowNewWindow(path,width,height)
{
  window.open(path,null,"height=" + height + ",width=" + width + ",scrollbars=yes,resizable=yes,status=yes,toolbar=yes,menubar=yes,location=yes");
}

function ShowHelp(path,width,height)
{
	// Cache Sitecore ID for use with help content	
	var metaTags = document.getElementsByTagName("META");
  var helpid = '';
  for(var i=metaTags.length-1; i>=0; i--)
		if (metaTags[i].name == 'scID')
			helpid = metaTags[i].content;

	var thepath = path;
	if (helpid != '')
		thepath = path + '?helpid=' + helpid;
		
	Page.Util.popUp(thepath, 'Hjælp', width, height);
}

// Clears the content of a SELECT
function ClearSelect(ctlSelect)
{
  for(var i=ctlSelect.options.length-1; i>=0; i--)
    ctlSelect.options.remove(i);
  
}

// Selects a value in a SELECT
function SetSelectedValue(selectID,value) 
{
  var select = document.getElementById(selectID);
              
  for(var i=0; i < select.options.length; i++)
  {
    if(select.options(i).value == value)
    {
      select.selectedIndex = i;
      break;
    }
  }
}

// Hides or shows an element
function SetVisible(element, visible)
{
  if(element != null)
  {   
    element.style.display = (visible == true ? "" : "none");   
  }
}

// Moves an OPTION up in a SELECT
function MoveOptionUp(select, option)
{
  if(select != null && option != null && option.index > 0)
  {
    var prevOption = select.options[option.index-1];
    prevOption.swapNode(option);
  }
}

// Moves an OPTION down in a SELECT
function MoveOptionDown(select, option)
{
  if(select != null && option != null && option.index < select.options.length-1)
  {
    var nextOption = select.options[option.index+1];
    nextOption.swapNode(option);
  }
}

// Moves the selected OPTION element from one SELECT to another SELECT
function MoveSelectedOption(source, destination)
{
  if(source != null && source.selectedIndex >= 0 && destination != null )    
  {    
    var selectedOption = source.options(source.selectedIndex);
  
    // Create new option
    var newOption = document.createElement("OPTION");
    destination.options.add(newOption);            
    newOption.innerText = selectedOption.innerText;
    newOption.value = selectedOption.value;
       
    // Remove original option
    source.options.remove(source.selectedIndex);
  }
}

// Get the selected value in a SELECT
function GetSelectedValue(select)
{
  if(select != null)
  {
    return select.options[select.selectedIndex].value;
  }
  return ""; 
}

// Returns a pipe separated list of the valus in a SELECT
function GetValuesInSelect(select)
{
  if(select != null)
  {
    var retval = "";
    for(var i = 0; i < select.options.length; i++)
    {
      retval += select.options[i].value + "|";
    }
    return retval;
  }
}

function GetQueryVariable(variable) 
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i<vars.length; i++) 
  {
    var pair = vars[i].split("=");
    if (pair[0] == variable) 
    {
      return pair[1];
    }
  } 
  return "";
}

// Sets the value of a variable in the query string and returns the complete
// url and query string
function SetQueryStringVariable(query, variable, value)
{
  var retval = "";  
  if(query.length > 0)
  {
    if(query.indexOf(variable + "=") > -1)
    {
      var vars = query.split("&");            
      for(var i = 0; i < vars.length; i++) 
      {
        var pair = vars[i].split("=");
        if (pair[0] == variable)         
          retval += variable + "=" + value;
        else
          retval += vars[i];
        if(i + 1 < vars.length)
          retval += "&";
      }
    }
    else    
      retval += query + "&" + variable + "=" + value;    
  }
  else  
    retval = variable + "=" + value;
   
  return retval;
  
}

/////////////////////////////////////////////////
//  Activity calendar functions
/////////////////////////////////////////////////
function SetListMode()
{ 
  var sourceSelect = window.event.srcElement;
  var selectedListMode = sourceSelect.options(sourceSelect.selectedIndex).value
  var query = window.location.search.substring(1);
    
  query = SetQueryStringVariable(query, "listmode", selectedListMode)  
  
  if(selectedListMode == "nonapproved")  
    query = SetQueryStringVariable(query, "startdate", "")    
  
  location.href = location.href.split("?")[0] + "?" + query;
}

/////////////////////////////////////////////////
//  Menu functions
/////////////////////////////////////////////////
function MenuSetHeaderBanner()
{
	var sResult = "";
	sResult += "<div>";
	sResult += "<a href='" + topFrieseUrl + "' target='_blank'>";
	sResult += "<img src='" + topFrieseSrc + "'>";
	sResult += "</a>";
	sResult += "</div>";
	
	return sResult;
}

// append extension
function appendExtension(localMenuExtension){
	// iterator to identify extension point
	this.iterate = function(content, dogtag){
		for(var i = 0; i < content.length; i++){
			if(content[i].dogtag && content[i].dogtag == dogtag){
				return content[i];
			}else if(content[i].childs){
				var extensionPoint = iterate(content[i].childs, dogtag);
				if(extensionPoint){
					return extensionPoint;
				}
			}
		}
		return false;
	}
	// append new items at extension point
	this.append = function(content){
		if(content.childs){
			content.childs = content.childs.concat(localMenuExtension.childs);
		}else{
			content.childs = localMenuExtension.childs;
		}
	}

	// identify and append
	var menuObject = this.iterate(menucontent.childs, localMenuExtension.dogtag);
	if(menuObject){
		append(menuObject);
	}else{
		alert("Menu punktet kunne ikke findes!\nKontroller extension dogtag");
	}
}

// remove extension
function removeExtension(localMenuExtension){
	// iterator to identify extension point
	this.remove = function(content, dogtag){
		for(var i = 0; i < content.length; i++){
			if(content[i].dogtag && content[i].dogtag == dogtag){
				var tmp = content[i];
				content.splice(i, 1);
				return tmp;
			}else if(content[i].childs){
				var extensionPoint = iterate(content[i].childs, dogtag);
				if(extensionPoint){
					return extensionPoint;
				}
			}
		}
		return false;
	}

	// identify and remove
	var menuObject = this.remove(menucontent.childs, localMenuExtension.dogtag);
	if(menuObject){
	}else{
		alert("Menu punktet kunne ikke findes!\nKontroller extension dogtag, for fjernede items.");
	}
}


/////////////////////////////////////////////////
//  Misc functions
/////////////////////////////////////////////////
function RefreshHelpPage(refreshOpener)
{
  if(refreshOpener && window.parent.opener != null)   
    window.parent.opener.document.location.href = window.parent.opener.document.location.href ;
  RemoveCommandFromQS();
  window.parent.location = window.parent.location;
}

function ReloadNewsPage() {
  setTimeout(ReloadNewsPageTimer, 10000);
}

function ReloadNewsPageTimer() {
  document.location.reload();
}

function RemoveCommandFromQS()
{
  var cmdStartIdx = document.location.search.indexOf("command"); 

  // If there's a command in the query string, remove it
  if (cmdStartIdx > -1)
  {
    var cmdEndIdx = document.location.search.indexOf("&", cmdStartIdx);
    var commandstring;
    
    if(cmdEndIdx > -1)
      commandstring = document.location.search.substring(cmdStartIdx, cmdEndIdx);
    else
      commandstring = document.location.search.substring(cmdStartIdx);
    
    document.location.href = document.location.href.replace(commandstring, "");    
  } 
}


function PrintThisPage() 
{ 
   var sOption="toolbar=yes,location=no,directories=yes,menubar=yes,"; 
       sOption+="scrollbars=yes,width=750,height=600,left=100,top=25"; 
   
   var winprint=window.open("/sitecore modules/Forms/fff.PrinterPage.aspx","",sOption); 
   winprint.focus(); 
}

function DeleteItem(sID)
{    
  var server = new Server("/sitecore/client/api/api.asmx", "http://sitecore.net/client/api/");
  server.Execute("DeleteItem", new Array("sItemList", sID))
  
  window.location.reload(false);
}


/////////////////////////////////////////////////
// Validation functions
/////////////////////////////////////////////////
function ValidateNewHelpItemName_Slash(source, arguments)
{ 
  if(arguments.Value.indexOf('/') == -1)
    arguments.IsValid = true;
  else
    arguments.IsValid = false;   
}

function ValidatePanelInput(inputs)
{
  for(var i = 0; i < inputs.length; i++)
  {
    if(inputs[i].value.trim() == "")
      return false;
  }
  return true;
}

/////////////////////////////////////////////////
// UpdateUserProfile functions
/////////////////////////////////////////////////
function UpdateUserProfile_EmailChange(emailListID, emailTextboxID) {
  var emailList = document.getElementById(emailListID);
  var emailText = document.getElementById(emailTextboxID);
  emailText.value = '';
  if (emailList.selectedIndex < emailList.options.length-1)
    emailText.style.display = "none";
  else
    emailText.style.display = "";
}

function UpdateUserProfile_ValidateEmail(emailTextboxID)
{
  var emailText = document.getElementById(emailTextboxID);

  if (emailText.value == '') {
    alert("Ugyldig e-mail adresse. Indtast venligst en korrekt e-mail adresse f�r der forts�ttes");
    emailText.focus();
    return false;
  }
  return true;
}

/////////////////////////////////////////////////
// Search as you type functions
/////////////////////////////////////////////////
var Results;
var HTML;
var RegionsArr = new Array();
var DepartmentsArr = new Array();
var OldDepartmentsArr = new Array();
var OfficesArr = new Array();
function SearchAsYouType() {

  RegionsResults = 0;
  DepartmentsResults = 0;
  OldDepartmentsResults =  0;
  OfficesResults = 0;
  
  var DefaultTableHeader = "<table class=\"standard\" cellspacing=\"0\">" 
                + "<tr>"
                  + "<th>Navn</th>"
                  + "<th>Type</th>"
                + "</tr>";
  var RegionsHTML  = DefaultTableHeader;
  var DepartmentsHTML  = DefaultTableHeader;
  var OfficesHTML  = DefaultTableHeader;
  
  var OldDepartmentsHTML;
  var OldDepartmentsHTML = "<table class=\"standard\" cellspacing=\"0\">" 
                + "<tr>"
                  + "<th>Navn</th>"
                  + "<th>Tidligere afdelinger</th>"
                + "</tr>";

  var resultGrid = document.getElementById('resultgrid');  
  var resultMessageDiv = document.getElementById('resultMessage');
  
  query = document.getElementById('searchBox').value;
  
  for (i=0; i< RegionsArr.length; i++) {
    if(query.length > 0){
      if (RegionsArr[i].SearchStr.toLowerCase().substr(0, query.length) == query.toLowerCase() || RegionsArr[i].SearchStr.toLowerCase().indexOf(query.toLowerCase()) > -1) {
        RegionsHTML += "<tr class=\"#LINECLASS#\"><td valign=\"top\" class=\"aleft\" style=\"width:270px\"><a href=\"#LINK#\">#NAME#</a>#ADDRESS#</td><td class=\"aleft\" style=\"width:265px\">Regionskontor</td></tr>".replace("#LINK", RegionsArr[i].Url).replace("#NAME#", RegionsArr[i].Name).replace("#ADDRESS#", RegionsArr[i].Address).replace("#LINECLASS#", (i % 2 == 1 ? "odd" : "even")) ;
        RegionsResults += 1;
      }
    }
  }  
  RegionsHTML += "</table>";
  //Lokalkontor  
  for (i=0; i< DepartmentsArr.length; i++) {
    if(query.length > 0){
      if (DepartmentsArr[i].SearchStr.toLowerCase().substr(0, query.length) == query.toLowerCase() || DepartmentsArr[i].SearchStr.toLowerCase().indexOf(query.toLowerCase()) > -1) {
        DepartmentsHTML += "<tr class=\"#LINECLASS#\"><td valign=\"top\" class=\"aleft\" style=\"width:270px\"><a href=\"#LINK#\">#NAME#</a>#ADDRESS#</td><td class=\"aleft\" style=\"width:265px\">Afdelingskontor</td></tr>".replace("#LINK", DepartmentsArr[i].Url).replace("#NAME#", DepartmentsArr[i].Name).replace("#ADDRESS#", DepartmentsArr[i].Address).replace("#LINECLASS#", (DepartmentsResults % 2 == 1 ? "odd" : "even")) ;;
        DepartmentsResults += 1;
      }
    }
  }  
  DepartmentsHTML += "</table>";
	
	//Tidligere afdelinger
  for (i=0; i< OldDepartmentsArr.length; i++) {
    if(query.length > 0){
      if (OldDepartmentsArr[i].SearchStr.toLowerCase().substr(0, query.length) == query.toLowerCase() || OldDepartmentsArr[i].SearchStr.toLowerCase().indexOf(query.toLowerCase()) > -1) {
        OldDepartmentsHTML += "<tr class=\"#LINECLASS#\"><td valign=\"top\" class=\"aleft\" style=\"width:270px\"><a href=\"#LINK#\">#NAME#</a>#ADDRESS#</td><td class=\"aleft\" style=\"width:265px\">#OLDNAME#</td></tr>".replace("#LINK", OldDepartmentsArr[i].Url).replace("#NAME#", OldDepartmentsArr[i].Name).replace("#ADDRESS#", OldDepartmentsArr[i].Address).replace("#LINECLASS#", (OldDepartmentsResults % 2 == 1 ? "odd" : "even")).replace("#OLDNAME#", OldDepartmentsArr[i].SearchStr.replace(/,/g, ",</br>") ) ;;
        OldDepartmentsResults += 1;
      }
    }
  }
  OldDepartmentsHTML += "</table>";

  //Servicekontor
  for (i=0; i< OfficesArr.length; i++) {
    if(query.length > 0){
      if (OfficesArr[i].SearchStr.toLowerCase().substr(0, query.length) == query.toLowerCase() || OfficesArr[i].SearchStr.toLowerCase().indexOf(query.toLowerCase()) > -1) {
        OfficesHTML += "<tr class=\"#LINECLASS#\"><td valign=\"top\" class=\"aleft\" style=\"width:270px\"><a href=\"#LINK#\">#NAME#</a>#ADDRESS#</td><td class=\"aleft\" style=\"width:265px\">Service- eller satellitkontor</td></tr>".replace("#LINK", OfficesArr[i].Url).replace("#NAME#", OfficesArr[i].Name).replace("#ADDRESS#", OfficesArr[i].Address).replace("#LINECLASS#", (OfficesResults % 2 == 1 ? "odd" : "even")) ;;
        OfficesResults += 1;
      }
    }
  }      
  OfficesHTML += "</table>";
  
                
  if (resultMessageDiv != null)
		resultMessageDiv.style.display = (RegionsResults == 0 && DepartmentsResults == 0 && OldDepartmentsResults == 0 && OfficesResults == 0 ? 'block' : 'none');
  resultGrid.style.display = (RegionsResults == 0 && DepartmentsResults == 0 && OldDepartmentsResults == 0 && OfficesResults == 0 ? 'none' : 'block');

  resultGrid.innerHTML = "";  
  resultGrid.innerHTML += (DepartmentsResults == 0 ? '' : DepartmentsHTML);
  resultGrid.innerHTML += (OldDepartmentsResults == 0 ? '' : OldDepartmentsHTML);
  resultGrid.innerHTML += (OfficesResults == 0 ? '' : OfficesHTML);
  resultGrid.innerHTML += (RegionsResults == 0 ? '' : RegionsHTML);
}

function Department(ID, Name, Address, Url, SearchStr) {
  this.ID    = ID
  this.Name  = Name
  this.Address  = Address
  this.Url  = Url
  this.SearchStr  = SearchStr
}


/////////////////////////////////////////////////
//  Web edit related
/////////////////////////////////////////////////
// Opens the Sitecore content window for editing of a item
function BeginEdit(sItemID) 
{
  var contentdot_win = null;
  var width = Math.min(820, screen.availWidth);
  var height = Math.min(550, screen.availHeight);
  
  var left = Math.floor((screen.availWidth-width)/2);
  var top = Math.floor((screen.availHeight-height)/2);

  contentdot_win = window.open("/sitecore/client/editors/content.aspx?path=" + sItemID, "contentdot_editor", "width=" + width + ",height=" + height + ",left=" + left + ",top=" + top + ",resizable=yes");
  contentdot_win.focus();

  // Make sure the command part of the QS is removed so that the refresh of the 
  // page caused by the Sitcore edit window, will not result in the edit window to pop up again
  // when the close button is pressed
  RemoveCommandFromQS();    
}


/////////////////////////////////////////////////
//  Document handling functions
/////////////////////////////////////////////////


// print selected documents
function printSelected()
{
	// printing only works in IE
	if(explorer()){
		this.printurl = (typeof(print_url) != "undefined" ? print_url : "/sitecore modules/util/printdocument/fff.PrintDocument.aspx");
		// if printurl exists and datagrid isn't zero
		if ((this.printurl) && (this.toolbar.datagrid != null)){
			// create post form
			this.printform = document.createElement('form');
			this.printform.id = "printform";
			this.printform.method = "post";
			this.printform.action = this.printurl;
			document.body.appendChild(this.printform);

			var legal_documents = 0;
			// find selected documents
			for(var i = 1; i < this.toolbar.datagrid.elements.length; i++){
				if ((this.toolbar.datagrid.elements[i].className.match(/selected/g)) &&
					  ((this.toolbar.datagrid.elements[i].getElementsByTagName("input")[0].style.visibility == 'visible') ||
					   (this.toolbar.datagrid.elements[i].getElementsByTagName("input")[0].style.visibility == ''))){

					var t = this.toolbar.datagrid.elements[i].getElementsByTagName("a").length;
					if (t > 0){				
						// Get Filename and url.
						// Always uses the last url found, since that is where document files are placed.
						var filename = this.toolbar.datagrid.elements[i].getElementsByTagName("a")[t-1].innerText;
						var url = this.toolbar.datagrid.elements[i].getElementsByTagName("a")[t-1].href;

						// The url field
						var inputfield = document.createElement('input');
						inputfield.name = "url" + ++legal_documents;
						inputfield.value = url;
						this.printform.appendChild(inputfield);
						// The filename field
						inputfield = document.createElement('input');
						inputfield.name = "filename" + legal_documents;
						inputfield.value = filename;
						this.printform.appendChild(inputfield);						
					}
				}
			}
			
			// submit form if selected documents can be printed
			if(legal_documents){
				popUp('','printwindow',false, (legal_documents*13 + 47));
				this.printform.target = 'printwindow';
				this.printform.submit();
			}
			// remove print form
			document.body.removeChild(this.printform);
		}
		else
		{
			window.print();
//			alert("Print komponenten er ikke defineret")
		}
	}else{
		Page.Message.setSubject('PRINTING');
		Page.Message.setHeader('Printning via Active-X');
		Page.Message.addBodyText('Direkte printning af dokumenter er desv\u00e6rre ikke underst\u00f8ttet af din browser endnu.');
		Page.Message.open('error');
	} 
}


// save selected documents
function saveSelected()
{
	// saving multiple documents only works in IE
	if(explorer()){
		this.saveurl = (typeof(save_url) != "undefined" ? save_url : "/sitecore modules/util/printdocument/fff.SaveDocument.aspx");
		// if saveurl exists
		if(this.saveurl){
			// create post form
			this.saveform = document.createElement('form');
			this.saveform.id = "saveform";
			this.saveform.method = "post";
			this.saveform.action = this.saveurl;
			document.body.appendChild(this.saveform);

			var legal_documents = 0;
			// find selected documents
			for (var i = 1; i < this.toolbar.datagrid.elements.length; i++){
				if ((this.toolbar.datagrid.elements[i].className.match(/selected/g)) &&
					  ((this.toolbar.datagrid.elements[i].getElementsByTagName("input")[0].style.visibility == 'visible') ||
					   (this.toolbar.datagrid.elements[i].getElementsByTagName("input")[0].style.visibility == ''))){

					var t = this.toolbar.datagrid.elements[i].getElementsByTagName("a").length;
					if (t > 0){
					// Always uses the last url found, since that is where document files are placed.
					var url = this.toolbar.datagrid.elements[i].getElementsByTagName("a")[t-1].href;
					// is selected file legal?
						var inputfield = document.createElement('input');
						inputfield.name = "url" + ++legal_documents;
						inputfield.value = url;
						this.saveform.appendChild(inputfield);
					}
				}
			}
			// submit form if selected documents can be saved
			if(legal_documents){
				popUp('','savewindow',false, (legal_documents*13 + 47));
				this.saveform.target = 'savewindow';
				this.saveform.submit();
			}
			// remove save form
			document.body.removeChild(this.saveform);
		}else{
			alert("Save komponenten er ikke defineret")
		}
	}else{
		Page.Message.setSubject('SAVING');
		Page.Message.setHeader('Saving via Active-X');
		Page.Message.addBodyText('Direkte gemning af dokumenter er desv\u00e6rre ikke underst\u00f8ttet af din browser endnu.');
		Page.Message.open('error');
	}
} 



// Iso Date input function
// Many standards all over the place use the W3C's subset of the ISO 8601 standard to specify a 
// date and time unambiguously. After a very brief search I couldn't find a simple JavaScript function 
// to parse a string in this form, so here's one I wrote for the job. It should be bullet-proof and 
// accept any correctly formatted date/time in the correct style.
// Example of use:
// var date = new Date();
// date.setISO8601("20050326T1951:34Z");
// Found a bug with the regex 
// If you specify a time with seconds (and without miliseconds), and a timezone offset, it screws up and gives the wrong time
// 1986-04-26T01:23:58.00+03:00 will work
// 1986-04-26T01:23:58+03:00 won't work
Date.prototype.setISO8601 = function (string) {
    var regexp = "([0-9]{4})(([0-9]{2})(([0-9]{2})" +
        "(T([0-9]{2})([0-9]{2})(([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));

    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    time = (Number(date) + (offset * 60 * 1000));
    this.setTime(Number(time));
}

// This function takes two arguments, both optional. The first describes the format the resulting 
// string should take, ie. how many components to include. This is an integer between 1 and 6, 
// with the meanings listed above in the comment block. The second argument is an optional timezone offset. If it is not specified the timezone is set to UTC using the Z character. It takes the form +HH:MM or -HH:MM.
Date.prototype.toISO8601String = function (format, offset) {
    /* accepted values for the format [1-6]:
     1 Year:
       YYYY (eg 1997)
     2 Year and month:
       YYYY-MM (eg 1997-07)
     3 Complete date:
       YYYY-MM-DD (eg 1997-07-16)
     4 Complete date plus hours and minutes:
       YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
     5 Complete date plus hours, minutes and seconds:
       YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
     6 Complete date plus hours, minutes, seconds and a decimal
       fraction of a second
       YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
    */
    if (!format) { var format = 6; }
    if (!offset) {
        var offset = 'Z';
        var date = this;
    } else {
        var d = offset.match(/([-+])([0-9]{2}):([0-9]{2})/);
        var offsetnum = (Number(d[2]) * 60) + Number(d[3]);
        offsetnum *= ((d[1] == '-') ? -1 : 1);
        var date = new Date(Number(Number(this) + (offsetnum * 60000)));
    }

    var zeropad = function (num) { return ((num < 10) ? '0' : '') + num; }

    var str = "";
    str += date.getUTCFullYear();
    if (format > 1) { str += "-" + zeropad(date.getUTCMonth() + 1); }
    if (format > 2) { str += "-" + zeropad(date.getUTCDate()); }
    if (format > 3) {
        str += "T" + zeropad(date.getUTCHours()) +
               ":" + zeropad(date.getUTCMinutes());
    }
    if (format > 5) {
        var secs = Number(date.getUTCSeconds() + "." +
                   ((date.getUTCMilliseconds() < 100) ? '0' : '') +
                   zeropad(date.getUTCMilliseconds()));
        str += ":" + zeropad(secs);
    } else if (format > 4) { str += ":" + zeropad(date.getUTCSeconds()); }

    if (format > 3) { str += offset; }
    return str;
}


var MONTH_NAMES=new Array('Januar','Februar','Marts','April','Maj','Juni','Juli','August','September','Oktober','November','December','Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec');
var DAY_NAMES=new Array('S&oslash;ndag','Mandag','Tirsdag','Onsdag','Tirsdag','Fredag','L&oslash;rdag','S&oslash;n','Man','Tir','Ons','Tor','Fre','L&oslash;r');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
		}
		if (value[token] != null) {
			result=result + value[token];
		}
		else {
			result=result + token;
		}
	}
	return result;
}

/////////////////////////////////////////////////
//  Document handling functions (Version 7.0)
/////////////////////////////////////////////////

function explorer70()
{
	return navigator.appName == 'Microsoft Internet Explorer';
}


// print selected documents (version 7.0)
function printSelected70()
{
	// printing only works in IE
	if(explorer70()){
		this.printurl = (typeof(print_url) != "undefined" ? print_url : "/sitecore modules/util/printdocument/fff.PrintDocument.aspx");
		
		// if printurl exists and datagrid isn't zero		
		var datagrid = document.getElementById("datagrid");		
		if ((this.printurl) && (datagrid != null)){				
			// create post form
			this.printform = document.createElement('form');
			this.printform.id = "printform";
			this.printform.method = "post";
			this.printform.action = this.printurl;
			document.body.appendChild(this.printform);

			var legal_documents = 0;
			// find selected documents
			for(var i = 0; i < datagrid.getSelected().length; i++){
				var row = datagrid.getSelected()[i];
				
				// Get Filename and url.
				var filename = datagrid.getRowTitle(row);				
				var url = datagrid.getRowValue(row);								
								
				// The url field
				var inputfield = document.createElement('input');
				inputfield.name = "url" + ++legal_documents;
				inputfield.value = url;
				inputfield.style.display = 'none';
				this.printform.appendChild(inputfield);
				// The filename field
				inputfield = document.createElement('input');
				inputfield.name = "filename" + legal_documents;
				inputfield.value = filename;
				inputfield.style.display = 'none';
				this.printform.appendChild(inputfield);						
			}
			
			// submit form if selected documents can be printed
			if(legal_documents){
				Page.Util.popUp('','printwindow',false, (legal_documents*13 + 115), null);
				this.printform.target = 'printwindow';
				this.printform.submit();								
			}
			// remove print form
			document.body.removeChild(this.printform);
		}
		else
		{
			window.print();
		}
	}else{
		Page.Message.setSubject('PRINTING');
		Page.Message.setHeader('Printning via Active-X');
		Page.Message.addBodyText('Direkte printning af dokumenter er desv\u00e6rre ikke underst\u00f8ttet af din browser endnu.');
		Page.Message.open('error');
	} 
}

// save selected documents (version 7.0)
function saveSelected70()
{
	// saving multiple documents only works in IE
	if(explorer70()){
		this.saveurl = (typeof(save_url) != "undefined" ? save_url : "/sitecore modules/util/printdocument/fff.SaveDocument.aspx");
		// if saveurl exists
		if(this.saveurl && (datagrid != null)){
			// create post form
			this.saveform = document.createElement('form');
			this.saveform.id = "saveform";
			this.saveform.method = "post";
			this.saveform.action = this.saveurl;
			document.body.appendChild(this.saveform);

			var legal_documents = 0;
			// find selected documents
			for(var i = 0; i < datagrid.getSelected().length; i++){
				var row = datagrid.getSelected()[i];
				
				// Get Filename and url.
				var filename = datagrid.getRowTitle(row);
				var url = datagrid.getRowValue(row);

				// The url field
				var inputfield = document.createElement('input');
				inputfield.name = "url" + ++legal_documents;
				inputfield.value = url;
				//inputfield.style.display = 'none';
				this.saveform.appendChild(inputfield);
				// The filename field
				inputfield = document.createElement('input');
				inputfield.name = "filename" + legal_documents;
				inputfield.value = filename;
				//inputfield.style.display = 'none';
				this.saveform.appendChild(inputfield);						
			}
			
			// submit form if selected documents can be saved
			if(legal_documents){
				Page.Util.popUp('','savewindow',false, (legal_documents*13 + 115), null);
				this.saveform.target = 'savewindow';
				this.saveform.submit();
			}
			// remove save form
			document.body.removeChild(this.saveform);
		}else{
			alert("Save komponenten er ikke defineret")
		}
	}else{
		Page.Message.setSubject('SAVING');
		Page.Message.setHeader('Saving via Active-X');
		Page.Message.addBodyText('Direkte gemning af dokumenter er desv\u00e6rre ikke underst\u00f8ttet af din browser endnu.');
		Page.Message.open('error');
	}
} 

/////////////////////////////////////////////////
//  URL manupulation functions
/////////////////////////////////////////////////

//Function to return a value of a querystring if exists
//Pass the window.location.href into href input parameter.
function GetQueryStringValue(href, queryStringIdentifier)
{
  var queryStringValue = '';
	if(href.indexOf(queryStringIdentifier) > 0)
	{
		  //Ex. if href = http://localhost/slagelse/Ledighedstal.aspx?Querystring1=3&GoogleMapMaxCount=1&Querystring2=5
			var sub1 = href.substring(0, href.indexOf(queryStringIdentifier) - 1); // We get: http://localhost/slagelse/Ledighedstal.aspx?Querystring1=3
			var sub2 = href.substring(href.indexOf(queryStringIdentifier));//We get: GoogleMapMaxCount=1&Querystring2=5
			var sub3 = '';
			
			if(sub2.indexOf('&') > 0) //If we have some querystring behind the 'GoogleMapMaxCount', then we need to remove it
			{
				sub3 = sub2.substring(sub2.indexOf('&') + 1, sub2.length);
				sub2 = sub2.substring(0, sub2.indexOf('&'));//Now we should have: GoogleMapMaxCount=1
			}
			
			if(sub2.indexOf('=') > 0 && sub2.length >= sub2.indexOf('=')+2)
			{
				queryStringValue = sub2.substring(sub2.indexOf('=') + 1, sub2.length);				
			}
	}
	
	return queryStringValue;

}

//Function to remove at specific querystring identifier from an url
//Pass the window.location.href into href input parameter.
function RemoveQueryStringIdentifierFromUrl(href, queryStringIdentifier)
{
	var newUrl = href;
	if(href.indexOf(queryStringIdentifier) > 0)
	{
		  //Ex. if href = http://localhost/slagelse/Ledighedstal.aspx?Querystring1=3&GoogleMapMaxCount=1&Querystring2=5
			var sub1 = href.substring(0, href.indexOf(queryStringIdentifier) - 1); // We get: http://localhost/slagelse/Ledighedstal.aspx?Querystring1=3
			var sub2 = href.substring(href.indexOf(queryStringIdentifier));//We get: GoogleMapMaxCount=1&Querystring2=5
			var sub3 = '';
			var delemiter = '';
			
			if(sub2.indexOf('&') > 0) //If we have some querystring behind the 'GoogleMapMaxCount', then we need to remove it
			{
				sub3 = sub2.substring(sub2.indexOf('&') + 1, sub2.length);				
			}
				
			//The currentUrl without the queryStringIdentifier information
			if(sub1.indexOf('?') > 0)
			{
				newUrl = sub1 + '&' + sub3;
			}
			else
			{
				if(sub3.trim() != '')
				{
					newUrl = sub1 + '?' + sub3;
				}
				else
				{
					newUrl = sub1;
				}
			}
	}
	
	return newUrl;

}


