var BrowserDetect={init:function(){this.browser=this.searchString(this.dataBrowser)||"Ukjent nettleser";this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"";this.OS=this.searchString(this.dataOS)||"ukjent operativsystem";},searchString:function(data){for(var i=0;i<data.length;i++){var dataString=data[i].string;var dataProp=data[i].prop;this.versionSearchString=data[i].versionSearch||data[i].identity;if(dataString){if(dataString.indexOf(data[i].subString)!=-1)
return data[i].identity;}
else if(dataProp)
return data[i].identity;}},searchVersion:function(dataString){var index=dataString.indexOf(this.versionSearchString);if(index==-1)return;return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},dataBrowser:[{string:navigator.userAgent,subString:"Chrome",identity:"Chrome"},{string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},{string:navigator.vendor,subString:"Apple",identity:"Safari",versionSearch:"Version"},{prop:window.opera,identity:"Opera"},{string:navigator.vendor,subString:"iCab",identity:"iCab"},{string:navigator.vendor,subString:"KDE",identity:"Konqueror"},{string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},{string:navigator.vendor,subString:"Camino",identity:"Camino"},{string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},{string:navigator.userAgent,subString:"MSIE",identity:"Internet&nbsp;Explorer",versionSearch:"MSIE"},{string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},{string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}],dataOS:[{string:navigator.platform,subString:"Win",identity:"Windows"},{string:navigator.platform,subString:"Mac",identity:"Mac"},{string:navigator.userAgent,subString:"iPhone",identity:"iPhone/iPod"},{string:navigator.platform,subString:"Linux",identity:"Linux"}]};var sendregning=(function($){var defaults={debug:true};if(!String.prototype.trim){String.prototype.trim=function(){return trim(this);};}
if($.fancybox){$.fancybox.defaults.openSpeed=500;$.fancybox.defaults.closeSpeed=500;}
function namespace(string){var object=this;var levels=string.split(".");for(var i=0,l=levels.length;i<l;i++){if(typeof object[levels[i]]=="undefined"){object[levels[i]]={};}
object=object[levels[i]];}
return object;}
function extend(target){var extensions=Array.prototype.slice.call(arguments,1);for(var i=0,l=extensions.length;i<l;++i){for(var prop in extensions[i]){target[prop]=extensions[i][prop];}}
return target;};function create(proto){var F=function(){};F.prototype=proto;return new F();}
function trim(str){if(!str){return"";}
str=str.replace(/^\s+/,'');for(var i=str.length-1;i>=0;i--){if(/\S/.test(str.charAt(i))){str=str.substring(0,i+1);break;}}
return str;}
function formatMonetaryAmount(amount){var numberAmount=Number(amount);numberAmount=numberAmount.toFixed(2);var strAmount=''+numberAmount;return strAmount.replace(/\./g,",");};var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=Base64._utf8_encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}
output=output+
this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+
this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4);}
return output;},decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2);}
if(enc4!=64){output=output+String.fromCharCode(chr3);}}
output=Base64._utf8_decode(output);return output;},_utf8_encode:function(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}
else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}
else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}
return utftext;},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++;}
else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode(((c&31)<<6)|(c2&63));i+=2;}
else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}
return string;}}
function displayVideos(){if(BrowserDetect){BrowserDetect.init();if(BrowserDetect.browser=='Opera'){return false;}}
if(typeof brightcove!="undefined"&&brightcove.createExperiences){brightcove.createExperiences();}
else{$.getScript('https://sadmin.brightcove.com/js/BrightcoveExperiences.js',function(){if(typeof brightcove!="undefined"&&brightcove.createExperiences){brightcove.createExperiences();}});}
$(".videoPopup").fancybox({openSpeed:400,closeSpeed:400,openOpacity:false,closeOpacity:false,openEffect:'elastic',closeEffect:'elastic'});return true;}
return{displayVideos:displayVideos,formatMonetaryAmount:formatMonetaryAmount,namespace:namespace,create:create,extend:extend,trim:trim,defaults:defaults,base64:Base64,addEventListener:function(el,event,handler){if(el.addEventListener){el.addEventListener(event,handler,false);}else if(el.attachEvent){el.attachEvent(event,function(){handler.call(el,window.event);});}else{el["on"+event]=function(){handler.call(el,window.event);};}}}})(jQuery);(function(){"use strict";var log=sendregning.namespace("log");var defaults=sendregning.defaults;log.debug=function debug(message){if(defaults.debug&&window.console&&window.console.log){if(typeof message==="object"){window.console.log(message);}
else{window.console.log(""+message+"\n");}}};log.js=function debug(message){if(jstestdriver){return jstestdriver.console.log(message);}};}());(function(sr){sr.namespace("formatter").parseNorwegianMonetaryAmount=parseNorwegianFloat;sr.namespace("formatter").string2NumberString=string2NumberString;sr.namespace("formatter").number2NorwegianMonetartyAmount=number2NorwegianMonetartyAmount;var debug=sr.debug;function parseNorwegianFloat(valueAsString){if(typeof valueAsString=="number"){return valueAsString;}
var convertedStr=string2NumberString(valueAsString);return new Number(convertedStr);}
function string2NumberString(s){s=s||"";s=s.replace(".","");s=s.replace(",",".");s=s.replace(/[^\d.]/g,'');return s;}
function number2NorwegianMonetartyAmount(value){return formatCurrency(value,""," ",",");}
function formatCurrency(theNumber,theCurrency,theThousands,theDecimals){var num=theNumber;if(isNaN(num)){num="0";}
sign=num<0?"-":""
num=Math.abs(num);num=Math.floor((num*100)+0.50000000001);decimalDigits=(num%100);if(10>decimalDigits){decimalDigits="0"+decimalDigits}
var thousands=Math.floor(num/100).toString();for(var i=0;i<Math.floor((thousands.length-(1+i))/3);i++){thousands=thousands.substring(0,thousands.length-(4*i+3))
+theThousands
+thousands.substring(thousands.length-(4*i+3));}
if(theDecimals==undefined){return(sign+theCurrency+thousands);}
else{return(sign+theCurrency+thousands+theDecimals+decimalDigits);}}})(sendregning);(function(sr){sr.namespace("error").handler=errorHandler;var log=sr.log;var debug=sr.debug;function errorHandler(noErrorsCallback,errorsCallback){var errorMessages={};function addError(key,value){if(!value){value="true";}
errorMessages[key]=value;makeCallback(errorsCallback);}
function removeError(key){errorMessages[key]=null;if(!hasErrors()){makeCallback(noErrorsCallback);}
else{makeCallback(errorsCallback);}}
function hasErrors(){for(var prop in errorMessages){if(errorMessages.hasOwnProperty(prop)){if(errorMessages[prop]!=null){return true;}}}
return false;}
function clearAll(){for(var prop in errorMessages){if(errorMessages.hasOwnProperty(prop)){errorMessages[prop]=null;}}
return false;}
function makeCallback(callback){if(typeof callback=="function"){callback();}}
return{hasErrors:hasErrors,addError:addError,removeError:removeError,clearAll:clearAll};}})(sendregning);(function(sr){sr.namespace("util").throttler={create:function(callback,opts){return sr.extend(sr.create(this),{callback:callback,opts:opts});},queue:function(term){var self=this;var delay=this.opts&&this.opts.delay||400;clearTimeout(this.timer);this.timer=setTimeout(function(){self.callback(term);},delay);}};}(sendregning));(function(sr){"use strict";var showDateInvoiceInFutureTooltip=true;var showDateInvoice14DaysInPastInfoDiv=true;var dates=sr.namespace("hints.date.invoice");dates.checkDateInvoice=checkDateInvoice;dates.hideTooltipDiv=hideTooltipDiv;dates.permanentHideInvoiceDateInFutureTooltipDiv=permanentHideInvoiceDateInFutureTooltipDiv;dates.permanentHideInvoiceDateInPastTooltipDiv=permanentHideInvoiceDateInPastTooltipDiv;function checkDateInvoice(){var $dateInFutureInfoDiv=$("#dateInFutureInfo");var $date14DaysInPastInfoDiv=$("#date14DaysInPastInfo");$dateInFutureInfoDiv.hide();$date14DaysInPastInfoDiv.hide();var $invoiceDateElement=$("#dateInvoice");var today=new Date();resetTime(today);if($invoiceDateElement.val()!=null&&$invoiceDateElement.val().length>0){var invoiceDate=stringToDate($invoiceDateElement.val());resetTime(invoiceDate);if(showDateInvoiceInFutureTooltip==true){if(invoiceDate>today){showDateWarning($dateInFutureInfoDiv,$invoiceDateElement)}}
var past14Days=new Date();resetTime(past14Days);addDays(past14Days,-14);if(showDateInvoice14DaysInPastInfoDiv==true){if(invoiceDate<past14Days){showDateWarning($date14DaysInPastInfoDiv,$invoiceDateElement);}}}}
function hideTooltipDiv(){$("#dateInFutureInfo").removeClass("sr-modal");$("#date14DaysInPastInfo").removeClass("sr-modal");$("#dateInFutureInfo").hide();$("#date14DaysInPastInfo").hide();}
function permanentHideInvoiceDateInFutureTooltipDiv(){showDateInvoiceInFutureTooltip=false;$("#dateInFutureInfo").hide();}
function permanentHideInvoiceDateInPastTooltipDiv(){showDateInvoice14DaysInPastInfoDiv=false;$("#date14DaysInPastInfo").hide();}}(sendregning));(function(sr){"use strict";var dates=sr.namespace("hints.date.order");dates.checkOrderDate=checkOrderDate;dates.hideTooltipDiv=hideTooltipDiv;dates.permanentHideOrderDateInFutureTooltipDiv=permanentHideOrderDateInFutureTooltipDiv;dates.permanentHideOrderDateInPastTooltipDiv=permanentHideOrderDateInPastTooltipDiv;var showOrderDateInFutureTooltip=true;var showOrderDateInPastTooltipDiv=true;function checkOrderDate(){var $orderDateMonthInPastInfoDiv=$("#orderDateMonthInPastInfo");var $orderDateInFutureInfoDiv=$("#orderDateInFutureInfo");$orderDateMonthInPastInfoDiv.hide();$orderDateInFutureInfoDiv.hide();var $orderDateElement=$("#orderDate");var today=new Date();resetTime(today);if($orderDateElement.val()!=null&&$orderDateElement.val().length>0){var orderDate=stringToDate($orderDateElement.val());resetTime(orderDate);if(showOrderDateInFutureTooltip==true){if(orderDate>today){showDateWarning($orderDateInFutureInfoDiv,$orderDateElement);}}
if(showOrderDateInPastTooltipDiv==true){var monthInPast=new Date();resetTime(monthInPast);addDays(monthInPast,-31);if(orderDate<monthInPast){showDateWarning($orderDateMonthInPastInfoDiv,$orderDateElement);}}}}
function hideTooltipDiv(){$("#orderDateInFutureInfo").removeClass("sr-modal");$("#orderDateMonthInPastInfo").removeClass("sr-modal");$("#orderDateInFutureInfo").hide();$("#orderDateMonthInPastInfo").hide();}
function permanentHideOrderDateInFutureTooltipDiv(){showOrderDateInFutureTooltip=false;$("#orderDateInFutureInfo").hide();}
function permanentHideOrderDateInPastTooltipDiv(){showOrderDateInPastTooltipDiv=false;$("#orderDateMonthInPastInfo").hide();}}(sendregning));(function(sr){"use strict";var dates=sr.namespace("hints.date.due");dates.checkDueDate=checkDueDate;dates.hideTooltipDiv=hideTooltipDiv;dates.permanentHideDueDateInFutureTooltipDiv=permanentHideDueDateInFutureTooltipDiv;dates.permanentHideDueDateInPastTooltipDiv=permanentHideDueDateInPastTooltipDiv;var showDueDateInFutureTooltip=true;var showDueDateInPastTooltipDiv=true;function checkDueDate(){var $dueDateMonthInFutureInfoDiv=$("#dueDateMonthInFutureInfo");var $dueDateInPastInfoDiv=$("#dueDateInPastInfo");$dueDateMonthInFutureInfoDiv.hide();$dueDateInPastInfoDiv.hide();var $dueDateElement=$("#dateDue");var today=new Date();resetTime(today);if($dueDateElement.val()!=null&&$dueDateElement.val().length>0){var dueDate=stringToDate($dueDateElement.val());resetTime(dueDate);if(showDueDateInPastTooltipDiv==true){if(dueDate<today){showDateWarning($dueDateInPastInfoDiv,$dueDateElement);}}
if(showDueDateInFutureTooltip==true){var monthInFuture=new Date();resetTime(monthInFuture);addDays(monthInFuture,31);if(dueDate>monthInFuture){showDateWarning($dueDateMonthInFutureInfoDiv,$dueDateElement);}}}}
function hideTooltipDiv(){$("#dueDateMonthInFutureInfo").removeClass("sr-modal");$("#dueDateInPastInfo").removeClass("sr-modal");$("#dueDateMonthInFutureInfo").hide();$("#dueDateInPastInfo").hide();}
function permanentHideDueDateInFutureTooltipDiv(){showDueDateInFutureTooltip=false;$("#dueDateMonthInFutureInfo").hide();}
function permanentHideDueDateInPastTooltipDiv(){showDueDateInPastTooltipDiv=false;$("#dueDateInPastInfo").hide();}}(sendregning));function postnr2sted(elem,targetName){$element=$(elem);var postcode=$element.val();if(postcode.length>2){$.ajax({url:'/rest/postnr/'+$element.val(),dataType:'json',success:function(json){var $city=$("#"+targetName);if(json.city){$city.val(unescape(json.city));$city.focus();$city.select();}}});}}
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;while(x<c.length){var m=r.exec(c.substr(x));if(m!=null&&m.length>1&&m[1]!=''){o+=m[1];x+=m[1].length;}else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;while((m=r.exec(o))!=null&&m.length>1&&m[1]!=''){b=parseInt(m[1].substr(1),16);t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}});function doMouseOver(elem){elem.style.color='rgb(255,213,3)';elem.style.backgroundColor='rgb(0,86,153)';}
function doMouseOut(elem){elem.style.color='';elem.style.backgroundColor='';}
function updateFieldOrgNoClass(elem){if(elem.value=='prv')
document.getElementById("orgNo").className="null";else
document.getElementById("orgNo").className="required";}
function displayTop5Questions(){$('#top5').load('/rest/html/sos/top/5',function(response,status,xhr){if(status=="error"){}
else{$('#top5 > .qa > div').remove();$('.qa ').wrapInner("<ol/>");$('.qa h3').wrap("<li/>");$('#top5').effect("highlight",{},500);}});}
function isThousands(position)
{if(Math.floor(position/3)*3==position)return true;return false;};function formatMoney(theNumber,theCurrency,theThousands,theDecimal){var theDecimalDigits;if(theDecimal==undefined){theDecimalDigits="";}
else{theDecimalDigits=Math.round((theNumber*100)-(Math.floor(theNumber)*100));}
theDecimalDigits=""+(theDecimalDigits+"0").substring(0,2);theNumber=""+Math.floor(theNumber);var theOutput=theCurrency;for(var x=0;x<theNumber.length;x++){theOutput+=theNumber.substring(x,x+1);if(isThousands(theNumber.length-x-1)&&(theNumber.length-x-1!=0)){theOutput+=theThousands;}}
if(theDecimal!=undefined){theOutput+=theDecimal+theDecimalDigits;}
return theOutput;}
function formatCurrency(theNumber,theCurrency,theThousands,theDecimals){var num=theNumber;if(isNaN(num)){num="0";}
sign=num<0?"-":""
num=Math.abs(num);num=Math.floor((num*100)+0.50000000001);decimalDigits=(num%100);if(10>decimalDigits){decimalDigits="0"+decimalDigits}
var thousands=Math.floor(num/100).toString();for(var i=0;i<Math.floor((thousands.length-(1+i))/3);i++){thousands=thousands.substring(0,thousands.length-(4*i+3))
+theThousands
+thousands.substring(thousands.length-(4*i+3));}
if(theDecimals==undefined){return(sign+theCurrency+thousands);}
else{return(sign+theCurrency+thousands+theDecimals+decimalDigits);}}
function string2NumberString(s){s=s.replace(".","");s=s.replace(",",".");s=s.replace(/ /g,'');return s;}
function field2Number(fld){if(fld!=null){var s=string2NumberString(fld.value);var n=Number(s);return n;}
else
return Number(0);}
var no_monthNames=['januar','februar','mars','april','mai','juni','juli','august','september','oktober','november','desember'];var no_quarterNames=['1. kvartal','1. kvartal','1. kvartal','2. kvartal','2. kvartal','2. kvartal','3. kvartal','3. kvartal','3. kvartal','4. kvartal','4. kvartal','4. kvartal'];function getWeekNumber(date){if(date){Year=getYear(date);Month=date.getMonth();Day=date.getDate();var now=Date.UTC(Year,Month,Day+1,0,0,0);var Firstday=new Date();Firstday.setYear(Year);Firstday.setMonth(0);Firstday.setDate(1);then=Date.UTC(Year,0,1,0,0,0);var Compensation=Firstday.getDay();if(Compensation>3)Compensation-=4;else Compensation+=3;NumberOfWeek=Math.round((((now-then)/86400000)+Compensation)/7);return NumberOfWeek;}}
function getMonthName(date){if(date){return no_monthNames[date.getMonth()];}}
function getQuarterName(date){if(date){return no_quarterNames[date.getMonth()];}}
function getYear(date){if(date){return date.getFullYear();}}
function calulateDueDate(shipmentDate,duePeriode){if(shipmentDate&&duePeriode){if(duePeriode=="firstNextMonth"){shipmentDate.setMonth(shipmentDate.getMonth()+1,1);return shipmentDate;}
else if(duePeriode=="lastThisMonth"){return new Date(Date.UTC(shipmentDate.getFullYear(),shipmentDate.getMonth()+1,1)-864E5);}
else if(duePeriode=="lastNextMonth"){return new Date(Date.UTC(shipmentDate.getFullYear(),shipmentDate.getMonth()+2,1)-864E5);}
else if(duePeriode=="oneWeek"){shipmentDate.setDate(shipmentDate.getDate()+7);return shipmentDate;}
else if(duePeriode=="twoWeeks"){shipmentDate.setDate(shipmentDate.getDate()+14);return shipmentDate;}
else if(duePeriode=="threeWeeks"){shipmentDate.setDate(shipmentDate.getDate()+21);return shipmentDate;}
else if(duePeriode=="oneMonth"){shipmentDate.setMonth(shipmentDate.getMonth()+1);return shipmentDate;}
else if(duePeriode=="twoMonths"){shipmentDate.setMonth(shipmentDate.getMonth()+2);return shipmentDate;}
else if(duePeriode=="threeMonths"){shipmentDate.setMonth(shipmentDate.getMonth()+3);return shipmentDate;}
else if(duePeriode=="halfYear"){shipmentDate.setMonth(shipmentDate.getMonth()+6);return shipmentDate;}
else if(duePeriode=="oneYear"){shipmentDate.setFullYear(shipmentDate.getFullYear()+1);return shipmentDate;}
else if(duePeriode=="fourtyFiveDays"){shipmentDate.setDate(shipmentDate.getDate()+45);return shipmentDate;}
else{alert("Unknown duePeriode: "+duePeriode);}}}
var MODAL_WINDOW_WIDTH="900px";var showDescriptionTooltipGlobal=true;var currentFieldOriginalBackgroundColor;var isIE=(navigator.appName.indexOf("Microsoft")!=-1);var requiredColor="251, 238, 172";var origCreditDays;var MAX_ITEMS_IN_VIEW=19;var ITEMS_TABLE_NAME="tblFakturaLinjer";var strutsPattern="(ivo.invoiceItems\\[)(\\d+)(\\].\\w+)";var namePattern=new RegExp(strutsPattern);var elementIdPattern="^(item[a-zA-Z]+\\[)(\\d+)(\\])$";var currentInvoice=new TInvoice(0,0,0);var tabIndexCounter=17
var recipientLost=false;;if(!Number.prototype.toFixed){Number.prototype.toFixed=function(n){var x=Math.pow(10,n);var y=(Math.round(this*x)/x);return y.toString();}}
var proposedRecipientNo=false;function onInit(){var recipientIdElem=document.getElementById('ivo.recipientId');if(recipientIdElem.value){setReadOnly(document.getElementById('ivo.recipientNo'));setReadOnly(document.getElementById('ivo.name'));setReadOnly(document.getElementById('ivo.address1'));setReadOnly(document.getElementById('ivo.address2'));setReadOnly(document.getElementById('ivo.zip'));setReadOnly(document.getElementById('city'));setReadOnly(document.getElementById('ivo.country'));setReadOnly(document.getElementById('ivo.recipientEmail'));copyDatesToGiro();copyAddressToGiro();if(Ext.get('x-button')!=null){Ext.get('x-button').setVisible(true,true);}
var searchCombo=Ext.getCmp('ajaxRecipientNameSearchCombo');if(searchCombo){searchCombo.disable();}
$('#dateInvoice').focus();}
else{$('#ivo\\.recipientNo').focus();if(document.getElementById('ivo.recipientNo').value!=null){proposedRecipientNo=true;}}
calcTotal();if(isInvoiceReadOnly()){setAllFieldsReadOnly();}
else{}
estimateDueDate();$("#dateInvoice").change(function(){sendregning.hints.date.invoice.checkDateInvoice();});$("#dateDue").change(function(){sendregning.hints.date.due.checkDueDate();});$("#orderDate").change(function(){sendregning.hints.date.order.checkOrderDate();});checkDates();return true;}
function maskDocument(text){Ext.get(document.documentElement||document.body).mask(text);}
function unmaskDocument(){Ext.get(document.documentElement||document.body).unmask();}
function findNextRecipientNo(event){if(window.event){keynum=event.keyCode;}
else if(event.which){keynum=event.which;}
if(keynum&&keynum==39){Ext.Ajax.request({url:'/sr/ajax/getNextRecipientNo.do',method:'GET',success:function(response,opt){if(isLoggedIn(response.responseText)){if(response.responseText.length>0){var next=Ext.util.JSON.decode(response.responseText);Ext.get('ivo.recipientNo').dom.value=next.next;proposedRecipientNo=true;$('#ivo\\.name').focus();}}},failure:function(response,opt){Ext.MessageBox.alert('Failed, response code='+response.status,response.responseText);}});}
else{proposedRecipientNo=false;}}
function findRecipientByRecipientNo(elem){if(elem!=null&&elem.value.length>0&&!proposedRecipientNo){Ext.get('invoiceRecipientTable').mask('S&oslash;ker etter kundenr: '+elem.value,'x-mask-loading');Ext.Ajax.request({url:'/sr/ajax/recipientNoLookup.do',params:{query:elem.value},method:'GET',callback:function(){Ext.get('invoiceRecipientTable').unmask();},success:function(response,opt){if(isLoggedIn(response.responseText)){copyRecipientToHeader(Ext.util.JSON.decode(response.responseText));copyDatesToGiro();checkIfRecipientLost(Ext.util.JSON.decode(response.responseText));madeChanges();}},failure:function(response,opt){Ext.MessageBox.alert('Failed, response code='+response.status,response.responseText);}});}
else{document.getElementById("ivo.recipientId").value='';document.getElementById("recipientDiscount").value='';}
proposedRecipientNo=false;return true;}
function navigateToNewInvoicePage(){var uri=document.documentURI;if(uri.indexOf('initInvoice.do?invoiceType=')>0){location.href=uri;}
else if(uri.indexOf('getInvoice.do?ivo.id=')>0){location.href=uri;}
else if(uri.indexOf('recurring/createTemplate.do')>0){location.href=uri;}
else if(uri.indexOf('editRecurringInvoiceTemplate.do?id=')>0){location.href=uri;}
else{location.href='/sr/initInvoice.do?invoiceType=ordinary';}}
function isLoggedIn(ajaxResponseText){if(ajaxResponseText.length>0){if(ajaxResponseText.indexOf('SendRegning.no kundep&aring;logging')>0){Ext.MessageBox.show({minWidth:300,title:'Inaktiv &oslash;kt',msg:'<h3>Din &oslash;kt har blitt inaktiv.</h3><p>Du er n&oslash;dt til &aring; logge p&aring; igjen f&oslash;r du kan fortsette</p><div><p>Det er dessverre ingen mulighet for &aring; f&aring; lagret det du evt. m&aring;tte ha fylt ut<br />i og med at du ikke er logget inn</p></div>',icon:Ext.MessageBox.ERROR,buttons:Ext.MessageBox.OK,fn:navigateToNewInvoicePage,cls:'sr-alert'});return false;}
else{return true;}}}
function findProductByProductNo(elem){if(elem!=null&&elem.value!=null&&elem.value.length>0){if(!Ext.isIE7){Ext.get('invoiceLines').mask('S&oslash;ker etter produktnr: '+elem.value,'x-mask-loading');}
Ext.Ajax.request({url:'/sr/ajax/productNoLookup.do',params:{query:elem.value},method:'GET',callback:function(){if(!Ext.isIE7){Ext.get('invoiceLines').unmask();}},success:function(response,opt){if(isLoggedIn(response.responseText)){copyProductToInvoiceLine(elem.parentNode.parentNode,Ext.util.JSON.decode(response.responseText));}},failure:function(response,opt){Ext.MessageBox.alert('Failed, response code='+response.status,response.responseText);}});}
else{return null;}}
function copyProductToInvoiceLine(row,product){if(row!=null&&product!=null){findInputElementInInvoiceItemRow(row,'invoiceItemProdCode').value=unescape(product.productNo);findInputElementInInvoiceItemRow(row,'invoiceItemDescription').value=unescape(product.productDesc);findInputElementInInvoiceItemRow(row,'invoiceItemUnitPrice').value=unescape(product.salesPrice);findInputElementInInvoiceItemRow(row,'invoiceItemTax').value=unescape(product.taxRate);var recipientDiscount=$("#recipientDiscount").val();if(recipientDiscount!=null&&recipientDiscount!="0"&&recipientDiscount!="0.00"){findInputElementInInvoiceItemRow(row,'invoiceItemDiscount').value=$("#recipientDiscount").val();}else{findInputElementInInvoiceItemRow(row,'invoiceItemDiscount').value="";}
calcItem(findInputElementInInvoiceItemRow(row,'invoiceItemUnitPrice'));if(findInputElementInInvoiceItemRow(row,'invoiceItemQty').value.length==0){$(findInputElementInInvoiceItemRow(row,'invoiceItemQty')).focus();}
else{$(findInputElementInInvoiceItemRow(row,'invoiceItemDescription')).focus();}
madeChanges();}}
function updateDiscount(elem,update){var itemsTable=document.getElementById(ITEMS_TABLE_NAME);var rowId=elem.parentNode.parentNode.rowIndex-1;var priceValue=$("#itemUnitPrice\\["+rowId+"\\]").val();if(priceValue==null||priceValue.length==0){$("#itemDiscount\\["+rowId+"\\]").val("");}else{var currentDiscount=$("#itemDiscount\\["+rowId+"\\]").val();if(currentDiscount!=null&&currentDiscount.length>0&&!update){return;}
copyDiscountFromRecipientToItem(rowId);}}
function updateItemsDiscounts(){var itemsTable=document.getElementById(ITEMS_TABLE_NAME);var i=0;var rowCount=itemsTable.rows.length;for(i=0;i<=rowCount;i++){var rowId=i;var elemAmount=document.getElementsByName('ivo.invoiceItems['+rowId+'].invoiceItemQty')[0];var elemUnitPrice=document.getElementsByName('ivo.invoiceItems['+rowId+'].invoiceItemUnitPrice')[0];if(elemAmount!=null&&elemAmount.value!=null&&elemAmount.value.length>0&&elemUnitPrice!=null&&elemUnitPrice.value!=null&&elemUnitPrice.value.length>0){copyDiscountFromRecipientToItem(rowId);}}}
function copyDiscountFromRecipientToItem(rowId){var recipientDiscount=$("#recipientDiscount").val();if(recipientDiscount!=null&&recipientDiscount!="0"&&recipientDiscount!="0.00"){$("#itemDiscount\\["+rowId+"\\]").val(recipientDiscount);}else{$("#itemDiscount\\["+rowId+"\\]").val("");}}
function checkIfRecipientLost(recipient){if(recipient!=null){try{recipientLost=recipient.get("lost");}
catch(exception){recipientLost=unescape(recipient.lost);}
if(recipientLost=='true'){$("#lostRecipientInfo").show();}else{$("#lostRecipientInfo").hide();}}}
function copyRecipientToHeader(recipient){if(recipient!=null){try{var recip=recipient.get("recipientNo");}
catch(exception){var recip=unescape(recipient.recipientNo);}
var ivoRecipNo=document.getElementById("ivo.recipientNo");ivoRecipNo.value=recip;setReadOnly(ivoRecipNo);var ivoName=document.getElementById("ivo.name");try{ivoName.value=recipient.get("name");}
catch(exception){ivoName.value=unescape(recipient.name);}
setReadOnly(ivoName);var ivoAddress1=document.getElementById("ivo.address1");try{ivoAddress1.value=recipient.get("address1");}
catch(exception){ivoAddress1.value=unescape(recipient.address1);}
setReadOnly(ivoAddress1);var ivoAddress2=document.getElementById("ivo.address2");try{ivoAddress2.value=recipient.get("address2");}
catch(exception){ivoAddress2.value=unescape(recipient.address2);}
setReadOnly(ivoAddress2);var ivoZip=document.getElementById("ivo.zip");try{ivoZip.value=recipient.get("zip");}
catch(exception){ivoZip.value=unescape(recipient.zip);}
setReadOnly(ivoZip);var ivoCity=document.getElementById("city");try{ivoCity.value=recipient.get("city");}
catch(exception){ivoCity.value=unescape(recipient.city);}
setReadOnly(ivoCity);var ivoCountry=document.getElementById("ivo.country");try{ivoCountry.value=recipient.get("country");}
catch(exception){ivoCountry.value=unescape(recipient.country);}
setReadOnly(ivoCountry);var ivoRecipientEmail=document.getElementById("ivo.recipientEmail");try{var recipientEmail=recipient.get("recipientEmail");}
catch(exception){var recipientEmail=unescape(recipient.recipientEmail);}
if(recipientEmail==null||recipientEmail==""||recipientEmail=="null"){ivoRecipientEmail.value="";}
else{ivoRecipientEmail.value=recipientEmail;}
setReadOnly(ivoRecipientEmail);try{var recipientId=recipient.get("recipientId");}
catch(exception){var recipientId=unescape(recipient.recipientId);}
if(recipientId!=null&&recipientId>0){document.getElementById("ivo.recipientId").value=recipientId;}
else{document.getElementById("ivo.recipientId").value=null;}
try{var creditDays=recipient.get("creditDays");}
catch(exception){var creditDays=unescape(recipient.creditDays);}
var newDueDate=addDays(new Date(),creditDays);if(newDueDate!=null){var dateDue=document.getElementById("dateDue");if(dateDue!=null){dateDue.value=dateToString(newDueDate);}}
try{var recipientDiscount=recipient.get("discount");}
catch(exception){var recipientDiscount=unescape(recipient.discount)}
$("#recipientDiscount").val(recipientDiscount);Ext.get('x-button').setVisible(true,true);Ext.getCmp('ajaxRecipientNameSearchCombo').disable();updateItemsDiscounts();$("#dateInvoice").focus();}
else
if(recipient==null){removeReadOnly(document.getElementById("ivo.recipientNo"),"255,255,255");removeReadOnly(document.getElementById("ivo.name"),requiredColor);removeReadOnly(document.getElementById("ivo.address1"),requiredColor);removeReadOnly(document.getElementById("ivo.address2"),"255,255,255");removeReadOnly(document.getElementById("ivo.zip"),requiredColor);removeReadOnly(document.getElementById("city"),requiredColor);removeReadOnly(document.getElementById("ivo.country"),"255,255,255");removeReadOnly(document.getElementById("ivo.recipientEmail"),"255,255,255");document.getElementById("ivo.recipientId").value='';document.getElementById("ivo.country").value="NORGE";$("#recipientDiscount").val("");var dateDueElement=document.getElementById("dateDue");if(dateDueElement!=null){dateDueElement.value=dateToString(addDays(new Date(),null));}
Ext.get('x-button').setVisible(false,true);Ext.getCmp('ajaxRecipientNameSearchCombo').enable();Ext.get('ajaxRecipientNameSearch').dom.value='';$("#lostRecipientInfo").hide();$('#ajaxRecipientNameSearch').focus();}
copyAddressToGiro();calcTotal();}
function validate_form(){alertMessage="";if(document.getElementById("ivo.name").value.length==0){alertMessage='<li>Mottakers navn</li>';}
if(document.getElementById("ivo.zip").value.length==0){alertMessage=alertMessage+'<li>Mottakers postnummer</li>';}
else
if(document.getElementById("ivo.zip").value.length<4){alertMessage=alertMessage+'<li>Mottakers postnummer</li>';}
if(document.getElementById("city").value.length==0){alertMessage=alertMessage+'<li>Mottakers poststed</li>';}
if(document.getElementById("dateInvoice").value.length==0){alertMessage=alertMessage+'<li>Fakturadato</li>';}
if(document.getElementById("dateDue").value.length==0){alertMessage=alertMessage+'<li>Forfallsdato</li>';}
if(alertMessage.length>0){niceMessage='F&oslash;lgende felter m&aring; fylles ut for &aring; g&aring; videre:';Ext.MessageBox.show({minWidth:300,title:niceMessage,msg:'<div><ul>'+alertMessage+'</ul></div>',icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});return false;}
return true;}
function setOnFocusAndBlurEvent(){if(isIE){for(i=0;i<document.forms.length;i++){currentForm=document.forms[i];for(j=0;j<currentForm.elements.length;j++){var elem=currentForm.elements[j];if(elem.tagName&&(elem.tagName=='SELECT'||(elem.tagName=="INPUT"&&elem.type=="text"))){elem.onfocus=new Function("setFocus(this);"+elem.onfocus);elem.onblur=new Function("leaveFocus(this);"+elem.onblur);}}}}}
function isInvoiceReadOnly(){var inputElement=document.getElementById('state');if(inputElement&&(inputElement.value=='draft'||inputElement.value=='start')){return false;}
else{return true;}}
function setAllFieldsReadOnly(){for(i=0;i<document.forms.length;i++){currentForm=document.forms[i];for(j=0;j<currentForm.elements.length;j++){elem=currentForm.elements[j];if(elem.type&&elem.type!='submit'){elem.onfocus=null;elem.onblur=null;if(elem.type=='button'){elem.onclick=null;}
else
if(elem.type=="select-one"){elem.outerText=elem.value;}
elem.style.borderStyle='none';elem.readOnly=true;if(elem.type=='button')
elem.style.display='none';}}}}
function post_event(el,invoiceEventName){if(invoiceEventName!="cancel"&&validate_form()==false)
return false;var eventField=document.getElementById("invoiceEvent");if(!eventField){throw"HTML Field 'invoiceEvent' not found";}
eventField.value=invoiceEventName;return true;}
function updateIdenticalEventAndChangeFormAction(identicalEventName,newFormAction){var identicalEventNameField=document.getElementById("identicalEventName");if(!identicalEventNameField){throw"HTML field named 'identicalEventName' not found...";}
identicalEventNameField.value=identicalEventName;document.forms[0].action=newFormAction;return true;}
function changeFormAction(newFormAction){document.forms[0].action=newFormAction;return true;}
function TInvoice(total,tax,roundingTotal){this.invoiceTotal=total;this.invoiceTax=tax;this.roundingTotal=roundingTotal;this.mvaGroups=new Object();this.mvaGrunlagGroups=new Object();}
function Titem(total,tax,itemTaxRate){this.itemTotal=total;this.itemTax=tax;this.totalWithoutTax=total-tax;this.itemTaxRate=itemTaxRate;}
function dateToString(d){if(d){var day=d.getDate();var month=d.getMonth();var year=d.getFullYear()-2000;month+=1;day=day+'';month=month+'';year=year+'';if(day.length==1){day="0"+day;}
if(month.length==1){month="0"+month;}
if(year.length==1){year="0"+year;}
return day+'.'+month+'.'+year;}}
function stringToDate(s){var year=s.substr(6,2);var month=Number(s.substr(3,2));var date=Number(s.substr(0,2));month-=1;var newYear="20"+year;var result=new Date();result.setDate(date);result.setMonth(month);result.setFullYear(Number(newYear));return result;}
function addDays(myDate,days){if(days==null||days=="null"||days==""){days=origCreditDays;}
var D=myDate;var daysToAdd=Number(days);var daysInDate=Number(D.getDate());var totalDays=daysInDate+daysToAdd;D.setDate(totalDays);return D;}
function copyDatesToGiro(){var dateDue=document.getElementById("dateDue");if(dateDue!=null){document.getElementById("giro_due_date").innerHTML=dateDue.value;document.getElementById("giro_invoice_date").innerHTML=document.getElementById("dateInvoice").value;}}
function isValidNumber(elem,fieldName,min,max){if(elem!=null&&elem.value!=null&&elem.value.length>0){var n=field2Number(elem);if(!isNaN(n)){if(min!=null){if(n<min){Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Verdien i feltet '"+fieldName+"' kan ikke v&aelig;re mindre enn: "+min,icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}
if(max!=null){if(n>max){Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Verdien i feltet '"+fieldName+"' kan ikke v&aelig;re st&oslash;rre enn: "+max,icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}
var splitArray=string2NumberString(elem.value).split(".");if(splitArray.length>1){if(splitArray[1].length>2){Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Et tall kan bare inneholde to desimaltegn",icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}
return true;}
else{Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Feltet '"+fieldName+"' kan kun inneholde et heltall eller et desimaltall!<br />F.eks: 1, 10, eller 0,5.",icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}}
function isValidPositiveNumber(elem,fieldName,max){if(elem!=null&&elem.value!=null&&elem.value.length>0){var splitArray=string2NumberString(elem.value).split(".");if(splitArray.length>1){if(splitArray[1].length>2){Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Et tall kan bare inneholde to desimaltegn",icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}
var n=field2Number(elem);if(!isNaN(n)&&n>=0){if(max!=null){if(n>max){Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Verdien i feltet '"+fieldName+"' kan ikke v&aelig;re st&oslash;rre enn: "+max,icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}
return true;}
else{Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Feltet '"+fieldName+"' kan kun inneholde et positivt heltall eller et desimaltall!<br />F.eks: 1, 10 eller 0,5<p>Ikke bruk komma eller punktum som tusentegnskille</p>",icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}}
function setReadOnly(elem){elem.readOnly=true;elem.style.backgroundColor='rgb(204,204,204)';elem.onfocus=null;elem.onblur=null;return true;}
function removeReadOnly(elem,color){elem.readOnly=false;var bColor="rgb("+color+")";elem.style.backgroundColor=bColor;elem.value="";elem.onfocus=new Function("setFocus(this);");elem.blur=new Function("leaveFocus(elem);");if(elem.name=="ivo.zip"){elem.onblur=new Function("leaveFocus(this); copyAddressToGiro(); postnr2sted(this, 'city'); checkAddress1('ivo.address1');");}
else
if(elem.name=="ivo.recipientNo"){elem.onblur=new Function("leaveFocus(this); findRecipientByRecipientNo(this);");}
else if(elem.name=="ivo.name"){elem.onblur=new Function("leaveFocus(this); checkRecipient(); findRecipientByRecipientNo(this);");}
else if((elem.name=="ivo.address1")||(elem.name=="ivo.city")){elem.onblur=new Function("leaveFocus(this); copyAddressToGiro(); checkAddress1('ivo.address1');");}
else{elem.onblur=new Function("leaveFocus(this); copyAddressToGiro();");}
return true;}
function copyAddressToGiro(){try{var PaidByBox=document.getElementById("PaidByBox");if(!PaidByBox){throw"copyAddressToGiro() :- Fant ikke HTML elementet med navn 'PaidByBox'";}
var fields=["ivo.name","ivo.address1","ivo.address2","ivo.zip","city","ivo.country"];var delimiter="";var newInnerHtml="";for(var i=0;i<fields.length;i++){var fieldValue;var field=document.getElementById(fields[i]);if(!field)
throw"copyAddressToGiro() :- HTML element '"+fields[i]+"' not found in document";if(field.value!="")
newInnerHtml+=delimiter+field.value;if(fields[i]=="ivo.zip"){delimiter=" ";}
else{delimiter="<br>";}}
PaidByBox.innerHTML="<p class=\"giro_address\">"+newInnerHtml+"</p>";}
catch(ex){alert("Det oppstod en intern feil i copyAddressToGiro() :- \n"+ex);}}
function lookupProduct(elem){var productStore=new Ext.data.JsonStore({id:'productNo',root:'products',totalProperty:'totalCount',fields:[{name:'productNo',mtype:'string',convert:function(s){return unescape(s)}},{name:'productDesc',type:'string',convert:function(s){return unescape(s)}},{name:'salesPrice',type:'string',convert:function(s){return unescape(s)}},{name:'taxRate',type:'string',convert:function(s){return unescape(s)}}],url:'/sr/ajax/productList.do',listeners:{loadexception:function(proxy,options,response,error){isLoggedIn(response.responseText);}}});var productPagingBar=new Ext.PagingToolbar({pageSize:10,store:productStore,displayInfo:true,displayMsg:'Viser {0} - {1} av {2} produkter',emptyMsg:"Ingen produkter i produktlisten...",items:['-',{text:'Avbryt',cls:'x-btn',handler:function(button,event){productListWindow.close();}}]});var productGridPanel=new Ext.grid.GridPanel({height:250,store:productStore,stripeRows:true,trackMouseOver:true,loadMask:true,autoExpandColumn:'pd',bbar:productPagingBar,viewConfig:{deferEmptyText:true,emptyText:'Ingen produkter i produktlisten...'},columns:[{header:"Produktnr",dataIndex:'productNo',sortable:true},{header:"Beskrivelse",dataIndex:'productDesc',sortable:true,id:"pd"},{header:"Enhetspris",dataIndex:'salesPrice',sortable:true},{header:"MVA",dataIndex:'taxRate',sortable:true}],sm:new Ext.grid.RowSelectionModel({singleSelect:true}),listeners:{rowclick:function(grid,rowIndex,event){var record=grid.getStore().getAt(rowIndex);var product=new Object();product.productNo=record.get('productNo');product.productDesc=record.get('productDesc');product.salesPrice=record.get('salesPrice');product.taxRate=record.get('taxRate');copyProductToInvoiceLine(elem.parentNode.parentNode,product);productListWindow.close();}}});var productSearchPanel=new Ext.form.FormPanel({height:50,bodyStyle:'padding: 5px 5px 0',xtype:'form',id:'asset-form',layout:'hbox',frame:true,collapsed:false,tbar:[new Ext.Toolbar.TextItem("S\u00F8k etter:"),{xtype:'textfield',fieldLabel:'Search',name:'pattern',id:'pattern'},{xtype:'tbseparator'},new Ext.Toolbar.Button({text:'S\u00F8k',iconCls:'search-icon',handler:function search_submit(){productStore.baseParams={pattern:document.getElementById('pattern').value};productStore.load({params:{start:0,limit:10}});}}),{xtype:'tbseparator'},new Ext.Toolbar.Button({text:'Nullstill s\u00F8k',iconCls:'reload-icon',handler:function(){var s=Ext.getCmp('pattern');s.setValue('');productStore.baseParams={pattern:document.getElementById('pattern').value};productStore.load({params:{start:0,limit:10}});}})]});var productListWindow=new Ext.Window({height:335,width:600,autoScroll:true,closeable:true,constrain:true,title:'Velg produkt ved &aring; klikke p&aring; produktet...',modal:true,layout:'anchor',items:[productSearchPanel,productGridPanel],listeners:{show:function(comp){productStore.load({params:{start:0,limit:10}});}}});productListWindow.show(elem);}
function calcItem(currentInput){if(currentInput.readOnly||isInvoiceReadOnly()){return;}
var s=currentInput.value.replace(/\./g,",");currentInput.value=s;var currentCell=currentInput.parentNode;var currentRow=currentCell.parentNode;if(currentRow.tagName!="TR"){alert('Ooops, unable to find row: '+currentRow.tagName);}
else{calcTotal();}}
function calcTotal(){var invoiceNetValue=0;currentInvoice.invoiceTotal=0.0;currentInvoice.invoiceTax=0.0;currentInvoice.roundingTotal=0.0;currentInvoice.mvaGroups=new Object();currentInvoice.mvaGrunlagGroups=new Object();try{if(isInvoiceReadOnly()){currentInvoice.invoiceTotal=new Number(document.getElementById('total').value);currentInvoice.invoiceTax=new Number(document.getElementById('tax').value);currentInvoice.roundingTotal=new Number(document.getElementById('roundingTotal').value);}
else{var tbody=document.getElementById("invoiceItems");if(!tbody){throw'Unable to find the TBODY "invoiceItems"';}
var item;var invoiceTotalEksMva=0.0;for(var i=0;i<tbody.childNodes.length;i++){if(tbody.childNodes[i].nodeName=="TR"){item=calcRow(tbody.childNodes[i]);currentInvoice.invoiceTotal+=item.itemTotal;currentInvoice.invoiceTax+=item.itemTax;invoiceTotalEksMva+=item.totalWithoutTax;if(item.itemTotal!=0){if(currentInvoice.mvaGroups[item.itemTaxRate]==null){currentInvoice.mvaGrunlagGroups[item.itemTaxRate]=item.totalWithoutTax;currentInvoice.mvaGroups[item.itemTaxRate]=item.itemTax;}
else{currentInvoice.mvaGrunlagGroups[item.itemTaxRate]+=item.totalWithoutTax;currentInvoice.mvaGroups[item.itemTaxRate]+=item.itemTax;}}}}
var roundedTaxAmount=0.0;for(var x in currentInvoice.mvaGroups){roundedTaxAmount+=new Number(currentInvoice.mvaGroups[x].toFixed(2));}
var roundedTotalEksMva=new Number(invoiceTotalEksMva.toFixed(2));var roundedTaxTotal=new Number(roundedTaxAmount.toFixed(2));var roundedTotal=new Number(currentInvoice.invoiceTotal.toFixed(2));var roundingAmount=roundedTotal-(roundedTotalEksMva+roundedTaxTotal);currentInvoice.roundingTotal=roundingAmount;}
if(!isNaN(currentInvoice.invoiceTotal)){invoiceNetValue=currentInvoice.invoiceTotal-currentInvoice.invoiceTax;var netValue=document.getElementById("netValue");generateMvaString(netValue,currentInvoice.mvaGrunlagGroups);var totalTax=document.getElementById("totalTax");generateMvaString(totalTax,currentInvoice.mvaGroups);var paymentIntegerPart=new Number(currentInvoice.invoiceTotal.toFixed(2));var grandTotal=formatCurrency(currentInvoice.invoiceTotal,""," ",",");var payKroner=grandTotal.substring(0,grandTotal.indexOf(","));var payOre=grandTotal.substring(grandTotal.indexOf(",")+1);var grandTotElement=document.getElementById("grandTotal")
grandTotElement.innerHTML=grandTotal;if(currentInvoice.roundingTotal.toFixed(2)==0){$("#roundingContainer").hide();}
else{$("#roundingContainer").show();}
var roundingTotal=formatCurrency(currentInvoice.roundingTotal,""," ",",");var roundingTotalElement=document.getElementById("roundingTotalSum");roundingTotalElement.innerHTML=roundingTotal;document.getElementById("payOre").innerHTML=payOre;document.getElementById("payKroner").innerHTML=payKroner;return currentInvoice.invoiceTotal;}}
catch(e){var x="";for(p in e){x+='\n\t'+p+':'+e[p];}
alert('INTERNFEIL I001:'+'calcTotal() :- '+x!=""?x:e);return null;}
return null;}
function generateMvaString(element,mvagroups){if(element){var netValStr="";var size=0;for(var x in mvagroups){if(mvagroups[x]==0){continue;}
if(size!=0){netValStr+=" ";}
netValStr+=x+"%: "
netValStr+=formatCurrency(mvagroups[x],""," ",",");size++;}
if(netValStr==""){netValStr="0,00";}
element.innerHTML=netValStr;}}
function findInputElementInInvoiceItemRow(row,elemName){var pattern=new RegExp(elemName);if(row.cells==null){alert("Row='"+row+"', elemName='"+elemName+"'");return null;}
for(var i=0;i<row.cells.length;i++){var cell=row.cells[i];if(cell.nodeName!="TD"){continue;}
for(var j=0;j<cell.childNodes.length;j++){var inputElement=cell.childNodes[j];if(inputElement.tagName!=null&&(inputElement.tagName=="INPUT"||inputElement.tagName=="SELECT")){if(inputElement.name.indexOf(elemName)>0){return inputElement;}}}}
alert("Returning null when looking for: "+elemName);return null;}
function calcRow(rowToCalc){var itemQty=0;var itemUnitPrice=0;var itemDiscount=0;var itemTaxRate=0;var itemTax=0;var itemTotal=new Number(0);var totalCell=null;itemQty=field2Number(findInputElementInInvoiceItemRow(rowToCalc,'invoiceItemQty'));itemUnitPrice=field2Number(findInputElementInInvoiceItemRow(rowToCalc,'invoiceItemUnitPrice'));itemDiscount=field2Number(findInputElementInInvoiceItemRow(rowToCalc,'invoiceItemDiscount'));itemTaxRate=field2Number(findInputElementInInvoiceItemRow(rowToCalc,'invoiceItemTax'));totalCell=findInputElementInInvoiceItemRow(rowToCalc,'invoiceItemTotal');itemTotal=((itemQty*itemUnitPrice)*(100-itemDiscount)/100);itemTax+=itemTotal*(itemTaxRate)/100;itemTotal+=itemTax;var displayFigure=itemTotal;var e=document.getElementById("itemTaxInclude");if(e){if(e.value){if(e.value.match(/false/i)){displayFigure=itemTotal-itemTax;}}}
if(totalCell!=null){if(itemTotal!=null&&!isNaN(itemTotal)){totalCell.value=(displayFigure!=0)?formatCurrency(displayFigure,""," ",","):"";}
else{totalCell.value="";}}
return(new Titem(itemTotal,itemTax,itemTaxRate));}
function addAnotherInvoiceItem(){var itemsTable=document.getElementById(ITEMS_TABLE_NAME);if(!itemsTable){throw"Intern feil: fant ikke '"+ITEMS_TABLE_NAME+"'";}
if(itemsTable.rows.length>=MAX_ITEMS_IN_VIEW){Ext.MessageBox.show({minWidth:300,title:'Advarsel',msg:"Beklager, det er en begrensning p&aring; "+(MAX_ITEMS_IN_VIEW-1)+" fakturalinjer pr. faktura",icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});return false;}
var lastRow=itemsTable.rows[itemsTable.rows.length-1];if(!lastRow){alert("Unable to find last row");}
var newRow=itemsTable.insertRow(itemsTable.rows.length);$(newRow).addClass("invoiceItem");for(var i=0;i<lastRow.cells.length;i++){var newCell=newRow.insertCell(i);newCell.innerHTML=new String(lastRow.cells[i].innerHTML);}
renumberAndUpdateTabIndexForInvoiceItemElements(itemsTable);findInputElementInInvoiceItemRow(newRow,'invoiceItemQty').value='';findInputElementInInvoiceItemRow(newRow,'invoiceItemProdCode').value='';findInputElementInInvoiceItemRow(newRow,'invoiceItemDescription').value='';findInputElementInInvoiceItemRow(newRow,'invoiceItemUnitPrice').value='';findInputElementInInvoiceItemRow(newRow,'invoiceItemDiscount').value='';findInputElementInInvoiceItemRow(newRow,'invoiceItemTotal').value='';$(findInputElementInInvoiceItemRow(newRow,'invoiceItemQty')).focus();return true;}
function removeInvoiceItem(elem){var itemsTable=document.getElementById(ITEMS_TABLE_NAME);var rowCount=itemsTable.rows.length;var rowId=elem.parentNode.parentNode.rowIndex-1;if(rowId==0&&rowCount==2){clearFirstLine();}else{itemsTable.deleteRow(elem.parentNode.parentNode.rowIndex);renumberAndUpdateTabIndexForInvoiceItemElements(itemsTable);}}
function clearFirstLine(){$("#itemQty\\[0\\]").val("");$("#itemProdCode\\[0\\]").val("");$("#itemDescription\\[0\\]").val("");$("#itemUnitPrice\\[0\\]").val("");$("#itemDiscount\\[0\\]").val("");$("#itemTax\\[0\\]").val("25");}
function renumberAndUpdateTabIndexForInvoiceItemElements(table){var rowCounter=-1;for(var rowNumber=0;rowNumber<table.tBodies[0].childNodes.length;rowNumber++){if(table.tBodies[0].childNodes[rowNumber].nodeName=="TR"){rowCounter++;var currentRow=table.tBodies[0].childNodes[rowNumber];for(var cellNumber=0;cellNumber<currentRow.cells.length;cellNumber++){var currentCell=currentRow.cells[cellNumber];for(var cellElementIndex=0;cellElementIndex<currentCell.childNodes.length;cellElementIndex++){var cellElement=currentCell.childNodes[cellElementIndex];if(cellElement.nodeName=="INPUT"||cellElement.nodeName=="SELECT"){reIndexElementNameAndReValueHiddenFieldItemNo(cellElement,rowCounter);updateTabIndex(cellElement);reIndexElementId(cellElement,rowCounter);}
else if(cellElement.nodeName=="IMG"){reIndexBallonHelp(cellElement,rowCounter);}
else if(cellElement.nodeName=="BUTTON"&&cellElement.name.indexOf("lookUpProductBtn")>0){updateTabIndex(cellElement);}
else if(cellElement.nodeName=="BUTTON"&&rowCounter>0&&cellElement.disabled==true){cellElement.disabled=false;}}}}}}
function reIndexBallonHelp(cellElement,indexNumber){var globNamePattern=new RegExp(strutsPattern,"g");for(var i=0;i<cellElement.attributes.length;i++){var current=cellElement.attributes[i];if(current.nodeName=="onmouseover"){current.nodeValue=current.nodeValue.replace(globNamePattern,function(oldName,prefix,number,suffix){return prefix+indexNumber+suffix});break;}}}
function reIndexElementNameAndReValueHiddenFieldItemNo(cellElement,indexNumber){var globNamePattern=new RegExp(strutsPattern,"g");var cellElementName=cellElement.name;cellElementName=cellElementName.replace(globNamePattern,function(oldName,prefix,number,suffix){return prefix+indexNumber+suffix});cellElement.name=cellElementName;if(cellElement.nodeName=="INPUT"&&cellElement.name.indexOf("invoiceItemItemNo")>0){cellElement.value=indexNumber+1;}}
function reIndexElementId(cellElement,indexNumber){var globIdPattern=new RegExp(elementIdPattern,"g");var cellElementId=cellElement.id;cellElementId=cellElementId.replace(globIdPattern,function(oldName,prefix,number,suffix){return prefix+indexNumber+suffix});cellElement.id=cellElementId;}
function updateTabIndex(elem){if(elem.name.indexOf("total")>0){return;}
elem.tabIndex=tabIndexCounter++;document.getElementById("newInvoiceItem").tabIndex++;}
function setFocus(elem){this.currentFieldOriginalBackgroundColor=elem.style.backgroundColor;elem.style.backgroundColor='rgb(245,193,174)';}
function leaveFocus(elem){elem.style.backgroundColor=currentFieldOriginalBackgroundColor;}
function madeChanges(){sendregning.namespace("invoice").changesHaveBeenMade=true;return true;}
function getTarget(evt){var node=(evt.target)?evt.target:((evt.srcElement)?evt.srcElement:null);return node;}
function preventEnter(evt){evt=(evt)?evt:((event)?event:null);if(evt){var kc=(evt.charCode)?evt.charCode:((evt.which)?evt.which:evt.keyCode);if(kc==13||kc==3){var srcElement=getTarget(evt);if(srcElement.nodeName=="INPUT"){currentTabIndex=srcElement.tabIndex;for(i=0;i<document.forms[0].elements.length;i++){if(document.forms[0].elements[i].tabIndex==currentTabIndex+1){$(document.forms[0].elements[i]).focus();}}}
if(srcElement.nodeName=='INPUT'&&(srcElement.type!="submit"&&srcElement.type!="reset")){if(evt.returnValue){evt.returnValue=false;}
else if(evt.preventDefault){evt.preventDefault();}
else{return false;}}}}}
function proposeInvoiceText(fakturaNumber){invText=document.getElementById("invoice_invoiceText");invText.value="Kreditnota for fakturanr. "+fakturaNumber;}
function estimateDueDate(){var selectDuePeriode=document.getElementById("id_duePeriode");if(selectDuePeriode){var estimatedDueDate=dateToString(calulateDueDate(getEstimatedShipmentDate(),selectDuePeriode.value));if(estimatedDueDate){selectDuePeriode.title="Estimert forfallsdato: "+estimatedDueDate;document.getElementById("giro_due_date").innerHTML=estimatedDueDate;}}}
function getEstimatedShipmentDate(){var elemNextDate=document.getElementById("id_invoiceTemplateNextDate");if(elemNextDate&&elemNextDate.value){return stringToDate(elemNextDate.value);}
else{var elemFirstDate=document.getElementById("id_invoiceTemplateFirstDate");if(elemFirstDate&&elemFirstDate.value){return stringToDate(elemFirstDate.value);}}
return null;}
function parseDynamicValues(elemName){var elemSource=document.getElementById(elemName);if(!elemSource){var elementsByName=document.getElementsByName(elemName);if(elementsByName[0]){elemSource=elementsByName[0];}}
var bySendDate=document.getElementById("bySendDate").checked;var baseDate=getEstimatedShipmentDate();if(!bySendDate){baseDate=calulateDueDate(baseDate,document.getElementById("id_duePeriode").value);}
var result="";if(elemSource){result=elemSource.value;}
else{alert("ERROR: Can't find element by id or name: '"+elemName+"'");}
if(baseDate){var weekNumber=getWeekNumber(baseDate);var monthName=getMonthName(baseDate);var quarterName=getQuarterName(baseDate);var yearName=getYear(baseDate);result=result.replace(/\[uke\]/gi,weekNumber);result=result.replace(/\[m�ned\]/gi,monthName);result=result.replace(/\[kvartal\]/gi,quarterName);result=result.replace(/\[�r\]/gi,yearName);}
return"<span style='white-space: nowrap'>"+result+"<\/span>";}
function checkDescription(elem){var itemsTable=document.getElementById(ITEMS_TABLE_NAME);var rowCount=itemsTable.rows.length;var divText="Beskrivelse mangler for linje : ";var showTooltip=false;var first=true;var i=0;for(i=0;i<=rowCount;i++){var rowId=i;var elemAmount=document.getElementsByName('ivo.invoiceItems['+rowId+'].invoiceItemQty')[0];var elemDescription=document.getElementsByName('ivo.invoiceItems['+rowId+'].invoiceItemDescription')[0];var elemUnitPrice=document.getElementsByName('ivo.invoiceItems['+rowId+'].invoiceItemUnitPrice')[0];if(elemAmount!=null&&elemAmount.value!=null&&elemAmount.value.length>0&&elemUnitPrice!=null&&elemUnitPrice.value!=null&&elemUnitPrice.value.length>0&&(elemDescription==null||elemDescription.value==null||elemDescription.value.length==0)){showTooltip=true;if(first==true){divText=divText+" "+(rowId+1);first=false;}else{divText=divText+", "+(rowId+1);}}}
if((showTooltip==true)&&(showDescriptionTooltipGlobal)){showTooltipDiv(divText);}else{hideTooltipDiv(false);}}
function showTooltipDiv(divText){var pos=$("#itemDescription\\[0\\]").offset();$("#tooltipDiv").css({"left":(pos.left+100)+"px","top":(pos.top-40)+"px"});$("#tooltipDiv").text(divText);$("#tooltipDiv").append('&nbsp;&nbsp;'+'<img src="/images/delete.png" width="14" height="14" vspace=2 style="vertical-align: top; border="0" onclick="hideTooltipDiv(true);" alt="X">');$("#tooltipDiv").show();}
function hideTooltipDiv(permanently){if(permanently){showDescriptionTooltipGlobal=false;}
$("#tooltipDiv").hide();}
function checkRecipient(){var name=$("#ivo\\.name").val();if(name==null||name.length==0||($("#ivo\\.name").attr("readonly")==true)){hideRecipientDiv();return}
var currentRecipientId=$("#ivo.recipientId").val();var foundRecipientsStore=new Ext.data.JsonStore({id:'recipientId',root:'recipients',totalProperty:'totalCount',fields:[{name:'recipientId',type:'int'},{name:'recipientNo',mtype:'string',convert:function(s){return unescape(s)}},{name:'name',type:'string',convert:function(s){return unescape(s)}},{name:'address1',type:'string',convert:function(s){return unescape(s)}},{name:'address2',type:'string',convert:function(s){return unescape(s)}},{name:'zip',type:'string',convert:function(s){return unescape(s)}},{name:'city',type:'string',convert:function(s){return unescape(s)}},{name:'country',type:'string',convert:function(s){return unescape(s)}},{name:'recipientEmail',type:'string',convert:function(s){return unescape(s)}},{name:'creditDays',type:'int'},{name:'discount',type:'string'},{name:'lost',type:'string'}],url:"/sr/ajax/recipientNameExists.do",baseParams:{name:name,currentRecipientId:currentRecipientId},listeners:{load:function(){var rows=this.getTotalCount();if(rows!=null&&rows>0){renderRecipientGrid(recipientGrid);}else{hideRecipientDiv();}},loadexception:function(proxy,options,response,error){isLoggedIn(response.responseText);}}});var recipientGrid=new Ext.grid.GridPanel({store:foundRecipientsStore,trackMouseOver:true,border:false,columns:[{header:'Nr',width:40,dataIndex:'recipientNo',sortable:false,resizable:false},{header:'Navn',dataIndex:'name',sortable:false,resizable:false},{header:'Adresse',dataIndex:'address1',sortable:false,resizable:false},{header:'Poststed',dataIndex:'city',sortable:false,resizable:false}],stripeRows:true,title:" ",autoHeight:true,sm:new Ext.grid.RowSelectionModel({singleSelect:true,listeners:{rowselect:function(smObj,rowIndex,record){copyRecipientToHeader(record);copyDatesToGiro();madeChanges();checkIfRecipientLost(record);Ext.get('dateInvoice').focus();hideRecipientDiv();}}})});foundRecipientsStore.load();}
function renderRecipientGrid(recipientGrid){$("#recipientDiv").text("");var totalCount=recipientGrid.store.getTotalCount();if(totalCount==1){recipientGrid.setTitle("Mente du denne kunden?");}else{recipientGrid.setTitle("Mente du \u00E5 velge en av disse kundene?");}
recipientGrid.render('recipientDiv');showRecipientDiv();}
function showRecipientDiv(){var pos=$("#ivo\\.name").offset();var height=$("#recipientDiv").height();$("#recipientDiv").css({"left":(pos.left+280)+"px","top":(pos.top-height/2)+"px"});$("#recipientDiv").append("<a href='' onclick='hideRecipientDiv(); return false'>Avbryt</a>");$("#recipientDiv").show();}
function hideRecipientDiv(){$("#recipientDiv").hide();}
function showDateWarning(elementToShow,nextToElement){var pos=nextToElement.offset();var textBoxHeight=nextToElement.height();var divHeight=elementToShow.height();var newTop=pos.top+(textBoxHeight/2)-((divHeight+8)/2);elementToShow.css({"right":(pos.left-435)+"px","top":newTop+"px"});elementToShow.addClass("sr-modal sr-modal-date");$(".sr-modal-date").hide();elementToShow.show();}
function hideDateWarning(elem){var $elementToHide=$("#"+elem);$elementToHide.hide();}
function checkDates(){sendregning.hints.date.order.checkOrderDate();sendregning.hints.date.due.checkDueDate();sendregning.hints.date.invoice.checkDateInvoice();}
function resetTime(dateToReset){dateToReset.setHours(0);dateToReset.setMinutes(0);dateToReset.setSeconds(0);dateToReset.setMilliseconds(0);}
var showAddressTooltip=true;function checkAddress1(addressFieldId){var addressFieldIdReplaced=addressFieldId.replace(".","\\.");var $address1=$("#"+addressFieldIdReplaced);if($address1.length&&$address1.val().length>0){hideAddressTooltipDiv();}else{showAddressTooltipDiv(addressFieldIdReplaced);}}
function showAddressTooltipDiv(addressFieldIdReplaced){if(showAddressTooltip==true){var address1=$("#"+addressFieldIdReplaced);var pos=address1.offset();var $addressToolTip=$("#addressTooltipDiv");var height=$addressToolTip.height();$addressToolTip.css({"left":(pos.left+275)+"px","top":((pos.top-height/2)+5)+"px"});$(".sr-modal-address").hide();$addressToolTip.addClass("sr-modal sr-modal-address");$addressToolTip.show();}}
function hideAddressTooltipDiv(){var $addressToolTip=$("#addressTooltipDiv");$addressToolTip.removeClass("sr-modal");$("#addressTooltipDiv").hide();}
function permanentHideAddressTooltipDiv(){showAddressTooltip=false;$("#addressTooltipDiv").hide();}
(function($){var $shoppingCart;var items=[];var headingTxt="";var totalPriceTxt="";var price=0;var selector;var isDebug;var formatter=sendregning.namespace("formatter");$.fn.shoppingCart=function(options){var opts=$.extend({},$.fn.shoppingCart.defaults,options);$shoppingCart=this;selector=this.selector;headingTxt=opts.title;totalPriceTxt=opts.totaltxt;isDebug=opts.debug;debug('Creating a shopping cart using: '+selector);return this;};function calculatePrice(){price=0;$.each(items,function(index,item){price=price+item.price;});return price;};function createHeading(){return $('<h3 class="center">'+headingTxt+'</h3>');}
function createBorderTop(){return $('<div class="borderTop"/>');}
function createBorderBottom(){return $('<div class="borderBottom"/>');}
function createProduct(item){var $borderTop=createBorderTop();var $borderBottom=createBorderBottom();var $productContent=$('<div class="shoppingCartItem" id="'+item.id+'"><span>'+item.description+'</span><span style="float:right" id="chosenSendMethodPrice">'+formatter.number2NorwegianMonetartyAmount(item.price)+'</span></div>')
return $borderTop.add($productContent).add($borderBottom);}
function createTotalPrice(item){calculatePrice();return $('<div id="totalPrice" class="section">'+'<span>'+totalPriceTxt+'</span>'+'<span style="float:right">'+formatter.number2NorwegianMonetartyAmount(price)+'</span>'+'</div>');}
function debug(message){if(isDebug&&window.console&&window.console.log){window.console.log(message);}};$.fn.shoppingCart.defaults={'debug':false};$.fn.shoppingCart.addProduct=function(id,description,price){items.push({'id':id,'description':description,'price':price});};$.fn.shoppingCart.removeProduct=function(id){items=$.grep(items,function(item){return item.id!=id;});};$.fn.shoppingCart.clear=function(){items=[];};$.fn.shoppingCart.draw=function(location){var $heading=createHeading();var $cartItems=$('<div class="shoppingCartItems"/>');$.each(items,function(index,item){var $product=createProduct(item);$cartItems=$cartItems.append($product);});var $totalPrice=createTotalPrice();$shoppingCart.html($heading.add($cartItems).add($totalPrice));return this;}})(jQuery);(function($){var $notificationMessage;var messages=[];var selector;var isDebug;var reallocDisplayType='REALLOC';var infoDisplayType='INFO';$.fn.fetchNotificationMessages=function(options){var opts=$.extend({},$.fn.fetchNotificationMessages.defaults,options);$notificationMessage=this;selector=this.selector;isDebug=opts.debug;debug('Fetching notification messages and displaying using: '+selector);fetchNotifications();this.subscribe('messagesLoaded',function(event,data){if(messages.length>0){$notificationMessage.each(function(){draw();});$notificationMessage.show();}});return this;};function fetchNotifications(){$.ajax({type:"GET",url:"/sr/ajax/notificationTop.do",dataType:"json",error:function(xhr,status,error){},success:function(data){if(data==null){$notificationMessage.hide();}else{var notificationCount=data.result.length;if(notificationCount==0){$notificationMessage.hide();}else if(notificationCount==1){messages=data.result;}
$notificationMessage.publish("messagesLoaded");}}});}
function markNotificationAsRead(messageId,update){$.ajax({async:false,type:"GET",url:"/sr/ajax/markNotificationAsRead.do",dataType:"json",data:{messageId:messageId},error:function(xhr,status,error){},success:function(data){var result=data.result.length;if(result==1){$.each(data.result,function(i,row){var status=unescape(row.status);if(status=='OK'){if(update){$notificationMessage.hide();fetchNotifications();}}});}}});}
function disableReallocNotification(){$.ajax({async:false,type:"GET",url:"/sr/ajax/disableNotification.do",dataType:"json",data:{displayType:reallocDisplayType},error:function(xhr,status,error){},success:function(data){var result=data.result.length;if(result==1){$.each(data.result,function(i,row){var status=unescape(row.status);if(status=='OK'){$notificationMessage.hide();fetchNotifications();}});}}});}
function draw(){$notificationMessage.addClass("messageContainer noPrint hidden");var $heading=createHeading();var $borderTop=createBorderTop();var $borderBottom=createBorderBottom();var $notificationMessages=createMessages();$notificationMessage.html($heading.append($borderTop).append($notificationMessages).append($borderBottom));return this;}
function createHeading(){var $heading=$('<div class="messageMask"/>');var displayType=unescape(messages[0].displayType);$heading.addClass(displayType);return $heading;}
function createBorderTop(){return $('<div class="borderTop"/>');}
function createBorderBottom(){return $('<div class="borderBottom"/>');}
function createMessages(){if(messages.length==1){var $notificationMessages=$('<div class="messages"/>');$.each(messages,function(index,message){var $message=createMessage(message);$notificationMessages=$notificationMessages.append($message);});return $notificationMessages;}
else{return"";}}
function createMessage(notification){var messageBody=unescape(notification.messageBody);var messageId=unescape(notification.messageId);var uniqueDomId='notifcation_'+messageId;var $table=$('<table id="'+uniqueDomId+'" />');var $tableRow=$('<tr/>');var $messageContent=$('<td class="notificationBody">'+messageBody+'</td>');var $messageLinks=createMessageLinks(notification);$("#"+uniqueDomId+" a.markable").live('click',function(){markNotificationAsRead(messageId,true);});$("#"+uniqueDomId+" a.disableRealloc").live('click',function(){disableReallocNotification();});return $table.append($tableRow.append($messageContent).append($messageLinks));}
function createMessageLinks(notification){var displayType=unescape(notification.displayType);var messageId=unescape(notification.messageId);var $links=$('<td class="notificationLinks"/>');var $linksList=$('<ul/>');if(displayType===reallocDisplayType){var $closeLink=$('<li><span class="nowrap"><a href="#" class="markable">Skjul denne meldingen</a></span></li>');var $disableUrl=$('<li><span class="nowrap"><a href="#" class="disableRealloc" >Ikke vis flere meldinger om AutoRydd</a></span></li>');$linksList.append($disableUrl).append($closeLink);}
else if(displayType===infoDisplayType){markNotificationAsRead(messageId,false);}
return $links.append($linksList);}
function debug(message){if(isDebug&&window.console&&window.console.log){window.console.log(message);}};$.fn.fetchNotificationMessages.defaults={'debug':false};$.fn.fetchNotificationMessages.clear=function(){messages=[];};})(jQuery);(function($){_subscribe_topics={};_subscribe_handlers={};_subscribe_getDocumentWindow=function(document){return document.parentWindow||document.defaultView;};$.fn.extend({createTopic:function(topic){if(topic&&!_subscribe_topics[topic]){_subscribe_topics[topic]={};_subscribe_topics[topic].objects={};_subscribe_topics[topic].objects['__noId__']=[];}
return this;},destroyTopic:function(topic){if(topic&&_subscribe_topics[topic]){for(i in _subscribe_topics[topic].objects){var object=_subscribe_topics[topic].objects[i];if($.isArray(object)){if(object.length>0){for(j in object){object[j].unbind(topic);}}}else{object.unbind(topic,data);}}}
delete _subscribe_topics[topic];return this;},subscribe:function(topic,handler,data){if(this[0]&&topic&&handler){this.createTopic(topic);if(this.attr('id')){_subscribe_topics[topic].objects[this.attr('id')]=this;}else{var noIdObjects=_subscribe_topics[topic].objects['__noId__'];if(this[0].nodeType==9){for(var index in noIdObjects){var noIdObject=noIdObjects[index];if(noIdObject[0].nodeType==9&&_subscribe_getDocumentWindow(this[0]).frameElement==_subscribe_getDocumentWindow(noIdObject[0]).frameElement){return this;}}}
var exists=false;for(var i=0;i<noIdObjects.length;i++){if(noIdObjects[i]==this){exists=true;break;}}
if(!exists){_subscribe_topics[topic].objects['__noId__'].push(this);}}
if(typeof(handler)=='function'){this.bind(topic,data,handler);}else if(typeof(handler)=='string'&&typeof(_subscribe_handlers[handler])=='function'){this.bind(topic,data,_subscribe_handlers[handler]);}}
return this;},unsubscribe:function(topic){if(topic){if(_subscribe_topics[topic]){if(this.attr('id')){var object=_subscribe_topics[topic].objects[this.attr('id')];if(object){delete _subscribe_topics[topic].objects[this.attr('id')];}}else{var noIdObjects=_subscribe_topics[topic].objects['__noId__'];for(var i=0;i<noIdObjects.length;i++){if(noIdObjects[i]==this){subscribe_topics[topic].objects['__noId__'].splice(index,1);break;}}}}
this.unbind(topic);}
return this;},publish:function(topic,data,originalEvent){if(topic){this.createTopic(topic);var subscriberStopPropagation=function(){this.isImmediatePropagationStopped=function(){return true;};(new $.Event).stopPropagation();if(this.originalEvent){this.originalEvent.isImmediatePropagationStopped=function(){return true;};this.originalEvent.stopPropagation=subscriberStopPropagation;}}
var event=jQuery.Event(topic);$.extend(event,{originalEvent:originalEvent,stopPropagation:subscriberStopPropagation});for(i in _subscribe_topics[topic].objects){var object=_subscribe_topics[topic].objects[i];if($.isArray(object)){if(object.length>0){for(j in object){object[j].trigger(event,data);}}}else{object.trigger(event,data);}}}
return this;},publishOnEvent:function(event,topic,data){if(event&&topic){this.createTopic(topic);this.bind(event,data,function(e){$(this).publish(topic,e.data,e);});}
return this;}});$.extend({subscribe:function(topic,handler,data){return $().subscribe(topic,handler,data);},unsubscribe:function(topic,handler,data){return $().unsubscribe(topic,handler,data);},subscribeHandler:function(name,handler){if(name&&handler&&typeof(handler)=="function"){_subscribe_handlers[name]=handler;}
return $();},publish:function(topic,data){return $().publish(topic,data);},createTopic:function(topic){return $().createTopic(topic);},destroyTopic:function(topic){return $().destroyTopic(topic);}});})(jQuery);(function($){$.fn.salesLedger=function(invoiceId,options){debug('Applying salesLedger to: '+this.size()+' elements');var opts=$.extend({},$.fn.salesLedger.defaults,options);var selector=this.selector;debug(selector);this.each(function(){setup($(this),invoiceId,opts,selector);});return this;};$.fn.widgetify=function(invoiceId,options){var opts=$.extend({},$.fn.widgetify.defaults,options);this.each(function(){widgetify($(this),opts);});return this;};function widgetify(widget,opts){var form=$('form',widget);form.submit(function(event){var $this=$(this);event.preventDefault();$.post("/salesledger/ajax/"+$this.attr('action'),$this.serialize(),function(data){widget.html(data);});return false;});}
function setup($this,invoiceId,opts,selector){var configuration=$.meta?$.extend({},opts,$this.data()):opts;var salesledgerBody=$(".salesLedgerBody",$this);if(salesledgerBody.length==0){$this.prepend("<div class='salesLedgerMessage' style='display:none'></div><div class='salesLedgerBody'></div>")
salesledgerBody=$(".salesLedgerBody",$this);}
debug(salesledgerBody.data('loaded'));if(!salesledgerBody.data('loaded')){salesledgerBody.html("");salesledgerBody.data('changed',false);load(invoiceId,salesledgerBody,configuration);$('#fancybox-inner a.closePopup').live('click',function(event){event.preventDefault();$.fancybox.close();});$this.subscribe('widgetLoaded',function(event,data){});$this.subscribe('widgetComplete',function(event,data){debug("widget complete");if(data.invoiceId===invoiceId){salesledgerBody.data('changed',true);if(configuration.autoClose){window.setTimeout(function(){$.fancybox.close();},configuration.autoCloseTimeout);}
$('.salesLedgerMessage',$this).html(data.message).show();}});salesledgerBody.subscribe('reloadSalesLedger',function(event,data){$.fn.salesLedger.reload($this,invoiceId,configuration,event,data);});}else{handleCallbacks($this,invoiceId,configuration);}}
function debug(message){if($.fn.salesLedger.defaults.debug&&window.console&&window.console.log){window.console.log(message);}};function load(invoiceId,salesledgerBody,configuration){salesledgerBody.load(configuration.endpoint+'?invoiceId='+invoiceId+'&template='+configuration.template+'&noskin',function(response,status,xhr){if(status=="error"){salesledgerBody.html("<div class='fields error'><span>Feil, Saldooversikt for denne regningen er ikke tilgjengelig</span></div>");handleCallbacks(salesledgerBody,invoiceId,configuration);return;}
salesledgerBody.data('loaded',true);var popupLinks=$("a.imagePopup",salesledgerBody);popupLinks.fancybox({type:'ajax',closeClick:false,afterLoad:function(){$("#fancybox-inner").css({'overflow-x':'hidden'});salesledgerBody.publish("widgetLoaded",invoiceId);},beforeClose:function(){if(salesledgerBody.data('changed')){salesledgerBody.publish("reloadSalesLedger",invoiceId);}}});handleCallbacks(salesledgerBody,invoiceId,configuration);if(configuration.animate){salesledgerBody.effect("highlight",{times:1},1000);}});}
function handleCallbacks($this,invoiceId,configuration){debug("loaded");if($.publish){$this.publish("salesledgerLoaded",invoiceId);}else{}
configuration.callback($this);}
$.fn.salesLedger.callback=function(element){};$.fn.salesLedger.reload=function($this,invoiceId,configuration,event,data){if(data===invoiceId){load(invoiceId,$(".salesLedgerBody",$this),configuration);}};$.fn.salesLedger.defaults={'debug':false,'autoClose':true,'autoCloseTimeout':0,'template':'editableSalesLedger','callback':$.fn.salesLedger.callback,'endpoint':'/salesledger/ajax/viewSalesLedger','reload':$.fn.salesLedger.reload,'animate':true};$.fn.widgetify.defaults={}})(jQuery);(function($,sr){"use strict";var $invoice;var selector;var isDebug;var opts;var MODAL_WINDOW_WIDTH="900px";var showDescriptionTooltipGlobal=true;var isIE=(navigator.appName.indexOf("Microsoft")!=-1);var origCreditDays;var creditedInvoiceNo;var CREDIT_INVOICE_DATE;var MAX_ITEMS_IN_VIEW=19;var ITEMS_TABLE_NAME="tblFakturaLinjer";var strutsPattern="(invoiceDetails\\[)(\\d+)(\\].\\w+)";var namePattern=new RegExp(strutsPattern);var elementIdPattern="^(item[a-zA-Z]+\\[)(\\d+)(\\])$";var currentInvoice=new TInvoice(0,0,0);var tabIndexCounter=17
var recipientLost=false;;var numberOfRecipients=0;if(!Number.prototype.toFixed){Number.prototype.toFixed=function(n){var x=Math.pow(10,n);var y=(Math.round(this*x)/x);return y.toString();}}
var proposedRecipientNo=false;$.fn.invoice=function(options){opts=$.extend({},$.fn.invoice.defaults,options);numberOfRecipients=opts.numberOfRecipients;origCreditDays=opts.origCreditDays;creditedInvoiceNo=opts.creditedInvoiceNo;CREDIT_INVOICE_DATE=opts.creditInvoiceDate;$invoice=this;selector=this.selector;isDebug=opts.debug;init();return this;};function init(){debug("Running init");Ext.BLANK_IMAGE_URL='/images/ext/default/s.gif';document.onkeydown=preventEnter;setUpRecipientForm();var $lostRecipientInfo=$("#invoiceRecipientLost");if($lostRecipientInfo.val()=='true'){$lostRecipientInfo.show();}else{$lostRecipientInfo.hide();}
$("input, textarea").addClass("idle");$("input, textarea").focus(function(){$(this).addClass("activeField").removeClass("idle");}).blur(function(){$(this).removeClass("activeField").addClass("idle");});$("input[name='action:saveAndSendDraftSalesDocument']").click(function(){var result=validate_form();return result;});setUpCalendars();if(creditedInvoiceNo!=''){setUpCreditInvoice();}
calcTotal();copyDatesToGiro();estimateDueDate();return true;}
function setUpRecipientForm(){displayRecipientSearchCombo();var $recipientIdElem=$('#recipientIdField');if($recipientIdElem.val()!=""){setReadOnly($("#recipientNoField"));setReadOnly($("#nameField"));setReadOnly($("#address1Field"));setReadOnly($("#address2Field"));setReadOnly($("#zipField"));setReadOnly($("#cityField"));setReadOnly($("#countryField"));setReadOnly($("#recipientEmailField"));$("#namesearchdiv").hide();copyAddressToGiro();if(Ext.get('x-button')!=null){Ext.get('x-button').setVisible(true,true);}
$('#dateInvoice').focus();}
else{if(numberOfRecipients>0){$("#namesearchdiv").show();$("#ajaxRecipientNameSearch").focus();}
else{$('#recipientNoField').focus();}
if($("#recipientNoField").val()!=null){proposedRecipientNo=true;}}}
function displayRecipientSearchCombo(){var recipientStore=new Ext.data.JsonStore({id:'recipientId',root:'recipients',totalProperty:'totalCount',fields:[{name:'recipientId',type:'int'},{name:'recipientNo',mtype:'string',convert:function(s){return unescape(s)}},{name:'name',type:'string',convert:function(s){return unescape(s)}},{name:'address1',type:'string',convert:function(s){return unescape(s)}},{name:'address2',type:'string',convert:function(s){return unescape(s)}},{name:'zip',type:'string',convert:function(s){return unescape(s)}},{name:'city',type:'string',convert:function(s){return unescape(s)}},{name:'country',type:'string',convert:function(s){return unescape(s)}},{name:'recipientEmail',type:'string',convert:function(s){return unescape(s)}},{name:'creditDays',type:'int'},{name:'discount',type:'string'},{name:'lost',type:'string'}],url:'/sr/ajax/recipientNameSearchFromInvoice.do',listeners:{loadexception:function(proxy,options,response,error){isLoggedIn(response.responseText);}}});var searchRecipientNameCombo=new Ext.form.ComboBox({store:recipientStore,displayField:'name',id:'ajaxRecipientNameSearchCombo',emptyText:'Velg fra kundeliste...',listEmptyText:'Ingen treff...',loadingText:'S&oslash;ker...',forceSelection:true,pageSize:15,resizable:true,selectOnFocus:true,triggerAction:'all',minChars:2,shadow:'drop',minListWidth:250,applyTo:'ajaxRecipientNameSearch',listeners:{select:function(combo,record,index){copyRecipientToHeader(record);copyDatesToGiro();madeChanges();checkIfRecipientLost(record);combo.lastQuery=null;Ext.get('dateInvoice').focus();}}});}
function copyRecipientToHeader(recipient){if(recipient!=null){$("#namesearchdiv").hide();try{var recip=recipient.get("recipientNo");}
catch(exception){var recip=unescape(recipient.recipientNo);}
var $ivoRecipNo=$("#recipientNoField");$ivoRecipNo.val(recip);setReadOnly($ivoRecipNo);var $ivoName=$("#nameField");try{$ivoName.val(recipient.get("name"));}
catch(exception){$ivoName.val(unescape(recipient.name));}
setReadOnly($ivoName);var $ivoAddress1=$("#address1Field");try{$ivoAddress1.val(recipient.get("address1"));}
catch(exception){$ivoAddress1.val(unescape(recipient.address1));}
setReadOnly($ivoAddress1);var $ivoAddress2=$("#address2Field");try{$ivoAddress2.val(recipient.get("address2"));}
catch(exception){$ivoAddress2.val(unescape(recipient.address2));}
setReadOnly($ivoAddress2);var $ivoZip=$("#zipField");try{$ivoZip.val(recipient.get("zip"));}
catch(exception){$ivoZip.val(unescape(recipient.zip));}
setReadOnly($ivoZip);var $ivoCity=$("#cityField");try{$ivoCity.val(recipient.get("city"));}
catch(exception){$ivoCity.val(unescape(recipient.city));}
setReadOnly($ivoCity);var $ivoCountry=$("#countryField");try{$ivoCountry.val(recipient.get("country"));}
catch(exception){$ivoCountry.val(unescape(recipient.country));}
setReadOnly($ivoCountry);var $ivoRecipientEmail=$("#recipientEmailField");try{var recipientEmail=recipient.get("recipientEmail");}
catch(exception){var recipientEmail=unescape(recipient.recipientEmail);}
if(recipientEmail==null||recipientEmail==""||recipientEmail=="null"){$ivoRecipientEmail.val("");}
else{$ivoRecipientEmail.val(recipientEmail);}
setReadOnly($ivoRecipientEmail);var $recipientIdField=$("#recipientIdField");try{var recipientId=recipient.get("recipientId");}
catch(exception){var recipientId=unescape(recipient.recipientId);}
if(recipientId!=null&&recipientId>0){$recipientIdField.val(recipientId);}
else{$recipientIdField.val(null);}
try{var creditDays=recipient.get("creditDays");}
catch(exception){var creditDays=unescape(recipient.creditDays);}
var newDueDate=addDays(new Date(),creditDays);if(newDueDate!=null){var $dateDue=$("#dateDue");if($dateDue.length){$dateDue.val(dateToString(newDueDate));}}
try{var recipientDiscount=recipient.get("discount");}
catch(exception){var recipientDiscount=unescape(recipient.discount)}
$("#recipientDiscount").val(recipientDiscount);Ext.get('x-button').setVisible(true,true);Ext.getCmp('ajaxRecipientNameSearchCombo').disable();updateItemsDiscounts();$("#dateInvoice").focus();}
else
if(recipient==null){removeReadOnly($("#recipientNoField"));removeReadOnly($("#nameField"));removeReadOnly($("#address1Field"));removeReadOnly($("#address2Field"));removeReadOnly($("#zipField"));removeReadOnly($("#cityField"));removeReadOnly($("#countryField"));removeReadOnly($("#recipientEmailField"));$("#namesearchdiv").show();$("#recipientIdField").val('');$("#countryField").val("NORGE");$("#recipientDiscount").val("");var $dateDueElement=$("#dateDue");$dateDueElement.val(dateToString(addDays(new Date(),null)));Ext.get('x-button').setVisible(false,true);Ext.getCmp('ajaxRecipientNameSearchCombo').enable();Ext.get('ajaxRecipientNameSearch').dom.value='';$("#lostRecipientInfo").hide();$('#ajaxRecipientNameSearch').focus();}
copyAddressToGiro();calcTotal();}
function findNextRecipientNo(event){var keynum;if(window.event){keynum=event.keyCode;}
else if(event.which){keynum=event.which;}
if(keynum&&keynum==39){Ext.Ajax.request({url:'/sr/ajax/getNextRecipientNo.do',method:'GET',success:function(response,opt){if(isLoggedIn(response.responseText)){if(response.responseText.length>0){var next=Ext.util.JSON.decode(response.responseText);Ext.get('recipientNoField').dom.value=next.next;proposedRecipientNo=true;$('#nameField').focus();}}},failure:function(response,opt){Ext.MessageBox.alert('Failed, response code='+response.status,response.responseText);}});}
else{proposedRecipientNo=false;}}
function findRecipientByRecipientNo(elem){if(elem!=null&&elem.value.length>0&&!proposedRecipientNo){Ext.get('recipientGroup').mask('S&oslash;ker etter kundenr: '+elem.value,'x-mask-loading');Ext.Ajax.request({url:'/sr/ajax/recipientNoLookup.do',params:{query:elem.value},method:'GET',callback:function(){Ext.get('recipientGroup').unmask();},success:function(response,opt){if(isLoggedIn(response.responseText)){copyRecipientToHeader(Ext.util.JSON.decode(response.responseText));copyDatesToGiro();checkIfRecipientLost(Ext.util.JSON.decode(response.responseText));madeChanges();}},failure:function(response,opt){Ext.MessageBox.alert('Failed, response code='+response.status,response.responseText);}});}
else{$("#recipientIdField").val('');$("#recipientDiscount").val('');}
proposedRecipientNo=false;return true;}
function findProductByProductNo(elem){if(elem!=null&&elem.value!=null&&elem.value.length>0){if(!Ext.isIE7){Ext.get('invoiceLines').mask('S&oslash;ker etter produktnr: '+elem.value,'x-mask-loading');}
Ext.Ajax.request({url:'/sr/ajax/productNoLookup.do',params:{query:elem.value},method:'GET',callback:function(){if(!Ext.isIE7){Ext.get('invoiceLines').unmask();}},success:function(response,opt){if(isLoggedIn(response.responseText)){copyProductToInvoiceLine(elem.parentNode.parentNode,Ext.util.JSON.decode(response.responseText));}},failure:function(response,opt){Ext.MessageBox.alert('Failed, response code='+response.status,response.responseText);}});}
else{return null;}}
function copyProductToInvoiceLine(row,product){if(row!=null&&product!=null){findInputElementInInvoiceItemRow(row,'itemProdCode').value=unescape(product.productNo);findInputElementInInvoiceItemRow(row,'itemDescription').value=unescape(product.productDesc);findInputElementInInvoiceItemRow(row,'itemUnitPrice').value=unescape(product.salesPrice);findInputElementInInvoiceItemRow(row,'itemTax').value=unescape(product.taxRate);var recipientDiscount=$("#recipientDiscount").val();if(recipientDiscount!=null&&recipientDiscount!="0"&&recipientDiscount!="0.00"){findInputElementInInvoiceItemRow(row,'itemDiscount').value=$("#recipientDiscount").val();}else{findInputElementInInvoiceItemRow(row,'itemDiscount').value="";}
calcItem(findInputElementInInvoiceItemRow(row,'itemUnitPrice'));if(findInputElementInInvoiceItemRow(row,'itemQty').value.length==0){$(findInputElementInInvoiceItemRow(row,'itemQty')).focus();}
else{$(findInputElementInInvoiceItemRow(row,'itemDescription')).focus();}
madeChanges();}}
function updateDiscount(elem,update){var itemsTable=document.getElementById(ITEMS_TABLE_NAME);var rowId=elem.parentNode.parentNode.rowIndex-1;var priceValue=$("#itemUnitPrice\\["+rowId+"\\]").val();if(priceValue==null||priceValue.length==0){$("#itemDiscount\\["+rowId+"\\]").val("");}else{var currentDiscount=$("#itemDiscount\\["+rowId+"\\]").val();if(currentDiscount!=null&&currentDiscount.length>0&&!update){return;}
copyDiscountFromRecipientToItem(rowId);}}
function updateItemsDiscounts(){var itemsTable=document.getElementById(ITEMS_TABLE_NAME);var i=0;var rowCount=itemsTable.rows.length;for(i=0;i<=rowCount;i++){var rowId=i;var elemAmount=document.getElementsByName('itemDiscount['+rowId+'].itemQty')[0];var elemUnitPrice=document.getElementsByName('itemDiscount['+rowId+'].itemUnitPrice')[0];if(elemAmount!=null&&elemAmount.value!=null&&elemAmount.value.length>0&&elemUnitPrice!=null&&elemUnitPrice.value!=null&&elemUnitPrice.value.length>0){copyDiscountFromRecipientToItem(rowId);}}}
function copyDiscountFromRecipientToItem(rowId){var recipientDiscount=$("#recipientDiscount").val();if(recipientDiscount!=null&&recipientDiscount!="0"&&recipientDiscount!="0.00"){$("#itemDiscount\\["+rowId+"\\]").val(recipientDiscount);}else{$("#itemDiscount\\["+rowId+"\\]").val("");}}
function checkIfRecipientLost(recipient){if(recipient!=null){try{recipientLost=recipient.get("lost");}
catch(exception){recipientLost=unescape(recipient.lost);}
if(recipientLost=='true'){$("#lostRecipientInfo").show();}else{$("#lostRecipientInfo").hide();}}}
function validate_form(){var alertMessage="";if($("#nameField").val().length==0){alertMessage='<li>Mottakers navn</li>';}
if($("#zipField").val().length==0){alertMessage=alertMessage+'<li>Mottakers postnummer</li>';}
else
if($("#zipField").val().length<4){alertMessage=alertMessage+'<li>Mottakers postnummer</li>';}
if($("#cityField").val().length==0){alertMessage=alertMessage+'<li>Mottakers poststed</li>';}
if($("#dateInvoice").val().length==0){alertMessage=alertMessage+'<li>Fakturadato</li>';}
if(creditedInvoiceNo==""){if($("#dateDue").val().length==0){alertMessage=alertMessage+'<li>Forfallsdato</li>';}}
if(alertMessage.length>0){var niceMessage='F&oslash;lgende felter m&aring; fylles ut for &aring; g&aring; videre:';Ext.MessageBox.show({minWidth:300,title:niceMessage,msg:'<div><ul>'+alertMessage+'</ul></div>',icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});return false;}
return true;}
function post_event(el,invoiceEventName){if(invoiceEventName!="cancel"&&validate_form()==false)
return false;var $eventField=$("#invoiceEvent");if(!$eventField){throw"HTML Field 'invoiceEvent' not found";}
$eventField.value=invoiceEventName;return true;}
function updateIdenticalEventAndChangeFormAction(identicalEventName,newFormAction){var $identicalEventNameField=$("#identicalEventName");if(!$identicalEventNameField){throw"HTML field named 'identicalEventName' not found...";}
$identicalEventNameField.value=identicalEventName;document.forms[0].action=newFormAction;return true;}
function changeFormAction(newFormAction){document.forms[0].action=newFormAction;return true;}
function TInvoice(total,tax,roundingTotal){this.invoiceTotal=total;this.invoiceTax=tax;this.roundingTotal=roundingTotal;this.mvaGroups=new Object();this.mvaGrunlagGroups=new Object();}
function Titem(total,tax,itemTaxRate){this.itemTotal=total;this.itemTax=tax;this.totalWithoutTax=total-tax;this.itemTaxRate=itemTaxRate;}
function dateToString(d){if(d){var day=d.getDate();var month=d.getMonth();var year=d.getFullYear()-2000;month+=1;day=day+'';month=month+'';year=year+'';if(day.length==1){day="0"+day;}
if(month.length==1){month="0"+month;}
if(year.length==1){year="0"+year;}
return day+'.'+month+'.'+year;}
return"";}
function stringToDate(s){var year=s.substr(6,2);var month=Number(s.substr(3,2));var date=Number(s.substr(0,2));month-=1;var newYear="20"+year;var result=new Date();result.setDate(date);result.setMonth(month);result.setFullYear(Number(newYear));return result;}
function addDays(myDate,days){if(days===null||days==="null"||days===""){days=origCreditDays;}
var D=myDate;var daysToAdd=Number(days);var daysInDate=Number(D.getDate());var totalDays=daysInDate+daysToAdd;D.setDate(totalDays);return D;}
function copyDatesToGiro(){var $dateDue=$("#dateDue");if($dateDue.length){$("#giro_due_date").html($dateDue.val());$("#giro_invoice_date").html($("#dateInvoice").val());}}
function isValidNumber(elem,fieldName,min,max){if(elem!=null&&elem.value!=null&&elem.value.length>0){var n=field2Number(elem);if(!isNaN(n)){if(min!=null){if(n<min){Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Verdien i feltet '"+fieldName+"' kan ikke v&aelig;re mindre enn: "+min,icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}
if(max!=null){if(n>max){Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Verdien i feltet '"+fieldName+"' kan ikke v&aelig;re st&oslash;rre enn: "+max,icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}
var splitArray=string2NumberString(elem.value).split(".");if(splitArray.length>1){if(splitArray[1].length>2){Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Et tall kan bare inneholde to desimaltegn",icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}
return true;}
else{Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Feltet '"+fieldName+"' kan kun inneholde et heltall eller et desimaltall!<br />F.eks: 1, 10, eller 0,5.",icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}}
function isValidPositiveNumber(elem,fieldName,max){if(elem!=null&&elem.value!=null&&elem.value.length>0){var splitArray=string2NumberString(elem.value).split(".");if(splitArray.length>1){if(splitArray[1].length>2){Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Et tall kan bare inneholde to desimaltegn",icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}
var n=field2Number(elem);if(!isNaN(n)&&n>=0){if(max!=null){if(n>max){Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Verdien i feltet '"+fieldName+"' kan ikke v&aelig;re st&oslash;rre enn: "+max,icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}
return true;}
else{Ext.MessageBox.show({minWidth:300,title:'Noe m&aring; rettes for &aring; g&aring; videre',msg:"Feltet '"+fieldName+"' kan kun inneholde et positivt heltall eller et desimaltall!<br />F.eks: 1, 10 eller 0,5<p>Ikke bruk komma eller punktum som tusentegnskille</p>",icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});if(!Ext.isIE&&!Ext.isOpera){elem.focus();}
return false;}}}
function copyAddressToGiro(){try{var $PaidByBox=$("#PaidByBox");var fields=["#nameField","#address1Field","#address2Field","#zipField","#cityField","#countryField"];var delimiter="";var newInnerHtml="";for(var i=0;i<fields.length;i++){var fieldValue;var $field=$(fields[i]);if($field.val()!="")
newInnerHtml+=delimiter+$field.val();if(fields[i]==="#zipField"){delimiter=" ";}
else{delimiter="<br>";}}
$PaidByBox.html("<p class=\"giro_address\">"+newInnerHtml+"</p>");}
catch(ex){alert("Det oppstod en intern feil i copyAddressToGiro() :- \n"+ex);}}
function lookupProduct(elem){var productStore=new Ext.data.JsonStore({id:'productNo',root:'products',totalProperty:'totalCount',fields:[{name:'productNo',mtype:'string',convert:function(s){return unescape(s)}},{name:'productDesc',type:'string',convert:function(s){return unescape(s)}},{name:'salesPrice',type:'string',convert:function(s){return unescape(s)}},{name:'taxRate',type:'string',convert:function(s){return unescape(s)}}],url:'/sr/ajax/productList.do',listeners:{loadexception:function(proxy,options,response,error){isLoggedIn(response.responseText);}}});var productPagingBar=new Ext.PagingToolbar({pageSize:10,store:productStore,displayInfo:true,displayMsg:'Viser {0} - {1} av {2} produkter',emptyMsg:"Ingen produkter i produktlisten...",items:['-',{text:'Avbryt',cls:'x-btn',handler:function(button,event){productListWindow.close();}}]});var productGridPanel=new Ext.grid.GridPanel({height:250,store:productStore,stripeRows:true,trackMouseOver:true,loadMask:true,autoExpandColumn:'pd',bbar:productPagingBar,viewConfig:{deferEmptyText:true,emptyText:'Ingen produkter i produktlisten...'},columns:[{header:"Produktnr",dataIndex:'productNo',sortable:true},{header:"Beskrivelse",dataIndex:'productDesc',sortable:true,id:"pd"},{header:"Enhetspris",dataIndex:'salesPrice',sortable:true},{header:"MVA",dataIndex:'taxRate',sortable:true}],sm:new Ext.grid.RowSelectionModel({singleSelect:true}),listeners:{rowclick:function(grid,rowIndex,event){var record=grid.getStore().getAt(rowIndex);var product=new Object();product.productNo=record.get('productNo');product.productDesc=record.get('productDesc');product.salesPrice=record.get('salesPrice');product.taxRate=record.get('taxRate');copyProductToInvoiceLine(elem.parentNode.parentNode,product);productListWindow.close();}}});var productSearchPanel=new Ext.form.FormPanel({height:50,bodyStyle:'padding: 5px 5px 0',xtype:'form',id:'asset-form',layout:'hbox',frame:true,collapsed:false,tbar:[new Ext.Toolbar.TextItem("S\u00F8k etter:"),{xtype:'textfield',fieldLabel:'Search',name:'pattern',id:'pattern'},{xtype:'tbseparator'},new Ext.Toolbar.Button({text:'S\u00F8k',iconCls:'search-icon',handler:function search_submit(){productStore.baseParams={pattern:$("#patternField").value};productStore.load({params:{start:0,limit:10}});}}),{xtype:'tbseparator'},new Ext.Toolbar.Button({text:'Nullstill s\u00F8k',iconCls:'reload-icon',handler:function(){var s=Ext.getCmp('pattern');s.setValue('');productStore.baseParams={pattern:$("#patternField").value};productStore.load({params:{start:0,limit:10}});}})]});var productListWindow=new Ext.Window({height:335,width:600,autoScroll:true,closeable:true,constrain:true,title:'Velg produkt ved &aring; klikke p&aring; produktet...',modal:true,layout:'anchor',items:[productSearchPanel,productGridPanel],listeners:{show:function(comp){productStore.load({params:{start:0,limit:10}});}}});productListWindow.show(elem);}
function setUpCalendars(){$("#dateInvoice").datepicker();$("#orderDate").datepicker();if(creditedInvoiceNo==""){$("#dateDue").datepicker();}}
function setUpCreditInvoice(){$('#dateDue').attr('disabled','');$('#dateDue').val(CREDIT_INVOICE_DATE);proposeInvoiceText(creditedInvoiceNo);$('#x-button').hide();}
function calcItem(currentInput){var s=currentInput.value.replace(/\./g,",");currentInput.value=s;var currentCell=currentInput.parentNode;var currentRow=currentCell.parentNode;if(currentRow.tagName!="TR"){alert('Ooops, unable to find row: '+currentRow.tagName);}
else{calcTotal();}}
function calcTotal(){var invoiceNetValue=0;currentInvoice.invoiceTotal=0.0;currentInvoice.invoiceTax=0.0;currentInvoice.invoiceTotalEksMva=0.0;currentInvoice.roundingTotal=0.0;currentInvoice.mvaGroups=new Object();currentInvoice.mvaGrunlagGroups=new Object();try{var $tbody=$("#invoiceItems");if(!$tbody){throw'Unable to find the TBODY "invoiceItems"';}
$tbody.children("tr").each(function(index){var item=calcRow($(this).get(0));currentInvoice.invoiceTotal+=item.itemTotal;currentInvoice.invoiceTax+=item.itemTax;currentInvoice.invoiceTotalEksMva+=item.totalWithoutTax;if(item.itemTotal!=0){if(currentInvoice.mvaGroups[item.itemTaxRate]==null){currentInvoice.mvaGrunlagGroups[item.itemTaxRate]=item.totalWithoutTax;currentInvoice.mvaGroups[item.itemTaxRate]=item.itemTax;}
else{currentInvoice.mvaGrunlagGroups[item.itemTaxRate]+=item.totalWithoutTax;currentInvoice.mvaGroups[item.itemTaxRate]+=item.itemTax;}}});var roundedTaxAmount=0.0;for(var x in currentInvoice.mvaGroups){roundedTaxAmount+=new Number(currentInvoice.mvaGroups[x].toFixed(2));}
var roundedTotalEksMva=new Number(currentInvoice.invoiceTotalEksMva.toFixed(2));var roundedTaxTotal=new Number(roundedTaxAmount.toFixed(2));var roundedTotal=new Number(currentInvoice.invoiceTotal.toFixed(2));var roundingAmount=roundedTotal-(roundedTotalEksMva+roundedTaxTotal);currentInvoice.roundingTotal=roundingAmount;if(!isNaN(currentInvoice.invoiceTotal)){invoiceNetValue=currentInvoice.invoiceTotal-currentInvoice.invoiceTax;var $netValue=$("#netValue");generateMvaString($netValue,currentInvoice.mvaGrunlagGroups);var $totalTax=$("#totalTax");generateMvaString($totalTax,currentInvoice.mvaGroups);var paymentIntegerPart=new Number(currentInvoice.invoiceTotal.toFixed(2));var grandTotal=formatCurrency(currentInvoice.invoiceTotal,""," ",",");var payKroner=grandTotal.substring(0,grandTotal.indexOf(","));var payOre=grandTotal.substring(grandTotal.indexOf(",")+1);var $grandTotElement=$("#grandTotal")
$grandTotElement.html(grandTotal);if(currentInvoice.roundingTotal.toFixed(2)==0){$("#roundingContainer").hide();}
else{$("#roundingContainer").show();}
var roundingTotal=formatCurrency(currentInvoice.roundingTotal,""," ",",");var roundingTotalElement=document.getElementById("roundingTotalSum");roundingTotalElement.innerHTML=roundingTotal;$("#payOre").html(payOre);$("#payKroner").html(payKroner);return currentInvoice.invoiceTotal;}}
catch(e){var x="";for(var p in e){x+='\n\t'+p+':'+e[p];}
alert('INTERNFEIL I001:'+'calcTotal() :- '+x!=""?x:e);return null;}
return null;}
function generateMvaString($element,mvagroups){if($element){var netValStr="";var size=0;for(var x in mvagroups){if(mvagroups[x]==0){continue;}
if(size!=0){netValStr+=" ";}
netValStr+=x+"%: "
netValStr+=formatCurrency(mvagroups[x],""," ",",");size++;}
if(netValStr==""){netValStr="0,00";}
$element.html(netValStr);}}
function findInputElementInInvoiceItemRow(row,elemName){var $elm=$("[id^="+elemName+"]",$(row));if(!$elm.length){alert("Returning null when looking for: "+elemName);}
return $elm.get(0);}
function calcRow(rowToCalc){var itemQty=0;var itemUnitPrice=0;var itemDiscount=0;var itemTaxRate=0;var itemTax=0;var itemTotal=new Number(0);var totalCell=null;itemQty=field2Number(findInputElementInInvoiceItemRow(rowToCalc,'itemQty'));itemUnitPrice=field2Number(findInputElementInInvoiceItemRow(rowToCalc,'itemUnitPrice'));itemDiscount=field2Number(findInputElementInInvoiceItemRow(rowToCalc,'itemDiscount'));itemTaxRate=field2Number(findInputElementInInvoiceItemRow(rowToCalc,'itemTax'));totalCell=findInputElementInInvoiceItemRow(rowToCalc,'itemTotal');itemTotal=((itemQty*itemUnitPrice)*(100-itemDiscount)/100);itemTax+=itemTotal*(itemTaxRate)/100;itemTotal+=itemTax;var displayFigure=itemTotal;var $itemTaxInclude=$("#itemTaxInclude");if($itemTaxInclude.val()!=null&&$itemTaxInclude.val().match(/false/i)){displayFigure=itemTotal-itemTax;}
if(totalCell!=null){if(itemTotal!=null&&!isNaN(itemTotal)){totalCell.value=(displayFigure!=0)?formatCurrency(displayFigure,""," ",","):"0,00";}
else{totalCell.value="";}}
return(new Titem(itemTotal,itemTax,itemTaxRate));}
function addAnotherInvoiceItem(){var itemsTable=document.getElementById(ITEMS_TABLE_NAME);if(!itemsTable){throw"Intern feil: fant ikke '"+ITEMS_TABLE_NAME+"'";}
if(itemsTable.rows.length>=MAX_ITEMS_IN_VIEW){Ext.MessageBox.show({minWidth:300,title:'Advarsel',msg:"Beklager, det er en begrensning p&aring; "+(MAX_ITEMS_IN_VIEW-1)+" fakturalinjer pr. faktura",icon:Ext.MessageBox.WARNING,buttons:Ext.MessageBox.OK,cls:'sr-alert'});return false;}
var lastRow=itemsTable.rows[itemsTable.rows.length-1];if(!lastRow){alert("Unable to find last row");}
var newRow=itemsTable.insertRow(itemsTable.rows.length);$(newRow).addClass("invoiceItem");for(var i=0;i<lastRow.cells.length;i++){var newCell=newRow.insertCell(i);newCell.innerHTML=new String(lastRow.cells[i].innerHTML);}
renumberAndUpdateTabIndexForInvoiceItemElements(itemsTable);findInputElementInInvoiceItemRow(newRow,'itemQty').value='';findInputElementInInvoiceItemRow(newRow,'itemProdCode').value='';findInputElementInInvoiceItemRow(newRow,'itemDescription').value='';findInputElementInInvoiceItemRow(newRow,'itemUnitPrice').value='';findInputElementInInvoiceItemRow(newRow,'itemDiscount').value='';findInputElementInInvoiceItemRow(newRow,'itemTotal').value='';$(findInputElementInInvoiceItemRow(newRow,'itemQty')).focus();return true;}
function removeInvoiceItem(elem){var itemsTable=document.getElementById(ITEMS_TABLE_NAME);var rowCount=itemsTable.rows.length;var rowId=elem.parentNode.parentNode.rowIndex-1;if(rowId==0&&rowCount==2){clearFirstLine();}else{itemsTable.deleteRow(elem.parentNode.parentNode.rowIndex);renumberAndUpdateTabIndexForInvoiceItemElements(itemsTable);}}
function clearFirstLine(){$("#itemQty\\[0\\]").val("");$("#itemProdCode\\[0\\]").val("");$("#itemDescription\\[0\\]").val("");$("#itemUnitPrice\\[0\\]").val("");$("#itemDiscount\\[0\\]").val("");$("#itemTax\\[0\\]").val("25");}
function renumberAndUpdateTabIndexForInvoiceItemElements(table){var rowCounter=-1;for(var rowNumber=0;rowNumber<table.tBodies[0].childNodes.length;rowNumber++){if(table.tBodies[0].childNodes[rowNumber].nodeName=="TR"){rowCounter++;var currentRow=table.tBodies[0].childNodes[rowNumber];for(var cellNumber=0;cellNumber<currentRow.cells.length;cellNumber++){var currentCell=currentRow.cells[cellNumber];for(var cellElementIndex=0;cellElementIndex<currentCell.childNodes.length;cellElementIndex++){var cellElement=currentCell.childNodes[cellElementIndex];if(cellElement.nodeName=="INPUT"||cellElement.nodeName=="SELECT"){reIndexElementNameAndReValueHiddenFieldItemNo(cellElement,rowCounter);updateTabIndex(cellElement);reIndexElementId(cellElement,rowCounter);}
else if(cellElement.nodeName=="IMG"){reIndexBallonHelp(cellElement,rowCounter);}
else if(cellElement.nodeName=="BUTTON"&&cellElement.name.indexOf("lookUpProductBtn")>0){updateTabIndex(cellElement);}
else if(cellElement.nodeName=="BUTTON"&&rowCounter>0&&cellElement.disabled==true){cellElement.disabled=false;}}}}}}
function reIndexBallonHelp(cellElement,indexNumber){var globNamePattern=new RegExp(strutsPattern,"g");for(var i=0;i<cellElement.attributes.length;i++){var current=cellElement.attributes[i];if(current.nodeName=="onmouseover"){current.nodeValue=current.nodeValue.replace(globNamePattern,function(oldName,prefix,number,suffix){return prefix+indexNumber+suffix});break;}}}
function reIndexElementNameAndReValueHiddenFieldItemNo(cellElement,indexNumber){var globNamePattern=new RegExp(strutsPattern,"g");var cellElementName=cellElement.name;cellElementName=cellElementName.replace(globNamePattern,function(oldName,prefix,number,suffix){return prefix+indexNumber+suffix});cellElement.name=cellElementName;if(cellElement.nodeName=="INPUT"&&cellElement.name.indexOf("itemNo")>0){cellElement.value=indexNumber+1;}}
function reIndexElementId(cellElement,indexNumber){var globIdPattern=new RegExp(elementIdPattern,"g");var cellElementId=cellElement.id;cellElementId=cellElementId.replace(globIdPattern,function(oldName,prefix,number,suffix){return prefix+indexNumber+suffix});cellElement.id=cellElementId;}
function updateTabIndex(elem){if(elem.name.indexOf("total")>0){return;}
elem.tabIndex=tabIndexCounter++;document.getElementById("newInvoiceItem").tabIndex++;}
function madeChanges(){sr.namespace("invoice").changesHaveBeenMade=true;return true;}
function getTarget(evt){var node=(evt.target)?evt.target:((evt.srcElement)?evt.srcElement:null);return node;}
function preventEnter(evt){evt=(evt)?evt:((event)?event:null);if(evt){var kc=(evt.charCode)?evt.charCode:((evt.which)?evt.which:evt.keyCode);if(kc==13||kc==3){var srcElement=getTarget(evt);if(srcElement.nodeName=="INPUT"){var currentTabIndex=srcElement.tabIndex;for(var i=0;i<document.forms[0].elements.length;i++){if(document.forms[0].elements[i].tabIndex==currentTabIndex+1){$(document.forms[0].elements[i]).focus();}}}
if(srcElement.nodeName=='INPUT'&&(srcElement.type!="submit"&&srcElement.type!="reset")){if(evt.returnValue){evt.returnValue=false;}
else if(evt.preventDefault){evt.preventDefault();}
else{return false;}}}}}
function proposeInvoiceText(fakturaNumber){$("#invoice_invoiceText").val("Kreditnota for fakturanr. "+fakturaNumber);}
function estimateDueDate(){var $selectDuePeriode=$("#id_duePeriode");if($selectDuePeriode.length){var estimatedDueDate=dateToString(calulateDueDate(getEstimatedShipmentDate(),$selectDuePeriode.val()));if(estimatedDueDate){$selectDuePeriode.attr('title',"Estimert forfallsdato: "+estimatedDueDate);$("#giro_due_date").html(estimatedDueDate);}}}
function getEstimatedShipmentDate(){var $elemNextDate=$("#id_invoiceTemplateNextDate");if($elemNextDate.val()!=null){return stringToDate($elemNextDate.val());}
else{var $elemFirstDate=$("#id_invoiceTemplateFirstDate");if($elemFirstDate.val()){return stringToDate($elemFirstDate.val());}}
return null;}
function parseDynamicValues(elemName){var elemSource=document.getElementById(elemName);if(!elemSource){var elementsByName=document.getElementsByName(elemName);if(elementsByName[0]){elemSource=elementsByName[0];}}
var $bySendDate=$("#bySendDate").checked;var baseDate=getEstimatedShipmentDate();if(!$bySendDate){baseDate=calulateDueDate(baseDate,$("#id_duePeriode").val());}
var result="";if(elemSource){result=elemSource.value;}
else{alert("ERROR: Can't find element by id or name: '"+elemName+"'");}
if(baseDate){var weekNumber=getWeekNumber(baseDate);var monthName=getMonthName(baseDate);var quarterName=getQuarterName(baseDate);var yearName=getYear(baseDate);result=result.replace(/\[uke\]/gi,weekNumber);result=result.replace(/\[m�ned\]/gi,monthName);result=result.replace(/\[kvartal\]/gi,quarterName);result=result.replace(/\[�r\]/gi,yearName);}
return"<span style='white-space: nowrap'>"+result+"<\/span>";}
function checkDescription(elem){var itemsTable=document.getElementById(ITEMS_TABLE_NAME);var rowCount=itemsTable.rows.length;var divText="Beskrivelse mangler for linje : ";var showTooltip=false;var first=true;var i=0;for(i=0;i<=rowCount;i++){var rowId=i;var elemAmount=document.getElementsByName('invoiceDetails['+rowId+'].qty')[0];var elemDescription=document.getElementsByName('invoiceDetails['+rowId+'].description')[0];var elemUnitPrice=document.getElementsByName('invoiceDetails['+rowId+'].unitPrice')[0];if(elemAmount!=null&&elemAmount.value!=null&&elemAmount.value.length>0&&elemUnitPrice!=null&&elemUnitPrice.value!=null&&elemUnitPrice.value.length>0&&(elemDescription==null||elemDescription.value==null||elemDescription.value.length==0)){showTooltip=true;if(first==true){divText=divText+" "+(rowId+1);first=false;}else{divText=divText+", "+(rowId+1);}}}
if((showTooltip==true)&&(showDescriptionTooltipGlobal)){showTooltipDiv(divText);}else{hideTooltipDiv(false);}}
function showTooltipDiv(divText){var pos=$("#itemDescription\\[0\\]").offset();var $tootTip=$("#tooltipDiv");$tootTip.css({"left":(pos.left+100)+"px","top":(pos.top-40)+"px"});$tootTip.text(divText);$tootTip.append('&nbsp;&nbsp;'+'<img src="/images/delete.png" width="14" height="14" vspace=2 style="vertical-align: top; border="0" onclick="hideTooltipDiv(true);" alt="X">');$tootTip.show();}
function hideTooltipDiv(permanently){if(permanently){showDescriptionTooltipGlobal=false;}
$("#tooltipDiv").hide();}
function checkRecipient(){var $name=$("#nameField");if($name.val()===null||$name.val().length===0){hideRecipientDiv();return}
var currentRecipientId=$("#recipientIdField").val();var foundRecipientsStore=new Ext.data.JsonStore({id:'recipientId',root:'recipients',totalProperty:'totalCount',fields:[{name:'recipientId',type:'int'},{name:'recipientNo',mtype:'string',convert:function(s){return unescape(s)}},{name:'name',type:'string',convert:function(s){return unescape(s)}},{name:'address1',type:'string',convert:function(s){return unescape(s)}},{name:'address2',type:'string',convert:function(s){return unescape(s)}},{name:'zip',type:'string',convert:function(s){return unescape(s)}},{name:'city',type:'string',convert:function(s){return unescape(s)}},{name:'country',type:'string',convert:function(s){return unescape(s)}},{name:'recipientEmail',type:'string',convert:function(s){return unescape(s)}},{name:'creditDays',type:'int'},{name:'discount',type:'string'},{name:'lost',type:'string'}],url:"/sr/ajax/recipientNameExists.do",baseParams:{name:$name.val(),currentRecipientId:currentRecipientId},listeners:{load:function(){var rows=this.getTotalCount();if(rows!=null&&rows>0){renderRecipientGrid(recipientGrid);}else{hideRecipientDiv();}},loadexception:function(proxy,options,response,error){isLoggedIn(response.responseText);}}});var recipientGrid=new Ext.grid.GridPanel({store:foundRecipientsStore,trackMouseOver:true,border:false,columns:[{header:'Nr',width:40,dataIndex:'recipientNo',sortable:false,resizable:false},{header:'Navn',dataIndex:'name',sortable:false,resizable:false},{header:'Adresse',dataIndex:'address1',sortable:false,resizable:false},{header:'Poststed',dataIndex:'city',sortable:false,resizable:false}],stripeRows:true,title:" ",autoHeight:true,sm:new Ext.grid.RowSelectionModel({singleSelect:true,listeners:{rowselect:function(smObj,rowIndex,record){copyRecipientToHeader(record);copyDatesToGiro();madeChanges();checkIfRecipientLost(record);Ext.get('dateInvoice').focus();hideRecipientDiv();}}})});foundRecipientsStore.load();}
function renderRecipientGrid(recipientGrid){$("#recipientDiv").text("");var totalCount=recipientGrid.store.getTotalCount();if(totalCount==1){recipientGrid.setTitle("Mente du denne kunden?");}else{recipientGrid.setTitle("Mente du \u00E5 velge en av disse kundene?");}
recipientGrid.render('recipientDiv');showRecipientDiv();}
function showRecipientDiv(){$(".sr-modal").hide();var pos=$("#nameField").offset();var $recipientDiv=$("#recipientDiv");var height=$recipientDiv.height();$recipientDiv.css({"left":(pos.left+280)+"px","top":(pos.top-height/2)+"px"});$recipientDiv.addClass("sr-modal");$recipientDiv.append("<a href='' onclick='hideRecipientDiv(); return false'>Avbryt</a>");$recipientDiv.show();}
function hideRecipientDiv(){$("#recipientDiv").removeClass("sr-modal").hide();}
function maskDocument(text){Ext.get(document.documentElement||document.body).mask(text);}
function unmaskDocument(){Ext.get(document.documentElement||document.body).unmask();}
function navigateToNewInvoicePage(){var uri=document.documentURI;if(uri.indexOf('initInvoice.do?invoiceType=')>0){location.href=uri;}
else if(uri.indexOf('getInvoice.do?ivo.id=')>0){location.href=uri;}
else if(uri.indexOf('recurring/createTemplate.do')>0){location.href=uri;}
else if(uri.indexOf('editRecurringInvoiceTemplate.do?id=')>0){location.href=uri;}
else{location.href='/sr/initInvoice.do?invoiceType=ordinary';}}
function isLoggedIn(ajaxResponseText){if(ajaxResponseText.length>0){if(ajaxResponseText.indexOf('SendRegning.no kundep&aring;logging')>0){Ext.MessageBox.show({minWidth:300,title:'Inaktiv &oslash;kt',msg:'<h3>Din &oslash;kt har blitt inaktiv.</h3><p>Du er n&oslash;dt til &aring; logge p&aring; igjen f&oslash;r du kan fortsette</p><div><p>Det er dessverre ingen mulighet for &aring; f&aring; lagret det du evt. m&aring;tte ha fylt ut<br />i og med at du ikke er logget inn</p></div>',icon:Ext.MessageBox.ERROR,buttons:Ext.MessageBox.OK,fn:navigateToNewInvoicePage,cls:'sr-alert'});return false;}
else{return true;}}}
function setReadOnly($element){$element.attr("disabled",true);}
function removeReadOnly($element){$element.removeAttr("disabled");$element.val(null);}
function debug(message){if(isDebug&&window.console&&window.console.log){window.console.log(message);}};$.fn.invoice.madeChanges=function(){return madeChanges();};$.fn.invoice.copyDatesToGiro=function(){return copyDatesToGiro();};$.fn.invoice.findRecipientByRecipientNo=function(elem){findRecipientByRecipientNo(elem)};$.fn.invoice.findNextRecipientNo=function(event){findNextRecipientNo(event)};$.fn.invoice.checkRecipient=function(){checkRecipient()};$.fn.invoice.copyAddressToGiro=function(){copyAddressToGiro()};$.fn.invoice.checkAddress1=function(addressFieldId){checkAddress1(addressFieldId)};$.fn.invoice.postnr2sted=function(elem,targetName){postnr2sted(elem,targetName)};$.fn.invoice.copyRecipientToHeader=function(recipient){copyRecipientToHeader(recipient)};$.fn.invoice.updateDiscount=function(elem,update){updateDiscount(elem,update)};$.fn.invoice.calcTotal=function(){calcTotal()};$.fn.invoice.calcItem=function(elem){calcItem(elem)};$.fn.invoice.checkDescription=function(elem){checkDescription(elem)};$.fn.invoice.findProductByProductNo=function(elem){findProductByProductNo(elem)};$.fn.invoice.lookupProduct=function(elem){lookupProduct(elem)};$.fn.invoice.isValidNumber=function(elem,fieldName,min,max){isValidNumber(elem,fieldName,min,max)};$.fn.invoice.calcItem=function(elem){calcItem(elem)};$.fn.invoice.isValidPositiveNumber=function(elem,fieldName,max){isValidPositiveNumber(elem,fieldName,max)};$.fn.invoice.removeInvoiceItem=function(elem){removeInvoiceItem(elem)};$.fn.invoice.addAnotherInvoiceItem=function(){addAnotherInvoiceItem()};$.fn.invoice.permanentHideAddressTooltipDiv=function(){permanentHideAddressTooltipDiv()};$.fn.invoice.proposeInvoiceText=function(fakturaNumber){proposeInvoiceText(fakturaNumber)};$.fn.invoice.permanentHideInvoiceDateInFutureTooltipDiv=sr.hints.date.invoice.permanentHideInvoiceDateInFutureTooltipDiv;$.fn.invoice.permanentHideInvoiceDateInPastTooltipDiv=sr.hints.date.invoice.permanentHideInvoiceDateInPastTooltipDiv;$.fn.invoice.permanentHideOrderDateInFutureTooltipDiv=sr.hints.date.order.permanentHideOrderDateInFutureTooltipDiv;$.fn.invoice.permanentHideOrderDateInPastTooltipDiv=sr.hints.date.order.permanentHideOrderDateInPastTooltipDiv;$.fn.invoice.permanentHideDueDateInFutureTooltipDiv=sr.hints.date.due.permanentHideDueDateInFutureTooltipDiv;$.fn.invoice.permanentHideDueDateInPastTooltipDiv=sr.hints.date.due.permanentHideDueDateInPastTooltipDiv;$.fn.invoice.checkOrderDate=sr.hints.date.order.checkOrderDate;$.fn.invoice.checkDueDate=sr.hints.date.due.checkDueDate;$.fn.invoice.checkDateInvoice=sr.hints.date.invoice.checkDateInvoice;$.fn.invoice.defaults={'debug':false};})(jQuery,sendregning);(function(sr){var validation=sr.namespace("validation");validation.handler=validationHandler;var model=sr.namespace("document.sendparams.model");var log=sr.namespace("log");function validationHandler(providedErrorHandler){providedErrorHandler.clearAll();function validateEmail(element,textInvalidEmail){var $emailAddressField=element instanceof $?element:$(element);var emailAddressValue=$emailAddressField.val();if(emailAddressValue.length<5){addError($emailAddressField,textInvalidEmail);return true;}
$.ajax({url:"validateEmailInvoiceSendParams.action",data:{invoiceId:model.invoiceId,sendEmailAddress:emailAddressValue},dataType:"json",error:function(xhr,status,error){},success:function(data){if(data.length==0){removeError($emailAddressField);}
else{var message="";$.each(data,function(index,value){message=message+value;});addError($emailAddressField,message);}}});return true;}
function validateOrgNum(element,processNotSupported,processElectronicSendMethod){var $orgNumElement=element instanceof $?element:$(element);$.ajax({url:"supportElectronicInvoiceSendParams.action",data:{invoiceId:model.invoiceId,draftSalesDocumentId:model.draftSalesDocumentId,orgNum:$orgNumElement.val()},dataType:"json",error:function(xhr,status,error){},success:function(data){if(data===null){return processNotSupported($orgNumElement.val());}
else if(typeof data.id!="undefined"){removeError($orgNumElement);processElectronicSendMethod(data);}
else{var message="";$.each(data,function(index,value){message=message+value;});addError($orgNumElement,message);}}});return true;}
function validateTextIsPresent(element,errorText){var $yourRef=element instanceof $?element:$(element);var value=$yourRef.val();if(value&&value.trim().length>0){removeError($yourRef);return true;}
addError($yourRef,errorText);return false;}
function validatePostCode(element,textInvalidPostNr){var $postCode=element instanceof $?element:$(element);var value=$postCode.val();if(value&&value.trim().length>0){removeError($postCode);return true;}
addError($postCode,textInvalidPostNr);return false;}
function validateCity(element,textInvalidCity){log.debug("validateCity");var $city=$(element);var value=$city.val();if(value&&value.trim().length>2){removeError($city);return true;}
log.debug($city);addError($city,textInvalidCity);return false;}
function validateFileUpload(element,messages){var file,fileName,fileSize,fileType;if($.isArray(element)){element=element[0];}
if(element.files&&element.files[0]){file=element.files[0];fileName=file.name;fileSize=file.size||0;fileType=file.type||'unknown';}
else{fileName=element.value;fileSize=0;fileType='unknown';}
var matches=fileName&&fileName.match(/^"?.*?([^"\/\\]+)"?$/);if(matches){fileName=matches[1];if(fileName.match("\.pdf$")){fileType="application/pdf";}}
if(fileType!="application/pdf"){addError(element,messages&&messages.fileType+" : "+fileName);return false;}
if(fileSize&&fileSize>5242880){addError(element,messages&&messages.fileSize+" : "+fileName);return false;}
removeError(element);return fileName;}
function removeError(element){var $element=element instanceof $?element:$(element);if($element.length){var elementId=$element.attr("id");providedErrorHandler.removeError(elementId);$element.addClass('valid');$element.removeClass('error');findErrorLabel($element,elementId).hide();}
else{throw"Unable to remove error with id: "+$element;}}
function addError(element,message){var $element=element instanceof $?element:$(element);if($element.length){var elementId=$element.attr("id");providedErrorHandler.addError(elementId,"true");$element.removeClass('valid');$element.addClass('error');var $label=findErrorLabel($element,elementId);if(!$label.length){$element.after("<label for='"+elementId+"' class='fieldError' generated='true'/>");$label=findErrorLabel($element,elementId);}
if($label.length){$label.html(message);$label.show();}}
else{throw"Unable to remove error with id: "+$element;}}
function findErrorLabel($element,elementId){return $element.parent().children("label.fieldError[for="+elementId+"]");}
return{validateEmail:validateEmail,validatePostCode:validatePostCode,validateCity:validateCity,validateOrgNum:validateOrgNum,validateTextIsPresent:validateTextIsPresent,validateFileUpload:validateFileUpload,addError:addError,hasErrors:providedErrorHandler.hasErrors,removeError:removeError,clearAll:providedErrorHandler.clearAll};}})(sendregning);(function(sr){"use strict";var log=sr.namespace("log");var sendparams=sr.namespace("document.sendparams");var model=sr.namespace("document.sendparams.model");var formatter=sr.namespace("formatter");sendparams.configureModel=configureModel;sendparams.configureGui=configureGui;sendparams.configureMessages=configureMessages;sendparams.setView=setView;sendparams.validator=getValidator;sendparams.createUploader=createUploader;sendparams.defaults={className:"sendParams"};sendparams.testFunctions={isDefaultCopySend:isDefaultCopySend}
var $priceBox;var $sendButton;var $sendCopyCheckBox;var $emailAddressTextBox;var $emailAddressCopyTextBox;var $yourRefTextBox;var $sendingMethod;var $sendingMethodContinueButton;var $postNrTextBox;var $cityTextBox;var $organisationNrTextBox;var $attachmentSection;var moreThanOneSendingMethod=false;var invoiceId;var draftSalesDocumentId;var defaultCopySend;var avtaleGiroKey;var invoiceSendEmailKey;var invoiceSendSnailKey;var dunningSendSnailKey;var checkElectronicKey;var electronicSendMethodKey;var textElectronicNotSupported1;var textElectronicNotSupported2;var textInvalidCity;var textInvalidPostNr;var textInvalidEmail;var textInvalidYourRef;var validatorObj;function setView(element){element.className=sendparams.defaults.className;}
function validatePostalAddress(){validatorObj.validatePostCode($postNrTextBox,textInvalidPostNr);validatorObj.validateCity($cityTextBox,textInvalidCity);}
function fetchSelctedSendMethod(){return $("input:radio[name='sendMethod']:checked");}
function getCopyMethod(){return $("div.sendMethodContainer").has("input:checkbox");}
function hideCopySendMethods(){$("#sendingMethodButtons").show();$sendingMethodContinueButton.addClass("active");$("#sendCopyMethod").hide();$priceBox.shoppingCart.removeProduct("id");$priceBox.shoppingCart.draw();disableSubmitButton();}
function showCopySendMethods(){$("#sendCopyMethod").show();$("#sendingMethodButtons").hide();$sendingMethodContinueButton.removeClass("active");if(isDefaultCopySend()&&!$sendCopyCheckBox.is(':checked')){$sendCopyCheckBox.attr('checked',true);}
updateCopyItem($sendCopyCheckBox);enableSubmitButton();focusSubmit();}
function showAttachments(){$attachmentSection.show();}
function hideAttachments(){$attachmentSection.hide();}
function disableSubmitButton(){$sendButton.attr('disabled',true);$sendButton.addClass("disabled").removeClass("active");}
function enableSubmitButton(){if($("#sendCopyMethod").is(":visible")&&!validatorObj.hasErrors()){$sendButton.attr('disabled',false);$sendButton.addClass("active").removeClass("disabled");}}
function isDefaultCopySend(){return defaultCopySend;}
function updateCopyItem(){var $selectedCopyMethod=getCopyMethod();var price=formatter.parseNorwegianMonetaryAmount($selectedCopyMethod.find("input:hidden[name='price']").val());var description=($selectedCopyMethod.find("input:hidden[name='description']")).val();var id=$sendCopyCheckBox.attr('id');if($sendCopyCheckBox.is(':checked')){$priceBox.shoppingCart.addProduct(id,description,price);$selectedCopyMethod.find("div").removeClass('disabled');validatorObj.validateEmail($emailAddressCopyTextBox,textInvalidEmail);}
else{$priceBox.shoppingCart.removeProduct(id);$selectedCopyMethod.find("div").addClass('disabled');validatorObj.removeError($emailAddressCopyTextBox);}
$priceBox.shoppingCart.draw();}
function updateSelectedMethod($priceBox,autoOpen){var id=fetchSelctedSendMethod().val();$priceBox.shoppingCart.clear();validatorObj.clearAll();var $selectedMethod=$("div.sendMethodContainer").has("input:radio::checked");var price=formatter.parseNorwegianMonetaryAmount($selectedMethod.find("input:hidden[name='price']").val());var description=$selectedMethod.find("input:hidden[name='description']").val();switch(id){case avtaleGiroKey:$("#checkElectronicOrgNum").hide();$("#sendEmailRecipientAddress").hide();$("#electronicParsableValidateFields").hide();$priceBox.shoppingCart.addProduct(id,description,price);break;case invoiceSendEmailKey:$("#checkElectronicOrgNum").hide();$("#sendEmailRecipientAddress").show();$emailAddressTextBox.select();if($emailAddressTextBox.val().trim().length<=0){setTimeout(function(){$($emailAddressTextBox).focus();},100);}
$("#electronicParsableValidateFields").hide();$priceBox.shoppingCart.addProduct(id,description,price);break;case invoiceSendSnailKey:$("#sendEmailRecipientAddress").hide();$("#checkElectronicOrgNum").hide();$("#electronicParsableValidateFields").hide();$priceBox.shoppingCart.addProduct(id,description,price);break;case dunningSendSnailKey:$("#sendEmailRecipientAddress").hide();$("#checkElectronicOrgNum").hide();$("#electronicParsableValidateFields").hide();$priceBox.shoppingCart.addProduct(id,description,price);break;case checkElectronicKey:$("#sendEmailRecipientAddress").hide();$("#checkElectronicOrgNum").show();$("#electronicParsableValidateFields").hide();break;case electronicSendMethodKey:$("#sendEmailRecipientAddress").hide();$("#checkElectronicOrgNum").hide();$("#electronicParsableValidateFields").hide();$priceBox.shoppingCart.addProduct(id,description,price);break;default:{$("#sendEmailRecipientAddress").hide();$("#checkElectronicOrgNum").hide();$("#electronicParsableValidateFields").hide();}}
$("#envelope").hide();$("#orgNum").hide();$("#orgNumMessage").hide();hideCopySendMethods();hideAttachments();$("#sendingMethodButtons").show();$priceBox.shoppingCart.draw();$(this).blur();if(autoOpen&&isSendingMethodComplete(id)){selectSendingMethod();}
else{$sendingMethodContinueButton.focus();}}
function isSendingMethodComplete(id){var isCompleteLookup={};isCompleteLookup[avtaleGiroKey]=true;isCompleteLookup[invoiceSendEmailKey]=function(){return $emailAddressTextBox.hasClass("valid")};isCompleteLookup[invoiceSendSnailKey]=true;isCompleteLookup[dunningSendSnailKey]=true;isCompleteLookup[checkElectronicKey]=false;isCompleteLookup[electronicSendMethodKey]=true;var methodCall=isCompleteLookup[id];var result=typeof methodCall=='function'?methodCall():methodCall;return!!result;}
function showElectronicRequiredFields(){$("#electronicParsableValidateFields").show();$($yourRefTextBox).blur();if($yourRefTextBox.val().trim().length<=0){setTimeout(function(){$($yourRefTextBox).focus();},100);}}
function selectSendingMethod(){var $selectedRadioBox=$("input:radio[name='sendMethod']:checked");var id=$selectedRadioBox.val();var selectSendingMethodLookup={};selectSendingMethodLookup[invoiceSendSnailKey]=function(){$("#envelope").show();};selectSendingMethodLookup[invoiceSendEmailKey]=showAttachments;selectSendingMethodLookup[dunningSendSnailKey]=function(){$("#envelope").show();};selectSendingMethodLookup[checkElectronicKey]=function(){$organisationNrTextBox.blur();return true;};selectSendingMethodLookup[electronicSendMethodKey]=showElectronicRequiredFields;var methodCall=selectSendingMethodLookup[id];var result=typeof methodCall=='function'?methodCall():methodCall;if(!!result){return false;}
$("div.sendMethodContainer").has("input:radio:not(:checked)").hide();if(moreThanOneSendingMethod){$("#chooseADifferentSendingOption").show();}
showCopySendMethods();}
function processElectronicSendMethod(data){$("div.sendMethodContainer").has("input:radio:checked").removeClass("sendMethodContainer").hide();var electronicSendMethod=createElectronicSendMethod(data);$("#allSendMethods").prepend(electronicSendMethod);$("#electronicSendMethod").attr("checked",true);$priceBox.shoppingCart.clear();$priceBox.shoppingCart.draw();updateSelectedMethod($priceBox,true);}
function createElectronicSendMethod(data){var electronicSendMethod=$('<div class="sendMethodContainer"><input type="hidden" value="'+data.price+'" name="price">'+'<input type="hidden" value="'+data.description+'" name="description">'+'<input type="radio" name="sendMethod" id="electronicSendMethod" value="'+data.id+'" class="sendMethod"><label for="electronicSendMethod">'+
data.productDescription+' ('+data.price+')</label></div>');return electronicSendMethod;}
function processNotSupported(orgNum){$("div.sendMethodContainer").has("input:radio:checked").removeClass("sendMethodContainer").hide();$("#checkElectronicOrgNum").hide();$("#sendingMethodButtons").show();$("#orgNumMessage").html(textElectronicNotSupported1+": "+orgNum+'<br>'+textElectronicNotSupported2).show();return;}
function setUpGui(){getValidator();$sendButton.click(function(){return!validatorObj.hasErrors();});var $inputFieldsNotIncludingButtons=$("input, select").not(".active");$inputFieldsNotIncludingButtons.bind('keypress',function(e){if((e.which&&e.which==13)||(e.keyCode&&e.keyCode==13)){e.target.blur();return false;}
else{return true;}});$inputFieldsNotIncludingButtons.bind('blur',focusSubmit);$sendCopyCheckBox.change(function(){updateCopyItem();});setupValidation();$sendingMethod.change(function(event){updateSelectedMethod($priceBox,true);});$sendingMethodContinueButton.click(function(){try{selectSendingMethod();}
finally{return false;}});$("input.sendMethod:first").attr('checked',true);hideCopySendMethods();hideAttachments();moreThanOneSendingMethod=$("#allSendMethods div.sendMethodContainer").size()>1;updateSelectedMethod($priceBox,!moreThanOneSendingMethod);$("#chooseADifferentSendingOption a").click(function(){$("#chooseADifferentSendingOption").hide();$("div.sendMethodContainer").has("input:radio:not(:checked)").show();updateSelectedMethod($priceBox,false);});$("#editAddress").click(function(){var $fixedAddress=$("#fixedAddress");var $editableAddress=$("#editableAddress");var $addressImage=$("#addressImage");if($fixedAddress.is(":visible")){$("#editableAddress :input").removeAttr('disabled');$("#fixedAddress").slideUp();$("#editableAddress").slideDown();validatePostalAddress();$addressImage.attr("src","/images/cancel27x20.png");$addressImage.attr("alt","cancel");}
else{$("#editableAddress :input").attr('disabled',true);$fixedAddress.slideDown();$editableAddress.slideUp();validatorObj.removeError($cityTextBox);validatorObj.removeError($postNrTextBox);$addressImage.attr("src","/images/salesledger/edit.png");$addressImage.attr("alt","edit address");focusSubmit();}});$sendingMethodContinueButton.focus();}
function configureGui(args){$sendButton=args.sendInvoiceBtn;$sendCopyCheckBox=args.sendCopyCheckBox;$emailAddressTextBox=args.emailAddressTextBox;$emailAddressCopyTextBox=args.emailCopyAddressTextBox;$yourRefTextBox=args.yourRefTextBox;$priceBox=args.priceBox;$sendingMethod=args.sendMethodRadioBoxes;$sendingMethodContinueButton=args.sendMethodContinueButton;$postNrTextBox=args.zipTextBox;$cityTextBox=args.cityTextBox;$organisationNrTextBox=args.orgNumTextBox;$attachmentSection=args.attachmentSection;avtaleGiroKey=args.avtaleGiroKey;invoiceSendEmailKey=args.invoiceSendEmailKey;invoiceSendSnailKey=args.invoiceSendSnailKey;dunningSendSnailKey=args.dunningSendSnailKey;checkElectronicKey=args.checkElectronicKey;electronicSendMethodKey=args.electronicSendMethodKey;setUpGui();}
function attachHandlers($textBox,method,errorMessage,throttle){var throttler=sr.util.throttler.create(function(validate){validate();});var methodCall=throttle?validateThrottle:defaultValidate;$textBox.keyup(methodCall);$textBox.blur(defaultValidate);function defaultValidate(){method(this,errorMessage);return true;}
function validateThrottle(){var self=this;throttler.queue(function(){method(self,errorMessage);});return true;}};function focusSubmit(){if(!validatorObj.hasErrors()){$sendButton.focus();}}
function setupValidation(){attachHandlers($emailAddressTextBox,validatorObj.validateEmail,textInvalidEmail,true);attachHandlers($emailAddressCopyTextBox,validatorObj.validateEmail,textInvalidEmail,true);attachHandlers($postNrTextBox,validatorObj.validatePostCode,textInvalidPostNr,false);attachHandlers($cityTextBox,validatorObj.validateCity,textInvalidCity,false);$organisationNrTextBox.blur(function(){validatorObj.validateOrgNum(this,processNotSupported,processElectronicSendMethod);});attachHandlers($yourRefTextBox,validatorObj.validateTextIsPresent,textInvalidYourRef,false);}
function configureModel(args){model.invoiceId=args.invoiceId;model.draftSalesDocumentId=args.draftSalesDocumentId;model.defaultCopySend=(typeof args.copySelectByDefault=="string")?args.copySelectByDefault=="true":args.copySelectByDefault;invoiceId=args.invoiceId;draftSalesDocumentId=args.draftSalesDocumentId;defaultCopySend=model.defaultCopySend;}
function configureMessages(args){textElectronicNotSupported1=args.electronicNotSupported1;textElectronicNotSupported2=args.electronicNotSupported2;textInvalidCity=args.invalidCity;textInvalidPostNr=args.invalidPostnr;textInvalidEmail=args.invalidEmail;textInvalidYourRef=args.invalidYourRef;};function getValidator(){if(!validatorObj){validatorObj=sr.validation.handler(sr.error.handler(enableSubmitButton,disableSubmitButton));}
return validatorObj;}
function createUploader($,$view,remote,i18n){if(!$view.length){return null;}
var attachmentId;var filename;var $attachmentIdField=$('#attachmentId',$view);var $fileNameField=$('#filename',$view);var $attachmentDiv=$("#attachmentDiv",$view);var $checkbox=$("input[type=checkbox]",$view);var $iframe=$('iframe.upload',$view);var $attachmentList=$("#attachments",$view);var $loadingScreen=$("#loadingScreen");var $cancelUpload=$("#cancelUpload");var locationPoller;var uploading=false;var $iframeFileInputField;setUpEventHandlers();function addAttachment($attachmentView){$.fancybox.close();var price=sendregning.formatter.parseNorwegianMonetaryAmount(i18n.price);$priceBox.shoppingCart.addProduct("attachment_"+attachmentId,"Lagring av vedlegg",price);$priceBox.shoppingCart.draw();$iframe.attr("src","");$iframe.hide();$attachmentView.append('<li>'+filename+'<img class="closeLink" data-attachment-id="'+attachmentId+'" width="12" height="12" src="/images/cancel.png" title="'+i18n.removeAttachment+'" /></li>');}
function removeAttachment(idToRemove){$.fancybox.close();sendparams.validator().removeError($iframeFileInputField);var $attachmentElement=$("img[data-attachment-id="+idToRemove+"]",$view).parent();$attachmentElement.remove();$priceBox.shoppingCart.removeProduct("attachment_"+attachmentId);$priceBox.shoppingCart.draw();attachmentId=null;filename=null;$attachmentIdField.val(attachmentId);$fileNameField.val(filename);$checkbox.attr("checked",false);$iframe.attr("src","");$iframe.hide();$attachmentDiv.hide();}
function showLoadingScreen(){$loadingScreen.html('<h1 class="uploading">'+i18n.uploading+'</h1>'+'<p><img width="32" height="32" alt="upload" src="/images/upload-amazon.gif"></p>');$loadingScreen.append($cancelUpload);$.fancybox({href:'#loadingScreen',modal:true,openEffect:'elastic',closeEffect:'elastic'});}
function handleError(){clearInterval(locationPoller);uploading=false;$iframe.hide();$loadingScreen.html("<h1>"+i18n.errorHeading+"</h1><p>"+i18n.noContact+"</p>");$loadingScreen.append($cancelUpload);}
function setUpEventHandlers(){$checkbox.change(function(){var $this=$(this)
if($this.is(":checked")){$iframe.attr("src",remote.initUrl);}
else{remote.removeAttachment(attachmentId,function(err,data){if(!err){removeAttachment(attachmentId);}});}});$iframe.load(function(){var src=$iframe.attr("src");if(uploading){handleError();}
else if(src==remote.initUrl){$iframe.show();$attachmentDiv.show();}});$attachmentList.click(function(event){var $target=$(event.target);if($target.attr("data-attachment-id")){remote.removeAttachment(attachmentId,function(err,data){removeAttachment(attachmentId);});event.preventDefault();}});$cancelUpload.live('click',function(event){clearInterval(locationPoller);uploading=false;remote.removeAttachment(attachmentId,function(err,data){removeAttachment(attachmentId);});event.preventDefault();});}
function isError(){try{var frameContents=$iframe[0].contentWindow||$iframe[0].contentDocument;if(!frameContents||!frameContents.location||!frameContents.location.href){handleError();}}
catch(e){handleError();}}
return{validator:function($fileInput){$iframeFileInputField=$fileInput;return sendparams.validator()},setAttachmentId:function(id){attachmentId=id;$attachmentIdField.val(attachmentId);},uploadStarted:function(name){filename=name;locationPoller=setInterval(isError,1000);uploading=true;$fileNameField.val(filename);showLoadingScreen();},uploadComplete:function(){uploading=false;addAttachment($attachmentList);}}}}(sendregning));(function($,sr){"use strict";var log=sr.namespace("log");var keyCodes={up:38,down:40,enter:13};var createNewStr='Create new label';var addToGroupText='Add to group';var $labels=$("<div class='sr-labels'/>");sr.Label=Label;sr.SearchBox=SrSearchBox;sr.Button=SrButton;sr.WidgetControl=SrWidgetControl
function create(element,opts){var labels=[];if(!element||typeof element.className!="string"){throw new TypeError("element is not a dom element");}
var labelMenuWidget=sr.create(this);labelMenuWidget.element=element;labelMenuWidget.labels=labels;labelMenuWidget.$labels=$labels;labelMenuWidget.recipientId=opts.recipientId;labelMenuWidget.callback=opts.callback;createNewStr=opts.createNewStr;addToGroupText=opts.addToGroupText;labelMenuWidget.parse(element,function(labelId){labelMenuWidget.assignLabel(labelId,function(label){labelMenuWidget.close();labelMenuWidget.callback(label);});});labelMenuWidget.filterbox=new sr.SearchBox(labelMenuWidget,function(){var value=this.value;var filteredLabels=labelMenuWidget.filter(value);labelMenuWidget.updateLabels(filteredLabels);labelMenuWidget.newLabelButton.setValue(value);},submitHandler);$(".sr-label",element).live("click",function(){var labelId=$(this).attr("data-label-id");labelMenuWidget.assignLabel(labelId,function(label){labelMenuWidget.close();labelMenuWidget.callback(label);});})
labelMenuWidget.newLabelButton=new sr.Button(labelMenuWidget,submitHandler);labelMenuWidget.uiElements=new sr.WidgetControl(element);labelMenuWidget.draw(element,function(){});return labelMenuWidget;}
function submitHandler(){var _this=this;var newLabelValue=_this.newLabelButton.value;this.createNewLabel(newLabelValue,function(label){_this.addLabel(label);_this.close();_this.callback(label);});}
function add(label){if(!this.labels){this.labels=[];}
var found=false;for(var i=0;i<this.labels.length;i++){var existingLabel=this.labels[i];if(label.equals(existingLabel)){found=true;}}
if(!found){this.labels.push(label);}
this.labels.sort(label.compareTo);}
function parse(element,submitHandler){var $labels=$("ul.labels li",element);var labelWidget=this;$labels.each(function(index,value){var $label=$(value);labelWidget.addLabel(new sr.Label($label.attr("id"),$label.html(),submitHandler));});}
function draw(element,callback){var $element=$(element);$element.empty();var $informativeText=$("<div class='sr-label-header'>"+addToGroupText+"</div>");$element.append($informativeText);$element.append(this.filterbox.get());$element.append(this.$labels);$element.append(this.newLabelButton.get());this.updateLabels(this.labels);if(typeof callback==='function'){callback($element);}}
function updateLabels(filteredLabels){var labelMenuWidget=this;var $labels=labelMenuWidget.$labels;$labels.empty();var uiElements=labelMenuWidget.uiElements;uiElements.clear();uiElements.add(labelMenuWidget.filterbox);$(filteredLabels).each(function(index,value){$labels.append("<div class='sr-label' data-label-id='"+value.id+"'>"+value.labelName+"</div>");uiElements.add(this);});uiElements.add(labelMenuWidget.newLabelButton);}
function filter(searchTerm){var result=[];if(!this.labels){return result;}
if(!searchTerm||sr.trim(searchTerm).length<=0){return this.labels;}
var labels=this.labels;for(var i=0;i<labels.length;i++){var label=labels[i];if(label.matches(searchTerm)){result.push(label);}}
return result;}
function assignLabel(labelId,callback){var widget=this;$.ajax({url:"assignLabelRecipient.action",type:"POST",data:{labelId:labelId,recipientId:widget.recipientId},dataType:"json",error:function(xhr,status,error){},success:function(data){if(data){var label=new sr.Label(data.labelId.value,data.labelName.value);callback(label);}}});}
function createNewLabel(newLabelName,callback){var widget=this;if(!sr.trim(newLabelName)){return;}
$.ajax({url:"newLabelRecipient.action",type:"POST",data:{labelName:newLabelName,recipientId:widget.recipientId},dataType:"json",error:function(xhr,status,error){},success:function(data){if(data){var label=new sr.Label(data.labelId.value,data.labelName.value);callback(label);}}});}
function close(){$(this.element).hide();}
function show(){$(this.element).show();this.filterbox.clear();this.filterbox.focus();}
function toggle(){var $menu=$(this.element);if($menu.is(":visible")){this.close();}
else{this.show();}}
sr.namespace("widget").labelMenuController={create:create,addLabel:add,filter:filter,draw:draw,parse:parse,updateLabels:updateLabels,createNewLabel:createNewLabel,assignLabel:assignLabel,toggle:toggle,close:close,show:show,submitHandler:submitHandler,load:function(){}};function Label(id,labelName,submitHandler){function matches(searchTerm){if(this.labelName.toLowerCase().indexOf(searchTerm.toLowerCase())==0){return true;}
return false;}
function compareTo(labelA,labelB){var a=String(labelA.labelName).toLowerCase();var b=String(labelB.labelName).toLowerCase();if(a>b)
return 1
if(a<b)
return-1
return 0;}
function equals(otherLabel){return this.labelName===otherLabel.labelName&&this.id===otherLabel.id;}
function get(){return $(".sr-label[data-label-id="+this.id+"]");}
function submit(){submitHandler(this.id);}
return{id:parseInt(id),labelName:labelName,matches:matches,equals:equals,compareTo:compareTo,get:get,submit:submit}}
function SrButton(labelMenuWidget,callback){var $newLabelButton=$("<div class='sr-new-label-btn'/>");this.$newLabelButton=$newLabelButton;this.value='';$newLabelButton.click(submit);function submit(){callback.call(labelMenuWidget);}
function get(){return $newLabelButton;}
function setValue(text){this.value=text;if(!sr.trim(text)){$newLabelButton.html("");$newLabelButton.hide();}
else{$newLabelButton.html(createNewStr+" '"+text+"'");$newLabelButton.show();}}
return{setValue:setValue,value:'',submit:submit,get:get}}
function SrSearchBox(labelMenuWidget,callback,submitHandler){var $searchBoxDiv=$("<div class='sr-search-box'><input maxlength='26' size='26' class='sr-input' type='text'/></div>");var $searchBoxInput=$("input.sr-input",$searchBoxDiv);$searchBoxInput.keyup(function(e){var keyCode=e.keyCode||e.which;switch(keyCode){case keyCodes.up:return true;break;case keyCodes.down:return true;break;case keyCodes.enter:return true;break;}
callback.call(this);});function get(){return $searchBoxDiv;}
function value(){$searchBoxInput.val();}
function focus(){$searchBoxInput.focus();}
function clear(){$searchBoxInput.val('');callback.call({value:''});}
function submit(){submitHandler.call(labelMenuWidget);}
return{submit:submit,value:value,focus:focus,clear:clear,get:get}}
function SrWidgetControl(element){this.elements=[];this.index=0;var widget={add:add,next:next,previous:previous,submit:submit,clear:clear,deactivateActiveElement:deactivateActiveElement,activateActiveElement:activateActiveElement,activateElement:activateElement};$(element).keyup(keyHandler);function next(){deactivateActiveElement.call(this);this.index=this.index+1;if(this.index>=this.elements.length){this.index=0;}
activateActiveElement.call(this);}
function previous(){deactivateActiveElement.call(this);this.index=this.index-1;if(this.index<0){this.index=0;}
activateActiveElement.call(this);}
function submit(){this.elements[this.index].submit();}
function add(item){this.elements.push(item);var itemIndex=this.elements.length-1;var _this=this;item.get().mouseenter(function(){_this.deactivateActiveElement();_this.activateElement(itemIndex);})}
function clear(){deactivateActiveElement.call(this);this.index=0;this.elements=[];}
function keyHandler(e){var keyCode=e.keyCode||e.which;switch(keyCode){case keyCodes.up:widget.previous();return false;break;case keyCodes.down:widget.next();return false;break;case keyCodes.enter:widget.submit();return false;break;}
return true;}
function deactivateActiveElement(){if(!this.elements){return;}
var activeElement=this.elements[this.index];if(activeElement){activeElement.get().removeClass("active");}}
function activateActiveElement(){if(!this.elements){return;}
this.activateElement(this.index);}
function activateElement(elmIndex){if(!this.elements){return;}
this.index=elmIndex;var activeElement=this.elements[elmIndex];if(activeElement){activeElement.get().addClass("active");}}
return widget;}}(jQuery,sendregning));(function($,sr){"use strict";sr.namespace("widget.textbox.lengthController").create=function(view,i18n){var maxLength=0;var label;setUpEventHandler();maxLength=view.maxLength;if(!maxLength||maxLength===2147483647||maxLength<=0||maxLength===524288){return{}}
label=document.createElement("label");$(label).addClass("counter");view.parentNode.insertBefore(label,view);renderMessage();function setUpEventHandler(){$(view).keyup(function(event){renderMessage();});$(view).change(function(event){renderMessage();});}
function renderMessage(){label.innerHTML=generateMessage();}
function generateMessage(){var remaining=maxLength-view.value.length;return remaining+" "+i18n.message;}
return{};};}(jQuery,sendregning));(function($,sr){"use strict";var dunning=sr.namespace("dunning");var formatter=sr.namespace("formatter");dunning.createCalculator=createCalculator;dunning.createFormatter=createFormatter;function createCalculator(view,constants){var $allInputs=$("input,select",view);var dunningFee=formatter.parseNorwegianMonetaryAmount(constants.dunningFeeValue);var interestRate=formatter.parseNorwegianMonetaryAmount(constants.interestRate);var principalBalance=formatter.parseNorwegianMonetaryAmount(constants.principalBalance);var recipientTotalBalance=formatter.parseNorwegianMonetaryAmount(constants.recipientTotalBalance);var overDueDays=formatter.parseNorwegianMonetaryAmount(constants.overDueDays);var sumOfPreviousInterests=formatter.parseNorwegianMonetaryAmount(constants.sumOfPreviousInterests);var sumOfPreviousDunningFees=formatter.parseNorwegianMonetaryAmount(constants.sumOfPreviousDunningFees);var $invoiceBase=$(".invoiceBase",view);setupEventHandlers(view);var model={payableAmount:0,interestSum:0,interestTotal:0,dunningFeeTotal:0,invoiceBase:$invoiceBase.html(),includeInterest:false,includeDunningFee:false,includeRecipientBalance:false}
function displayInterest(){var $interest=$('.interestAmount',view);var $interestSummary=$('.interestTotal',view);calculateInterest();$interest.html("kr "+sr.formatter.number2NorwegianMonetartyAmount(model.interestSum));$interestSummary.html(sr.formatter.number2NorwegianMonetartyAmount(model.interestTotal));}
function displayDunningFee(){var $dunningFeeSummary=$('.dunningFeeTotal',view);$dunningFeeSummary.html(sr.formatter.number2NorwegianMonetartyAmount(model.dunningFeeTotal));}
function updateSummaryTable(){var $paymentsRow=$(".payments",view);if(includeRecipientBalance()){$paymentsRow.hide();$invoiceBase.html(sr.formatter.number2NorwegianMonetartyAmount(recipientTotalBalance))}
else{$paymentsRow.show();$invoiceBase.html(model.invoiceBase);}}
function displayPayableAmount(){var $payableAmount=$('.payableAmount',view);var oldValue=$payableAmount.html();updateSummaryTable();calculatePayableAmount();displayInterest();displayDunningFee();var newValue="kr "+sr.formatter.number2NorwegianMonetartyAmount(model.payableAmount);if(oldValue!=newValue){$payableAmount.html(newValue);$payableAmount.stop().css("background-color","#FFFF9C").animate({backgroundColor:"#FFF"},1500);}}
function calculateInterest(){var interestPrDay=(interestRate/365)/100;var dueDays=Number($("#dueDays",view).val());model.interestSum=(interestPrDay*principalBalance)*(overDueDays+dueDays);}
function calculatePayableAmount(){calculateInterest();var chosenBalance=model.includeRecipientBalance?recipientTotalBalance:principalBalance;model.payableAmount=chosenBalance;model.dunningFeeTotal=sumOfPreviousDunningFees;model.interestTotal=sumOfPreviousInterests;if(includeInterest()){model.interestTotal+=model.interestSum;}
if(includeDunningFee()){model.dunningFeeTotal+=dunningFee;}
model.payableAmount+=model.dunningFeeTotal;model.payableAmount+=model.interestTotal;return model.payableAmount;}
function includeInterest(value){if(typeof value!="undefined"){model.includeInterest=!!value;}
return model.includeInterest;}
function includeDunningFee(value){if(typeof value!="undefined"){model.includeDunningFee=!!value;}
return model.includeDunningFee;}
function includeRecipientBalance(value){if(typeof value!="undefined"){model.includeRecipientBalance=!!value;}
return model.includeRecipientBalance;}
function setupEventHandlers(view){var resolve={addInterest:function(checked){includeInterest(checked);},addDunningFee:function(checked){includeDunningFee(checked);},dueDays:function(checked){displayInterest();},includeRecipientBalance:function(checked){includeRecipientBalance(checked);}}
$allInputs.change(function(event){var $this=$(this);var id=event.target.id;var includeFunction=resolve[id];if(typeof includeFunction=="function"){includeFunction($this.is(":checked"));displayPayableAmount();}});}
return{getTotal:calculatePayableAmount,displayInterest:displayInterest,includeInterest:includeInterest,includeDunningFee:includeDunningFee,update:function(){$allInputs.change();displayPayableAmount();}};}
function createFormatter(view,i18n){var $debtCollectionCheckBox=$("#asDebtCollectionNotice",view);var $heading=$("h2.heading",view);var heading=$heading.html();var $dunningText=$("#dunningText");var dunningText=$dunningText.val();setupEventHandlers(view);$debtCollectionCheckBox.trigger("change");function modifyMessages(checked){if($debtCollectionCheckBox.is(":checked")){dunningText=$dunningText.val();$heading.html(i18n.debtCollectionHeader);$dunningText.val(i18n.debtCollectionDunningText).change();}else{$heading.html(heading);$dunningText.val(dunningText).change();}}
function setupEventHandlers(view){$debtCollectionCheckBox.change(function(event){modifyMessages();});}
return{}}}(jQuery,sendregning))
