/*
	Lightbox JS: Fullsize Image Overlays by Lokesh Dhakar - http://www.huddletogether.com
	For more information on this script, visit: http://huddletogether.com/projects/lightbox/

	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
	Modified by Terje Enge to contain web code.
	Related files:
	* lightbox.css
	* ajax_sendmail.asp/php
	* ajax.js
	* livredd_refer.css
	* poster.htm (root) for preview
	* loading_31x31.gif (root)
*/
var loadingImage = 'loading_31x31.gif';		
// cmp. showLightbox!
var txtIntro_us = "Thank you for sharing<br><span style=\"font-weight:bold;letter-spacing:0.1em;\">another<span style=\"color:#f00\">IMAGE</span></span> with a friend !<br>&nbsp;<br><span style=\"font-size:0.9em;\">You may preview your message.<br>You may cc yourself.</span>";
var txtIntro_nor = "Her kan du enkelt spørre<br><span style=\"font-weight:bold;letter-spacing:0.1em;\">HOMEBASE</span> om hva som helst.<br>&nbsp;<br><span style=\"font-size:0.9em;\"><br>Du kan sende en kopi til deg selv.</span>";
var txtNotes_us = "(Your question here)";
var txtNotes_nor = "(ditt spørsmål her)";

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;
}

function getPageScroll(){
// Returns array with x,y page scroll values. Core code from - quirksmode.org
	var yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}
	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}
function getPageSize(){
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org. Edit for Firefox by pHaez	
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
function pause(numberMillis) {
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}
function getKey(evt){
	var keyCode;
	if (window.event) {
		keyCode = window.event.keyCode;
	} else if (evt) {
		keyCode = evt.keyCode;
	}
	//if (keyCode == 13) alert("getKey - ENTER");
	if (keyCode == 27) { hideLightbox(); return; }	//escape
}
function listenKey () {	
	document.onkeyup = getKey;
}
function showLoadingImage () {
	document.getElementById('loadingImage').style.display = 'block';
}
function hideLoadingImage () {
	document.getElementById('loadingImage').style.display = 'none';
}
function showResult (result) {
	document.getElementById('contain').style.display = "none";	
	document.getElementById('result').style.display = "block";	
//	if (result != "OK") {
//		document.getElementById('result').innerHTML = result
//	}
	//document.getElementById('lightbox').style.backgroundcolor = "transparent";
}

function showLightbox() {
		
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objLoadingImage = document.getElementById('loadingImage');

	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	if (objLoadingImage) {	// center loadingImage if it exists
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}
	// set height of Overlay to take up whole page and show
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';

	// center lightbox and make sure that the top and left values are not negative and the image placed outside the viewport
	var lightboxTop =  ((arrayPageSize[3] - 20 - 580) / 2) - arrayPageScroll[1];
	var lightboxLeft = ((arrayPageSize[0] - 20 - 360) / 2);
	
	objLightbox.style.top = (lightboxTop < 30) ? "30px" : lightboxTop + "px";
	objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
	// A small pause between the image loading and displaying is required with IE, this prevents the previous image displaying for a short burst causing flicker.
	if (navigator.appVersion.indexOf("MSIE")!=-1){
		pause(250);
	} 

	if (objLoadingImage) {	objLoadingImage.style.display = 'none'; }
	selects = document.getElementsByTagName("select");	// Hide select boxes as they will 'peek' through the image in IE
	for (i = 0; i != selects.length; i++) {
			selects[i].style.visibility = "hidden";
	}
	objLightbox.style.display = 'block';
	// After image is loaded, update the overlay height as the new image might have increased the overall page height.
	arrayPageSize = getPageSize();
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	
	listenKey();	// Check for 'esc' keypress
	document.getElementById('errmsg').innerHTML = "&nbsp;";
	//if (!gReferPhoto) resetForm();
	document.getElementsByTagName("input").item(0).focus();
}
function hideLightbox() {
	// get objects
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');
	// hide lightbox and overlay
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';
	document.getElementById('contain').style.display = "block";	
	document.getElementById('result').style.display = "none";	
	//document.getElementById('lightbox').style.backgroundcolor = "#444";
	selects = document.getElementsByTagName("select");	// make select boxes visible
    for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
	document.onkeypress = '';		// disable keypress listener
}
function initLightbox() {
	// this code inserts html at the top of the page that looks like this:
	// <div id="overlay">
	//		<a href="#" onclick="hideLightbox(); return false;"><img id="loadingImage" /></a>
	//	</div>
	// <div id="lightbox">
	// </div>
	
	var objBody = document.getElementsByTagName("body").item(0);
	var objOverlay = document.createElement("div");	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {hideLightbox(); return false;}
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
 	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var imgPreloader = new Image();	// preload and create loader image
	
	imgPreloader.onload=function(){	// if loader image found, create link to hide lightbox and create loadingimage

		var objLoadingImageLink = document.createElement("a");
		objLoadingImageLink.setAttribute('href','#');
		objLoadingImageLink.onclick = function () {hideLightbox(); return false;}
		objOverlay.appendChild(objLoadingImageLink);
		
		var objLoadingImage = document.createElement("img");
		objLoadingImage.src = loadingImage;
		objLoadingImage.setAttribute('id','loadingImage');
		objLoadingImage.style.position = 'absolute';
		objLoadingImage.style.zIndex = '150';
		objLoadingImageLink.appendChild(objLoadingImage);

		imgPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs

		return false;
	}

	imgPreloader.src = loadingImage;

	var objLightbox = document.createElement("div");	// create lightbox div, same note about styles as above
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';	
	// CMP anotherimage.js - switchLanguage !
	var sRefer = "<div id=\"result\">TAKK!<br>&nbsp;<br>SPØRSMÅL<br>SENDT!</div>"
	sRefer += "<div id=\"contain\">"
	sRefer += "<div id=\"containhead\"><div id=\"picthumb\"><img src=\"images/headerlogo_128x128.jpg\" width=\"128\" height=\"128\" alt=\"HOMEBASE\"></div>"
	sRefer += "<div id=\"taf_1\" >" + txtIntro_nor + "</div></div>"


	sRefer += "<div id=\"errmsg\">&nbsp;</div>"
	// action and onsubmit necessary due to to Safari. Check test on enter in textarea in submitSendMail
	sRefer += "<form action=\"ajax_sendquestion.asp\" method=\"post\" name=\"frmSendMail\" id=\"frmSendMail\" onkeydown=\"submitSendMail(event)\" onsubmit=\"ValidateSendMail(document.frmSendMail, document.getElementById('FROM_NAME'), document.getElementById('FROM_EMAIL'), 'errmsg', 'send');return false;\">"		// Skip enter - will trigger in textarea!
	sRefer += "<table style=\"margin:0;padding:0;\" width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\">"
	sRefer += "<tr><td align=\"left\" valign=\"top\" nowrap><p id=\"taf_2\">ditt navn:</p></td><td align=\"right\"><input type=\"text\" name=\"FROM_NAME\" id=\"FROM_NAME\" size=\"30\" border=\"0\" style=\"font-size:1em;\"></td></tr>"
	sRefer += "<tr><td align=\"left\" valign=\"top\" nowrap><p id=\"taf_3\">din epost:</p></td><td align=\"right\"><input type=\"text\" name=\"FROM_EMAIL\" id=\"FROM_EMAIL\" size=\"30\" border=\"0\" style=\"font-size:1em;\"></td></tr>"
	
	sRefer += "<tr><td colspan=\"2\">&nbsp;</td></tr>"
	sRefer += "<tr><td align=\"left\" valign=\"top\" nowrap><p id=\"taf_6\">ditt spørsmål:<br>(max. 400 tegn)</p><p id=\"taf_8\" style=\"margin-top:100px;\">#tegn = <span id=\"numchars\"></span></p></td><td align=\"right\"><textarea name=\"NOTES\" id=\"NOTES\" rows=\"6\" cols=\"28\" wrap=\"hard\" style=\"height:160px;font-size:1em;\" onkeyup=\"charCounter(this, 400)\">" + txtNotes_nor + "</textarea></td></tr>"
	sRefer += "<tr><td></td><td align=\"right\"><table style=\"margin:0;padding:0;\" width=\"205px\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td align=\"left\"><span id=\"taf_7\">send en kopi til deg selv:</span></td><td align=\"right\"><input type=\"checkbox\" checked class=\"check\" name=\"CC\" id=\"CC\" value=\"ON\"></td></tr></table></td></tr>"
	sRefer += "<tr><td colspan=\"2\">&nbsp;<input type=\"hidden\" name=\"langabb\" id=\"langabb\">"

	sRefer += "<input type=\"hidden\" name=\"task\" id=\"task\" value=\"send\">"
	sRefer += "</td></tr>"
	sRefer += "<tr><td align=\"right\" colspan=\"2\">"
	sRefer += "<input id=\"taf_submit\" class=\"btn\" style=\"width:120px;font-weight:bold;color:#f00;\" type=\"button\" name=\"cmdSubmit\" value=\"Send spørsmål\" onclick=\"return ValidateSendMail(document.frmSendMail, document.getElementById('FROM_NAME'), document.getElementById('FROM_EMAIL'), 'errmsg', 'send');\">"
	//sRefer += "<input id=\"taf_preview\" class=\"btn\" style=\"width:95px;\" type=\"button\" name=\"cmdPreview\" value=\"Preview\" onclick=\"return ValidateSendMail(document.frmSendMail, document.getElementById('FROM_NAME'), document.getElementById('TO_EMAIL'), 'errmsg', 'preview');\">"
	sRefer += "<input id=\"taf_reset\" class=\"btn\" style=\"width:65px;\" type=\"button\" name=\"cmdReset\" value=\"Nullstill\" onclick=\"resetForm(this.form);\" >"
	sRefer += "<input id=\"taf_cancel\" class=\"btn\" style=\"width:65px;\" type=\"button\" name=\"cmdCancel\" value=\"Avbryt\" onclick=\"hideLightbox();\">"
	sRefer += "</td></tr><tr><td colspan=\"2\" align=\"center\"><p id=\"taf_privacy\" style=\"font-size:0.8em;margin-top:1em;color:#ccc;\">Ingen epost-adresse vil bli brukt til annet enn å besvare dette spørsmål</p></td></tr></table></form></div>"
	
	objLightbox.innerHTML = sRefer;
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);
	
	//charCounter(document.getElementById("NOTES", 400)); to anotherImage.js - setCommonReferStrings
	
	// THIS IS COPY FROM ANOTHERIMAGE.JS TO SET ONLY NORWEGIAN - TEMP! __________________________
	
	if (document.getElementById("lightbox") ) {	// cmp- strings in lightbox.js - showLightbox
		document.getElementById("langabb").value = "nor"		// "no" will conflict with aNOtherimage ..
		charCounter(document.getElementById("NOTES", 400));
	}
	gLangAbb = "nor";
	
	// END COPY !! ____________________________
}

function addLoadEvent(func) {	
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}
}
function resetForm(frm) {
	// Better to act on onreset.
	frm.reset();
	document.getElementById("NOTES").value = (gLangAbb == "us") ? txtNotes_us : txtNotes_nor;
	document.getElementById("errmsg").innerHTML = "";
}
function submitSendMail (evnt) {
	// Submit form by ENTER (form is not submitted through AJAX), test for shiftKey due to textarea
	// NB : Will interupt ENTER in TEXTAREA without testing for this!
	if (((!evnt.shiftKey && evnt.which && evnt.which == 13) || (!evnt.shiftKey && evnt.keyCode && evnt.keyCode == 13))) {
		var orgelem = (evnt.target) ? evnt.target : evnt.srcElement;
		if(orgelem.type != "textarea") document.frmSendMail.cmdSubmit.click();
		return false;
	} else {
		return true;
	}
}
function ValidateSendMail(form, fld1, fld2, msgid, task) {  
	var s1=trim(fld1.value);	// my name	
	var s2=trim(fld2.value);	// my email
	if (isNotEmpty(fld1, msgid)) { 
		if (isNotEmpty(fld2, msgid)) { 
			if (isEMailAddr(fld2, msgid)) {
				document.forms["frmSendMail"].elements["task"].value = task;
				requestSendMail_1(form, task);
	    	}
		} 
  	}
	return false
}
function sendRefFromPreview () {
	//alert("sendRefFromPreview");
	document.frmSendMail.task.value = "send";
	document.frmSendMail.cmdSubmit.click()
//	document.forms["frmSendMail"].elements["task"].value = "send";
//	requestSendRefer_1(document.forms["frmSendMail"], "send");
}
// validates that the field value string has one or more characters in it and does not match any preset string
function isNotEmpty(elem, msgid) {
	var str = elem.value;
    var re = /.+/;
    if(!str.match(re)) {
        //setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "', 'Please fill in required field.', '" + msgid + "')", 0);
		setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "', 'Vennligst skriv inn nødvendig informasjon.', '" + msgid + "')", 0);
        return false;
    } else {
        return true;
    }
}
// validates that the entry is formatted as an e-mail address
function isEMailAddr(elem, msgid) {
	var str = trim(elem.value);
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!str.match(re)) {
        //setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "', 'Please specify a valid email address', '" + msgid + "')", 0);
		setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "', 'Vennligst spesifiser en gyldig epost adresse', '" + msgid + "')", 0);
        return false;
    } else {
        return true;
    }
}
function focusElement(formName, elemName, msg, msgid) {
    var elem = document.forms[formName].elements[elemName];
	var msgelem = document.getElementById(msgid);
    elem.focus();
    elem.select();
	msgelem.innerHTML = msg;
}
function showPreview (sBody) {
	var winPrev = window.open("poster.htm","preview","width=780, height=700, top=10, left=10, toolbar=no,resizable=yes,status=no,scrollbars=yes,menubar=no");
	//setTimeout("winPrev.document.write('" + sBody + "')", 100);	// ERROR MSG !!
	winPrev.document.write(sBody);
	winPrev.document.close();	// to stop loading ...
	if (winPrev.focus) { winPrev.focus(); }
}
function charCounter(field, maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);	// if too long...trim it!
		document.getElementById("taf_8").style.color = "#f00"; // warn
	} else {
		document.getElementById("taf_8").style.color = "#fff"
	}
	document.getElementById("numchars").innerHTML = field.value.length;
}