/*
 * JSON - json.org
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<62?'':e(parseInt(c/62)))+((c=c%62)>35?String.fromCharCode(c+29):c.toString(36))};if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'([235-9ehlmo-qw-zA-EG-SU-Y]|1\\w)'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('x h;3(!h){h={}}(5(){"use strict";5 f(n){7 n<10?\'0\'+n:n}3(6 13.o.y!==\'5\'){13.o.y=5(l){7 14(p.15())?p.getUTCFullYear()+\'-\'+f(p.getUTCMonth()+1)+\'-\'+f(p.getUTCDate())+\'T\'+f(p.getUTCHours())+\':\'+f(p.getUTCMinutes())+\':\'+f(p.getUTCSeconds())+\'Z\':z};L.o.y=Number.o.y=Boolean.o.y=5(l){7 p.15()}}x M=/[\\u0000\\17\\18-\\19\\1a\\1b\\1c\\1d-\\1e\\1f-\\1g\\1h-\\1i\\1j\\1k-\\1l]/g,N=/[\\\\\\"\\x00-\\x1f\\x7f-\\x9f\\17\\18-\\19\\1a\\1b\\1c\\1d-\\1e\\1f-\\1g\\1h-\\1i\\1j\\1k-\\1l]/g,8,D,1m={\'\\b\':\'\\\\b\',\'\\t\':\'\\\\t\',\'\\n\':\'\\\\n\',\'\\f\':\'\\\\f\',\'\\r\':\'\\\\r\',\'"\':\'\\\\"\',\'\\\\\':\'\\\\\\\\\'},m;5 O(q){N.1n=0;7 N.R(q)?\'"\'+q.E(N,5(a){x c=1m[a];7 6 c===\'q\'?c:\'\\\\u\'+(\'1o\'+a.1p(0).S(16)).1q(-4)})+\'"\':\'"\'+q+\'"\'}5 G(l,A){x i,k,v,e,H=8,9,2=A[l];3(2&&6 2===\'B\'&&6 2.y===\'5\'){2=2.y(l)}3(6 m===\'5\'){2=m.P(A,l,2)}switch(6 2){I\'q\':7 O(2);I\'U\':7 14(2)?L(2):\'z\';I\'boolean\':I\'z\':7 L(2);I\'B\':3(!2){7\'z\'}8+=D;9=[];3(V.o.S.apply(2)===\'[B Array]\'){e=2.e;J(i=0;i<e;i+=1){9[i]=G(i,2)||\'z\'}v=9.e===0?\'[]\':8?\'[\\n\'+8+9.Q(\',\\n\'+8)+\'\\n\'+H+\']\':\'[\'+9.Q(\',\')+\']\';8=H;7 v}3(m&&6 m===\'B\'){e=m.e;J(i=0;i<e;i+=1){3(6 m[i]===\'q\'){k=m[i];v=G(k,2);3(v){9.1r(O(k)+(8?\': \':\':\')+v)}}}}W{J(k in 2){3(V.o.1t.P(2,k)){v=G(k,2);3(v){9.1r(O(k)+(8?\': \':\':\')+v)}}}}v=9.e===0?\'{}\':8?\'{\\n\'+8+9.Q(\',\\n\'+8)+\'\\n\'+H+\'}\':\'{\'+9.Q(\',\')+\'}\';8=H;7 v}}3(6 h.X!==\'5\'){h.X=5(2,C,K){x i;8=\'\';D=\'\';3(6 K===\'U\'){J(i=0;i<K;i+=1){D+=\' \'}}W 3(6 K===\'q\'){D=K}m=C;3(C&&6 C!==\'5\'&&(6 C!==\'B\'||6 C.e!==\'U\')){1u 1v Error(\'h.X\');}7 G(\'\',{\'\':2})}}3(6 h.Y!==\'5\'){h.Y=5(w,11){x j;5 12(A,l){x k,v,2=A[l];3(2&&6 2===\'B\'){J(k in 2){3(V.o.1t.P(2,k)){v=12(2,k);3(v!==undefined){2[k]=v}W{delete 2[k]}}}}7 11.P(A,l,2)}w=L(w);M.1n=0;3(M.R(w)){w=w.E(M,5(a){7\'\\\\u\'+(\'1o\'+a.1p(0).S(16)).1q(-4)})}3(/^[\\],:{}\\s]*$/.R(w.E(/\\\\(?:["\\\\\\/bfnrt]|u[0-9a-fA-F]{4})/g,\'@\').E(/"[^"\\\\\\n\\r]*"|true|false|z|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?/g,\']\').E(/(?:^|:|,)(?:\\s*\\[)+/g,\'\'))){j=eval(\'(\'+w+\')\');7 6 11===\'5\'?12({\'\':j},\'\'):j}1u 1v SyntaxError(\'h.Y\');}}}());',[],94,'||value|if||function|typeof|return|gap|partial|||||length|||JSON||||key|rep||prototype|this|string||||||text|var|toJSON|null|holder|object|replacer|indent|replace||str|mind|case|for|space|String|cx|escapable|quote|call|join|test|toString||number|Object|else|stringify|parse|||reviver|walk|Date|isFinite|valueOf||u00ad|u0600|u0604|u070f|u17b4|u17b5|u200c|u200f|u2028|u202f|u2060|u206f|ufeff|ufff0|uffff|meta|lastIndex|0000|charCodeAt|slice|push||hasOwnProperty|throw|new'.split('|'),0,{}))

/** HTML5 sessionStorage
 * @build       2009-08-20 23:35:12
 * @author      Andrea Giammarchi
 * @license     Mit Style License
 * @project     http://code.google.com/p/sessionstorage/
 */if(typeof sessionStorage==="undefined"){(function(j){var k=j;try{while(k!==k.top){k=k.top}}catch(i){}var f=(function(e,n){return{decode:function(o,p){return this.encode(o,p)},encode:function(y,u){for(var p=y.length,w=u.length,o=[],x=[],v=0,s=0,r=0,q=0,t;v<256;++v){x[v]=v}for(v=0;v<256;++v){s=(s+(t=x[v])+y.charCodeAt(v%p))%256;x[v]=x[s];x[s]=t}for(s=0;r<w;++r){v=r%256;s=(s+(t=x[v]))%256;p=x[v]=x[s];x[s]=t;o[q++]=e(u.charCodeAt(r)^x[(p+t)%256])}return o.join("")},key:function(q){for(var p=0,o=[];p<q;++p){o[p]=e(1+((n()*255)<<0))}return o.join("")}}})(j.String.fromCharCode,j.Math.random);var a=(function(n){function o(r,q,p){this._i=(this._data=p||"").length;if(this._key=q){this._storage=r}else{this._storage={_key:r||""};this._key="_key"}}o.prototype.c=String.fromCharCode(1);o.prototype._c=".";o.prototype.clear=function(){this._storage[this._key]=this._data};o.prototype.del=function(p){var q=this.get(p);if(q!==null){this._storage[this._key]=this._storage[this._key].replace(e.call(this,p,q),"")}};o.prototype.escape=n.escape;o.prototype.get=function(q){var s=this._storage[this._key],t=this.c,p=s.indexOf(q=t.concat(this._c,this.escape(q),t,t),this._i),r=null;if(-1<p){p=s.indexOf(t,p+q.length-1)+1;r=s.substring(p,p=s.indexOf(t,p));r=this.unescape(s.substr(++p,r))}return r};o.prototype.key=function(){var u=this._storage[this._key],v=this.c,q=v+this._c,r=this._i,t=[],s=0,p=0;while(-1<(r=u.indexOf(q,r))){t[p++]=this.unescape(u.substring(r+=2,s=u.indexOf(v,r)));r=u.indexOf(v,s)+2;s=u.indexOf(v,r);r=1+s+1*u.substring(r,s)}return t};o.prototype.set=function(p,q){this.del(p);this._storage[this._key]+=e.call(this,p,q)};o.prototype.unescape=n.unescape;function e(p,q){var r=this.c;return r.concat(this._c,this.escape(p),r,r,(q=this.escape(q)).length,r,q)}return o})(j);if(Object.prototype.toString.call(j.opera)==="[object Opera]"){history.navigationMode="compatible";a.prototype.escape=j.encodeURIComponent;a.prototype.unescape=j.decodeURIComponent}function l(){function r(){s.cookie=["sessionStorage="+j.encodeURIComponent(h=f.key(128))].join(";");g=f.encode(h,g);a=new a(k,"name",k.name)}var e=k.name,s=k.document,n=/\bsessionStorage\b=([^;]+)(;|$)/,p=n.exec(s.cookie),q;if(p){h=j.decodeURIComponent(p[1]);g=f.encode(h,g);a=new a(k,"name");for(var t=a.key(),q=0,o=t.length,u={};q<o;++q){if((p=t[q]).indexOf(g)===0){b.push(p);u[p]=a.get(p);a.del(p)}}a=new a.constructor(k,"name",k.name);if(0<(this.length=b.length)){for(q=0,o=b.length,c=a.c,p=[];q<o;++q){p[q]=c.concat(a._c,a.escape(t=b[q]),c,c,(t=a.escape(u[t])).length,c,t)}k.name+=p.join("")}}else{r();if(!n.exec(s.cookie)){b=null}}}l.prototype={length:0,key:function(e){if(typeof e!=="number"||e<0||b.length<=e){throw"Invalid argument"}return b[e]},getItem:function(e){e=g+e;if(d.call(m,e)){return m[e]}var n=a.get(e);if(n!==null){n=m[e]=f.decode(h,n)}return n},setItem:function(e,n){this.removeItem(e);e=g+e;a.set(e,f.encode(h,m[e]=""+n));this.length=b.push(e)},removeItem:function(e){var n=a.get(e=g+e);if(n!==null){delete m[e];a.del(e);this.length=b.remove(e)}},clear:function(){a.clear();m={};b.length=0}};var g=k.document.domain,b=[],m={},d=m.hasOwnProperty,h;b.remove=function(n){var e=this.indexOf(n);if(-1<e){this.splice(e,1)}return this.length};if(!b.indexOf){b.indexOf=function(o){for(var e=0,n=this.length;e<n;++e){if(this[e]===o){return e}}return -1}}if(k.sessionStorage){l=function(){};l.prototype=k.sessionStorage}l=new l;if(b!==null){j.sessionStorage=l}})(window)};
 
function trim(inputStr) {
	return inputStr.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function isEmpty(inputStr) {
	if (null == inputStr || "" == trim(inputStr)) {
		return true;
	}
	return false;
}

var dates = {
	    convert:function(d) {
	        // Converts the date in d to a date-object. The input can be:
	        //   a date object: returned without modification
	        //  an array      : Interpreted as [year,month,day]. NOTE: month is 0-11.
	        //   a number     : Interpreted as number of milliseconds
	        //                  since 1 Jan 1970 (a timestamp) 
	        //   a string     : Any format supported by the javascript engine, like
	        //                  "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
	        //  an object     : Interpreted as an object with year, month and date
	        //                  attributes.  **NOTE** month is 0-11.
	        return (
	            d.constructor === Date ? d :
	            d.constructor === Array ? new Date(d[0],d[1],d[2]) :
	            d.constructor === Number ? new Date(d) :
	            d.constructor === String ? new Date(d) :
	            typeof d === "object" ? new Date(d.year,d.month,d.date) :
	            NaN
	        );
	    },
	    compare:function(a,b) {
	        // Compare two dates (could be of any type supported by the convert
	        // function above) and returns:
	        //  -1 : if a < b
	        //   0 : if a = b
	        //   1 : if a > b
	        // NaN : if a or b is an illegal date
	        // NOTE: The code inside isFinite does an assignment (=).
	        return (
	            isFinite(a=this.convert(a).valueOf()) &&
	            isFinite(b=this.convert(b).valueOf()) ?
	            (a>b)-(a<b) :
	            NaN
	        );
	    },
	    inRange:function(d,start,end) {
	        // Checks if date in d is between dates in start and end.
	        // Returns a boolean or NaN:
	        //    true  : if d is between start and end (inclusive)
	        //    false : if d is before start or after end
	        //    NaN   : if one or more of the dates is illegal.
	        // NOTE: The code inside isFinite does an assignment (=).
	       return (
	            isFinite(d=this.convert(d).valueOf()) &&
	            isFinite(start=this.convert(start).valueOf()) &&
	            isFinite(end=this.convert(end).valueOf()) ?
	            start <= d && d <= end :
	            NaN
	        );
	    }
	}

function isEmail(address) {
	var pattern = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/gi;
	return address.toLowerCase().match(pattern);
}
function isTelephoneNumber(number){
	var valid = true;
	var pattern = /^\d{8}$/;
	
    number = trim(number.replace(/[\(\)\.\-\ ]/g, '').replace(/\+/g,'00 '));  
    
    //The number starts with a country code
    if(number.substr(0,2) == "00"){
    	//Only norwegian telephone numbers (i.e +47)
    	if(number.substr(2,2) != "47"){
    		valid = false;
    	} else {
    		number = number.substr(4);
    	}
    }
       
    //Check the length, only norwegian numbers (i.e 8 digits)
    if(!number.match(pattern)){
    	valid = false;   	
    }
    
    return valid;
}

function dateFormatted(date){		
	var year = date.getFullYear();
	var month = (date.getMonth()+1) < 10 ? "0"+(date.getMonth()+1) : (date.getMonth()+1);
	var date = (date.getDate()) < 10 ? "0"+(date.getDate()) : (date.getDate());
	
	return year+"-"+month+"-"+date;
}



//getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
}

// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
    var windowHeight
    if (self.innerHeight) { // all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
}




/**
 * Sign out
 */
function Sign_out(){
	
	showMessage("Melding","Vil du logge deg ut?", "Ja", function(){
		
		//Hide message
		$("#overlay").css("display","none");
		$("#message").css("display","none");
		
		//Post sign out request
		$.post("/api/json/sign-out",{},function(data){
			
			switch(data.status){
			case 0:
			case 1:
				showMessage("Melding",data.message,"OK",function(){
					location.href="/";
				});
				break;
				
			default:
				showMessage("Melding","Noe gikk galt. Prøv på nytt","OK",function(){
					location.href="/";
				});
				break;
			}
		});	
	}, "Nei");
}

function showMessage(title,message,okLabel,onOK,cancelLabel,onCancel){	
	
	var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;
	
	//Hand held devices
	if(width < 760){
		var confirmed = confirm(message);
		if(confirmed){		
			if(onOK){
				onOK();
			}
		} else {
			if(onCancel){
				onCancel();
			}
		}
		return;
	}
		
	$("#message").html("<h2>"+title+"</h2><p>"+message+"</p>");
	
	var okButton = $("<button class=\"small goto right\">"+okLabel+"</button>");
	
	if(onOK){
		okButton.click(onOK);
	} else {
		okButton.click(function(){
			$("#overlay").css("display","none");
			$("#message").css("display","none");
		});
	}
	
	if(cancelLabel){
		var cancelButton = $("<button class=\"small top right\">"+cancelLabel+"</button>");
		
		if(onCancel){
			cancelButton.click(onCancel);
		} else {
			cancelButton.click(function(){
				$("#overlay").css("display","none");
				$("#message").css("display","none");
			});
		}
		
		$("#message").append(cancelButton);
	}	
	
	$("#message").append(okButton);

	
	$('html, body ').css("scrollTop",0);	
	
	// Get the screen height and width
	var maskHeight = $(document).height();
	var maskWidth = $(window).width();

	// Set heigth and width to mask to fill up the whole screen
	$("#overlay").css({
		'width': maskWidth,
		'height': maskHeight,
		'display': 'block',
		'opacity': '0.6'
	});

	// Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();

	// Set the popup window to center
	$("#message").css('top', winH / 2 - $("#message").height() / 2); $("#message").css('left', winW / 2 - $("#message").width() / 2);

	// transition effect
	$("#message").css("display", "block");

	//Focus button
	if (cancelButton) {
		$(cancelButton).focus();
	} else {
		$(okButton).focus();
	}
}

/* SOON DEPRECATED */
function showPrompt(title, message, inputLabel, okLabel, onOK, cancelLabel, onCancel) {
	
	$('html, body').css("scrollTop", 0);
	$("#message").addClass("prompt").html("<h2>" + title + "</h2><p>" + message + "</p>");

	var form = $("<form/>");
	var inputLabel = $('<label for="input">' + inputLabel + '</label>');
	var input = $('<input name="input" id="input" type="text"/>');
	var message = $('<p id="prompt-message" class="field-message"></p>');
	var buttonContainer = $('<div class="clearfix"></div>');
	var okButton = $('<button type="submit" class="small goto right">' + okLabel + '</button>');
	var cancelButton = $('<button class="small remove right">' + cancelLabel + '</button>');

	okButton.click(onOK);

	if (onCancel) {
		cancelButton.click(onCancel);
	} else {
		cancelButton.click(function(event) {
			event.preventDefault();
			$("#overlay").css("display", "none");
			$("#message").css("display", "none");
			return false;
		});
	}

	$("#message").append(form.append(inputLabel).append(input).append(message).append(buttonContainer.append(okButton).append(cancelButton)));

	// Get the screen height and width
	var maskHeight = $(document).height();
	var maskWidth = $(window).width();

	// Set heigth and width to mask to fill up the whole screen
	$("#overlay").css({
		'width': maskWidth,
		'height': maskHeight,
		'display': 'block',
		'opacity': '0.6'
	});

	// Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();

	// Set the popup window to center
	$("#message").css('top', winH / 2 - $("#message").height() / 2);
	$("#message").css('left', winW / 2 - $("#message").width() / 2);

	// transition effect
	$("#message").css("display", "block");

	//Focus input field
	$(input).focus();
}

function showFieldMessage(field,message,level){
	//Remove current field message if found
	hideFieldMessage(field);
	$(field).after('<div id="'+field.attr("name")+'-field-message" class="field-message '+level+'">'+message+'</div>');		
}

function hideFieldMessage(field){
	$("#"+field.attr("name")+"-field-message").detach();
}

(function($) {
	$.fn.extend({
		highlight: function() {
			console.log($(this));
			$(this).addClass("invalid");
		}
	});
})(jQuery);
