// STRINGS
String.prototype.trim = function() {
	// skip leading and trailing whitespace and return everything in between  call: result = s.trim();
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
   return this.replace(/^\s+/g,"");
}
String.prototype.rtrim = function() {
   return this.replace(/\s+$/g,"");
}
function trim(value) {
	// trim leading and trailing spaces plus consecutive blanks within string
	var temp = value;
	var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
	if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
	var obj = /  /g;
	while (temp.match(obj)) { temp = temp.replace(obj, " "); }
	return temp;
}
String.prototype.htmlEntities = function () {
   //convert &, <, and > to their respective HTML escape codes
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};
String.prototype.stripTags = function () {
   // strip all HTML-tags
   return this.replace(/<([^>]+)>/g,'');
}
// ARRAYS
Array.prototype.sortNum = function() {
   // sort array numerically
   return this.sort( function (a,b) { return a-b; } );
}
Array.prototype.find = function(searchStr) {
  //returns an array of the indexes where the search term was found, otherwise false
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {	// change to == if '66' = 66
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}
Array.prototype.map = function(f) {
   	//var tmp = ['now', 'is', '   the   ', 'time    ', '    for ',  ' all', ' good ', '   men   '];
	//var test = tmp.map(trim);  // returns now,is,the,time,for,all,good,men
  var returnArray=[];
  for (i=0; i<this.length; i++) {
    returnArray.push(f(this[i]));
  }
  return returnArray;
}
// NUMBERS
function formatNumber(num,prefix){
   //var test2 = formatNumber(1234.15,'$');     // returns $1,234.15
   prefix = prefix || '';
   num += '';
   var splitStr = num.split('.');
   var splitLeft = splitStr[0];
   var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
   var regx = /(\d+)(\d{3})/;
   while (regx.test(splitLeft)) {
      splitLeft = splitLeft.replace(regx, '$1' + ',' + '$2');
   }
   return prefix + splitLeft + splitRight;
}
function unformatNumber(num) {
   return num.replace(/([^0-9\.\-])/g,'')*1;
}
function leadzero(s) {
	var result = (s < 10) ? "0"+s : s;
	return result;
}
function extension (filename) { 
	// get the file extension
	return filename.substr(filename.lastIndexOf(".") + 1, filename.length); 
}
function enterPressed(e) {
   // check whether enter key was pressed
   var intKey = (window.Event) ? e.which : e.keyCode;
   if (intKey == 13) {
       return true;
   }
   return false;
}
function ClipBoard(copy, hold) {
	// for debug
	if (document.all) {
		//hold.innerText = copy.innerText;
		hold.innerText = copy;
		var Copied = hold.createTextRange();
		Copied.execCommand("Copy");
		alert("Debug code copied to clipboard.")
	} else {
		var selRef = window.getSelection();
		var oRange = document.createRange();
		oRange.selectNode(copy);
		selRef.addRange(oRange);
		alert("Høyre-klikk på utvalgt tekst, velg kopier til Utklippstavle.\nLim innholdet i denne inn på ønsket sted.")
	}
}
// COOKIES:
function cookiesAllowed() {
   setCookie('checkCookie', 'test', 1);
   if (getCookie('checkCookie')) {
      deleteCookie('checkCookie');
      return true;
   }
   return false;
}

function setCookie(name,value,expires, options) {
   if (options===undefined) { options = {}; }
   if ( expires ) {
      var expires_date = new Date();
      expires_date.setDate(expires_date.getDate() + expires)
   }
   document.cookie = name+'='+escape( value ) +
      ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + 
      ( ( options.path ) ? ';path=' + options.path : '' ) +
      ( ( options.domain ) ? ';domain=' + options.domain : '' ) +
      ( ( options.secure ) ? ';secure' : '' );
}

function getCookie( name ) {
   var start = document.cookie.indexOf( name + "=" );
   var len = start + name.length + 1;
   if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
      return null;
   }
   if ( start == -1 ) return null;
   var end = document.cookie.indexOf( ';', len );
   if ( end == -1 ) end = document.cookie.length;
   return unescape( document.cookie.substring( len, end ) );
}

function textDate2CalendarDate (txtdate) {
	return txtdate.substr(6, 2) + "." + txtdate.substr(4, 2) + "." + txtdate.substr(0, 4)
}
function calendarDate2TextDate (dato) {
	return dato.substr(6, 4) + dato.substr(3, 2) + dato.substr(0, 2)
}

function newLoc(strURL) {
	location=pathOnly(location.href) + strURL;
	return true;
}
function pathOnly (InString)  {
	LastSlash=InString.lastIndexOf ('/', InString.length-1);
	OutString=InString.substring  (0, LastSlash+1);
	return (OutString);
}
function popWin06 (pictURL, pictTitle, w, h) {
//	Direct read of width, height nofunc with Mozilla
//	var picfile = new Image();
//  picfile.src =(pictURL);
//	w = picfile.width;
//	h = picfile.height;
//	var newHeight = (h + 20);
//	var namepos = h + "px";
//	var args= "height=" + newHeight + ",innerHeight=" + newHeight;
//    args += ",width=" + w + ",innerWidth=" + w;
//    if (window.screen) {
//        var avht = screen.availHeight;
//        var avwd = screen.availWidth;
//        var xcen = (avwd - w) / 2;
//        var ycen = (avht - newHeight) / 2;
//        args += ",left=" + xcen + ",screenX=" + xcen;
//        args += ",top=" + ycen + ",screenY=" + ycen + ",resizable=no,status=no";
//    }
//	winPop = window.open(pictURL,"newwin",args);
//	winPop.document.write('<html><head><title>' + pictTitle + '<\/title><\/head><body style =\"margin:0;padding:0;\" background="' + pictURL + '" onblur=\"this.focus();\" onclick=\"javascript:window.close();\"><div style =\"width:100%;height:20px;padding-top:3px;text-align:center;border-top:1px solid #000;font-size:12px;font-family:verdana,helvetica,sans-serif;font-weight:normal;background-color:#000;color:#ccc;position:absolute;top:' + namepos + '\">' + pictTitle + '<\/div><\/body><\/html>')
//	winPop.document.close();
//	winPop.resizeBy(w - winPop.document.body.clientWidth, newHeight - winPop.document.body.clientHeight)
//	if (winPop.focus) { winPop.focus(); }
	
	jQuery.slimbox(pictURL, pictTitle);
}
function showHideAnswer(evt) {
	// Public Web. Cross browser, cmp. Goodman ...
	evt = (evt) ? evt : ((event) ? event : null);
	var elem = (evt.target) ? evt.target : evt.srcElement;
	var child = document.getElementById(elem.getAttribute("child", false));
	var source = elem;
	if (null != child) child.className = (child.className == "QA-collapsed" ? "QA-expanded" : "QA-collapsed");
	if (null != elem && null != child) elem.className = (elem.className == "QA-expandable" ? "QA-shown" : "QA-expandable");
}
function showHideQA(evt) {
	// Toaster only. Cross browser, cmp. Goodman ...
	evt = (evt) ? evt : ((event) ? event : null);
	var elem = (evt.target) ? evt.target : evt.srcElement;
	var child = document.getElementById(elem.getAttribute("child", false));
	var source = elem;
	if (null != child) child.className = (child.className == "toasterQA-collapsed" ? "toasterQA-expanded" : "toasterQA-collapsed");
	if (null != elem && null != child) elem.className = (elem.className == "toasterQA-expandable" ? "toasterQA-shown" : "toasterQA-expandable");
}
function popWin(w, h, url) {
	var winPop;
	if (winPop) { winPop.Close; }
	if (h == -1) { h = screen.availHeight - 20 }
	//alert("popWin, url = " + url);
	winPop = window.open(url,"hpWindow","width=" + w + ",height=" + h + ",toolbar=no,resizable=yes,status=no,scrollbars=yes, menubar=no");
	if (winPop.focus) { winPop.focus(); }
}

function loadLanguage (langabb) {
	document.location.replace("default.asp" + "?labb=" + langabb);
}
function showMessage (msg, warn) {
	document.getElementById("message").className = (warn) ? "warn" : "msg";		// ERROR: Background not set! ?????
	if (warn) {
		document.getElementById("message").style.backgroundColor = "#e00";		// TMP
	} else {
		document.getElementById("message").style.backgroundColor = "transparent";
	}
	document.getElementById("message").innerHTML = msg;
}
// encrypt/decrypt email
function UnCryptMailto(s) {
	// cmp encryption in TOASTER: publish_upload.asp
	var r, i, ch
	r = ""
	for(i = 0;i < s.length/2;i++) {
		ch = "0X" + s.substr(i*2, 2)
		ch = ch^111
		r = r + String.fromCharCode(ch)
	}
	return r;
}
function linkTo_UnCryptMailto(s) {
	//location.href = "mailto:" + UnCryptMailto(s);
	location.href = UnCryptMailto(s);
}
// TOASTER LITE
function loginLite () {
	var login;
	var oParams = new Object();
	oParams.pubid = pubid;
    oParams.pub = pub;
	oParams.sub = sub;
	login = showModalDialog("toaster/login_lite.htm", oParams, "resizable:no; help:no; status:no; scroll:no;");
	if (login != null) {
		document.frmLogin.id_pw.value = login.id + "$" + login.pw + "$" + login.pub + "$" + login.sub + "$" + login.pubid + "$" + langabb
		//alert(login.id + "$" + login.pw + "$" + login.pub + "$" + login.sub + "$" + login.pubid + "$" + langabb);
		document.frmLogin.submit();
	}
}
function abandonSession () {
	window.location.href= "default.asp?labb=" + langabb + "&pub=" + pub + "&sub=" + sub + "&pubid=" + pubid + "&action=abandon"
}
// Social Media
function fbs_click() {
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&amp;t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}
function twtr_click() {
	u=location.href;
	t=document.title;
	window.open('http://twitter.com/home?status=Anbefales: '+encodeURIComponent(t)+' ' +encodeURIComponent(u),'sharer','toolbar=0,status=0,width=726,height=436');
	return false;
}
