/* Custom part for virk.dk - utility functions and site specifik functions and 'class' 
   $Date: 2008-08-27 13:41:53 +0200 (on, 27 aug 2008) $ - $Revision: 1299 $ 
*/

/* simple extension to string that trims for whitespaces */
String.prototype.trim = function() { 
  return this.replace(/^\s+|\s+$/g, ''); 
}

/* if not present (IE browser) add Array funtion to delete specific entry */
if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
    for(var i=0; i<this.length; i++){
      if(this[i]==obj) {
        return i;
      }
	}
	return -1;
  }
}
	

/* Function to select element by css-class name
   Written by Jonathan Snook, http://www.snook.ca/jonathan 
   Add-ons by Robert Nyman, http://www.robertnyman.com
*/
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

/* Function that returns an array with parameter values for the requested 'parameterName', 
   if there isn't any a empty array is returned 
   The encoding for values are handlede with decodeURIComponent like "convert all other 
   characters to bytes according to UTF-8, and then percent-encode those values" 
   (http://en.wikipedia.org/wiki/Percent-encoding)
   Needed since the navigational search uses certain parameters multiple times
   */
function virk_getParameterArray(parameterName) {
  // removing the '?'
  var queryString =window.location.search.substring(1);
  queryString = queryString.replace(/\+/g, '%20');
  var resultArray = new Array();

  if (queryString.length==0) { 
    return resultArray; 
  }
  
  var querySnipArray = new Array();
  querySnipArray = queryString.split('&');

  for(var i = 0; i < querySnipArray.length; i++) {   
    var entry = querySnipArray[i].split('=');
    if(entry[0]==parameterName) {
      resultArray[resultArray.length] = decodeURIComponent(entry[1]);
    }   
  }
  return resultArray;
}

/* Function that returns the first value for the given 'parameterName' if multiple present, 
   crafted for use with the navigational search on virk.dk */
function virk_getFirstParameter(parameterName) {
  var valueArray = virk_getParameterArray(parameterName);
  if( valueArray.length == 0) {
    return null;
  } else {
    return valueArray[0];
  }
}

/* Function that returns the first value for the given 'parameterName' if multiple present, 
   crafted for use with the navigational search on virk.dk */
function virk_getLastParameter(parameterName) {
  var valueArray = virk_getParameterArray(parameterName);
  var clearNavigation = virk_getFirstParameter("cl");
  if( valueArray.length == 0) {
    return "";
  } else if (parameterName==clearNavigation) {
    return valueArray[valueArray.length-2];
  } else {
    return valueArray[valueArray.length-1];
  }
}

/* Function that returns true if querystring is empty */
function isQueryStringEmpty() {
  if(window.location.search=="?" || window.location.search=="") {
    return true;
  } else {
    return false;
  }
}

/* Function that returns if the resource was retrieved over an encrypted connection, 
   that's HTTP og SSL/TLS aka. 'https' */
function isEncryptet() {
   if (window.location.protocol == "https:") {
     return "Encryptet (https)";
   } else {
     return "Plain (http)";
   }
}
  
  
/* Function that returns the CVRnumberIdentifier for the logged in user, based on
   page content 
   * Notice! citizen certificates and users that work for other companies should not give an error
   */
function scrapeCvrNumberIdentifier() {
  var docText = document.body.innerHTML; 
  var result = null;
  try {
     cvrMatch = docText.match(/(CVR\:\&nbsp;)\d{2}\s\d{2}\s\d{2}\s\d{2}/g)[0];
     result = cvrMatch.substring(10).replace(/\s/g,'');
   } finally {
      return result;
   }
}


/* Function that returns true if the user has just passed login 
   todo: check for change current company */
function hasJustLoggedIn() {
//if( document.referrer.indexOf("https://wwwpre.virk.dk/VirkLoginSucces")==0) {
//if( document.referrer.indexOf("https://www.virk.dk/VirkLoginSucces")==0) {
  if( document.referrer.indexOf("/VirkLoginSucces")!=-1) {
    document.write("<!-- new login -->");
    return true
  } else {
    return false;
  }
}

/* Function that returns the title of the portal service, based on page content */
function scrapeTitle() {
  var docText = document.getElementById('title').innerHTML;
  return cvrMatch = docText.match(/(.)+/g)[0];
}


/* Function that returns the tyfpe of the portal service, based on page content. The
   possible values are Digital, PDF, EXCEL, DOC */
function scrapeServiceType() {
  var docText = document.getElementById("startFormular").innerHTML;
  //var fullRegu=/<span class="dots">&nbsp;<\/span>\s+<span>((.)+)<\/span>/g;
  //var arr2 = fullRegu.exec(docText);

  //document.write("<p>FUNC arr all :<b>" + arr2 + "</b></p>");
  //document.write("<p>FUNC arr one :<pre>" + arr2[1] + "</pre></p>");
  //var compareString =arr2[1];
  var compareString =docText;
   
  if(compareString.indexOf("PDF")>0) {
    //alert("hit");
    return "PDF";
  } else if (compareString.indexOf("Excel")>0){ 
    return "XLS";
    } else if (compareString.indexOf("Word")>0){ 
    return "DOC";
    } else if (compareString.indexOf("indberetning")>0){ 
    return "DIGITAL";
  } else {
    //alert("Fallback "+arr2[1]);
    return "text: " + compareString;
  }  
}

// 'http://wwwpre.virk.dk/myndigheder/' == 35
// 'http://www.virk.dk/myndigheder/' == 32
// ups how about http vs. https
// "/myndigheder/" 14
// "/kommuner/" 11
// http://wwwpre.virk.dk/myndigheder/SKAT/Slette_momsangivelser
//
function scrapeAuthority() {
  var firstPathElementEnd = window.location.pathname.indexOf('/',2)+1;
  var authAndForm = window.location.pathname.substring(firstPathElementEnd);
  //var action = document.forms[2].action;
 // document.write("<p>pathname: " + window.location.pathname + " " + firstPathElementEnd +"</p>");
  //var mynSlash = action.indexOf("/",35); // first after '/myndighed/'
  var mynSlash = authAndForm.indexOf("/"); // first after '/myndighed/'
  
  //document.write("<p>Action: " + action.substring(34,mynSlash) + "</p>");
  return authAndForm.substring(0,mynSlash).toUpperCase();
}


function getPortalServiceString() {
  return  "[" + scrapeAuthority() + "] [" + scrapeServiceType() + "] " + scrapeTitle();
  //return scrapeTitle();
}

/* Function to fire from the start buttons on the IntroPage to get information about
   initiated Portal Services */
function onPortalServiceStart(obj) {
  //alert("Sending event");
  var s_account="virkdev";
  var s=s_gi(s_account)

  s.linkTrackVars="events,prop10,prop11,prop12,prop13";
  s.linkTrackEvents="prodView,event1";
  var psText = getPortalServiceString();
  s.prop10=psText; // fulltext
  s.prop11=scrapeAuthority();
  s.prop12=scrapeServiceType();
  s.prop13=scrapeTitle();
  s.products=";"+psText;
  s.events="prodView,event1";
  //s.t(); 
  s.tl(obj,'o',psText);
  return true;
}


/* 
Forms[0]: <form action="/soeg" method="get" name="soeg">
Forms[1]: <form id="loginform" action="https://wwwpre.virk.dk/VirkLoggedIn">
Forms[2]: <form action="/myndigheder/........
*/
function attachPortalServiceOnStartEvent() {
   var buttonNode = document.forms[2];

  if(buttonNode) {
  document.write("<!-- portal service: "+getPortalServiceString() + "-->");
    if (buttonNode.addEventListener) {
      buttonNode.addEventListener("submit",  function() { onPortalServiceStart(this); } , false);
    } else if (buttonNode.attachEvent) {
      buttonNode.attachEvent("onsubmit", function(){onPortalServiceStart(this);});
    } else {
      buttonNode.onSubmit=onPortalServiceStart(this);
    }
  } else {
    document.write("<!-- Bugger - can't find button node - maybe you need to login -->");
  }
}



/* Function that returns the search terms based on the querystring */
function virk_getSearchTerms() {

  /* set search terms - build string for sitecatalyst */
  var searchTerms = "";
  
  /* q - free text search, all types - started from the orange searchbox 
     example:  q=keyword+liste
  */
  var query = virk_getFirstParameter('q');
  if (query) searchTerms += "q:"+ query;
  
  /* t - "information" or "indberetning" only search on the type */
  var type = virk_getFirstParameter('t');
  if (type) searchTerms += " t:" +type;
  
  /* a - authority (double encoding)
     example from general search: a=%5E%22Danmarks+Statistik%22%24 - that decodes to a=^"Danmarks Statistik"$
     example from forms search: a=%5ESKAT%24 - a=^SKAT$
  */
  var authority = virk_getFirstParameter('a');
  //if (authority) searchTerms += " a:" + decodeURIComponent(escape(authority.substring(1,authority.length-1)));
  if (authority) searchTerms += " a:" + authority.substring(1,authority.length-1);

  /* m - municipality 
     example: m=Aller%C3%B8d or m=Holb%C3%A6k
     %B8 - &cedil;
     %C3 - &Atilde;
     %A6 - &brvbar;
  */
  var municipality = s.getQueryParam('m');
  if (municipality) searchTerms += " m:" + decodeURIComponent(escape(municipality));
  
  /* c - category 
     example: c=%5E%22Landbrug%2C+Skovbrug+%26+Fiskeri%22 - c=^"Landbrug, Skovbrug & Fiskeri"
     */
  var category = virk_getLastParameter('c');
  //if (category) searchTerms += " c:" + decodeURIComponent(escape(category.substring(1,category.length)));
  if (category) searchTerms += " c:" + category.substring(1,category.length);
  
  /* k - keyword 
     example: k=%5Elandbrug%24 - k=^landbrug$ */ 
  var keyword = virk_getLastParameter('k');
  //if (keyword) searchTerms += " k:" +decodeURIComponent(escape(keyword.substring(1,keyword.length-1)));
  if (keyword) searchTerms += " k:" + keyword.substring(1,keyword.length-1);
  
  /* page, the first page doesn't have this parameter */
  var page = s.getQueryParam('page');
  if(page) searchTerms += " page:" + page;
  // if this is an active search and the first page, the page parameter is not present so I add it
  if(searchTerms.length>0 && (!page)) searchTerms += " page:1";
  return searchTerms.trim();
}



  
/*  Class 'SectionDivider' that takes the pageName with ':' seperation */
function SectionDivider(pagename)
{
  /// initialize the member variables for this instance
  this.pagename = pagename;
  
  //this.pagename = "myndigheder:ITST:NemHandel_FakturaBlanket";
  // initialize the member function references 
  // for the class prototype
  if (typeof(_sectiondivider_prototype_called) == 'undefined')
  {
     _sectiondivider_prototype_called = true;
     SectionDivider.prototype.isSearch = isSearch;
     SectionDivider.prototype.getSearchTerms = getSearchTerms;
     SectionDivider.prototype.getSearchResults = getSearchResults;
     SectionDivider.prototype.getChannel = getChannel;
     SectionDivider.prototype.getProp1 = getProp1;
     SectionDivider.prototype.getProp2 = getProp2;
     SectionDivider.prototype.getProp3 = getProp3;
     SectionDivider.prototype.getProp4 = getProp4;
     SectionDivider.prototype.init = init;
     SectionDivider.prototype.getPageName = getPageName;
     SectionDivider.prototype.getDebugInfo = getDebugInfo;
     SectionDivider.prototype.isIntroPage = isIntroPage;
  }
  
  function init() {
  if (!pagename) return;
  
  /* Adding pagename and removing tailing 'q' on Firefox requests on html:form[@action=='GET'] */
  var pn = this.pagename.split('?',1)[0];
  pn = pn.replace(":pid:",":pid_");  
  this.public_pagename = pn;
  this.pagename = pn.toLowerCase();
    
  /* cut off the hostname/domain and set all to lower case */
  var fullprop = this.pagename.substring(8,this.pagename.length);//.toLowerCase(); 
  var propArray = fullprop.split(":"); /// split into string array
    
  // set channel, ex. 'myndigheder'
  this.channel = propArray[0]; 
  // Handle that the frontpage has the system name "/pid/1" but that in terms of channels and sections it should be empty
  if(propArray[0]=="pid_1")
    this.channel = "";

  /// set property one, ex. 'myndigheder:ITST'
  this.prop1 = "";
  if(propArray.length>1) {
    this.prop1 = this.channel + ":" + propArray[1] ;
  }

  /// set property two, ex. 'myndigheder:ITST:NemHandel_FakturaBlanket'
  this.prop2 = "";
  if(propArray.length>2) {
    this.prop2 = this.prop1 + ":" + propArray[2] ;
  }

  /// set property three, ex. 'myndigheder:ITST:NemHandel_FakturaBlanket:Anvend'
  this.prop3 = "";
  if(propArray.length>3) {
    this.prop3 = this.prop2 + ":" + propArray[3] ;
  }

  /// set property four but not used in current IA
  this.prop4 = "";
  if(propArray.length>4) {
    this.prop4 = this.prop3 + ":" + propArray[4] ;
  }

  this.searchTerms = null;
  if(this.isSearch()) {
    this.searchTerms = virk_getSearchTerms();
  }
  
  this.searchResults = null;
  if(this.isSearch()) {
    // <h1 class="title noline">Indberetninger<span class="slim"> (75 indberetninger)</span> </h1>
    var spanStr = getElementsByClassName(document, "span", "slim")[0].innerHTML;
    this.searchResults = spanStr.match(/\d+/g)[0];
  }
  
  }

  // define predicat for enabling search terms
  function isSearch() {
     return (this.channel) && (this.channel=="soeg" || this.channel=="indberetninger") && (this.prop1=="") && !isQueryStringEmpty();
  }

  function getSearchTerms () {
    return this.searchTerms;
  }
  
  function getSearchResults() {
    return this.searchResults;
  }
  
  function getPageName() {
     return this.public_pagename;
  }
  
  function getChannel() {
     return this.channel;
  }
  
  function getProp1() {
     return this.prop1;
  }
  
  function getProp2() {
     return this.prop2;
  }
  
  function getProp3() {
     return this.prop3;
  }
  
  function getProp4() {
     return this.prop4;
  }
  
  function getDebugInfo() {
    document.write("<!--");
    document.write("pageName: " + this.public_pagename + "\n");
    document.write("getChannel: " + this.channel + "\n");
    document.write("getProp1: " + this.prop1 + "\n");
    document.write("getProp2: " + this.prop2 + "\n");
    document.write("getProp3: " + this.prop3 + "\n");
    document.write("getProp4: " + this.prop4 + "\n");
   
    document.write("getSearchTerms: " + this.searchTerms + "\n");
    document.write("getSearchResults: " + this.searchResults + "\n");
    
    
    document.write("isEncryptet: " + isEncryptet() + " [" + window.location.protocol + "]\n");
 
    document.write("-->");
  }

  function isIntroPage() {
    if(  (this.channel == "myndigheder" || this.channel == "kommuner")  &&  this.prop2  &&  (!this.prop3)  ) {
      return true;
    } else {
      return false;
    }
  }  
}// End Class definition