/*Base, version 1.0.2;Copyright 2006, Dean Edwards;License: http://creativecommons.org/licenses/LGPL/2.1/*/
var Base = function() {
	if (arguments.length) {
		if (this == window) { // cast an object to this class
			Base.prototype.extend.call(arguments[0], arguments.callee.prototype);
		} else {
			this.extend(arguments[0]);
		}
	}
};

Base.version = "1.0.2";

Base.prototype = {
	extend: function(source, value) {
		var extend = Base.prototype.extend;
		if (arguments.length == 2) {
			var ancestor = this[source];
			// overriding?
			if ((ancestor instanceof Function) && (value instanceof Function) &&
				ancestor.valueOf() != value.valueOf() && /\bbase\b/.test(value)) {
				var method = value;
			//	var _prototype = this.constructor.prototype;
			//	var fromPrototype = !Base._prototyping && _prototype[source] == ancestor;
				value = function() {
					var previous = this.base;
				//	this.base = fromPrototype ? _prototype[source] : ancestor;
					this.base = ancestor;
					var returnValue = method.apply(this, arguments);
					this.base = previous;
					return returnValue;
				};
				// point to the underlying method
				value.valueOf = function() {
					return method;
				};
				value.toString = function() {
					return String(method);
				};
			}
			return this[source] = value;
		} else if (source) {
			var _prototype = {toSource: null};
			// do the "toString" and other methods manually
			var _protected = ["toString", "valueOf"];
			// if we are prototyping then include the constructor
			if (Base._prototyping) _protected[2] = "constructor";
			for (var i = 0; (name = _protected[i]); i++) {
				if (source[name] != _prototype[name]) {
					extend.call(this, name, source[name]);
				}
			}
			// copy each of the source object's properties to this object
			for (var name in source) {
				if (!_prototype[name]) {
					extend.call(this, name, source[name]);
				}
			}
		}
		return this;
	},

	base: function() {
		// call this method from any other method to invoke that method's ancestor
	}
};

Base.extend = function(_instance, _static) {
	var extend = Base.prototype.extend;
	if (!_instance) _instance = {};
	// build the prototype
	Base._prototyping = true;
	var _prototype = new this;
	extend.call(_prototype, _instance);
	var constructor = _prototype.constructor;
	_prototype.constructor = this;
	delete Base._prototyping;
	// create the wrapper for the constructor function
	var klass = function() {
		if (!Base._prototyping) constructor.apply(this, arguments);
		this.constructor = klass;
	};
	klass.prototype = _prototype;
	// build the class interface
	klass.extend = this.extend;
	klass.implement = this.implement;
	klass.toString = function() {
		return String(constructor);
	};
	extend.call(klass, _static);
	// single instance
	var object = constructor ? klass : _prototype;
	// class initialisation
	if (object.init instanceof Function) object.init();
	return object;
};

Base.implement = function(_interface) {
	if (_interface instanceof Function) _interface = _interface.prototype;
	this.prototype.extend(_interface);
};

/*
Non Base
*/
	var Cookies = {
		get: function(name) {
			var start = document.cookie.indexOf( name + "=" );
			var len = start + name.length + 1;
			if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
				return null;
			}
			if ( start == -1 ) return null;
			var end = document.cookie.indexOf( ';', len );
			if ( end == -1 ) end = document.cookie.length;
			return unescape(document.cookie.substring( len, end ));
		},
		set: function(name, value, expires, path, domain, secure) {
			var today = new Date();
			today.setTime( today.getTime() );
			if ( expires ) {
				expires = expires; // * 1000 * 60 * 60 * 24;
			}
			var expires_date = new Date( today.getTime() + (expires) );
			document.cookie = name+'='+escape( value ) +
				( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
				( ( path ) ? ';path=' + path : '' ) +
				( ( domain ) ? ';domain=' + domain : '' ) +
				( ( secure ) ? ';secure' : '' );
			return Cookies.get(name);
		},
		clear: function(name, path, domain) {
			if ( Cookies.get( name ) ) document.cookie = name + '=' +
					( ( path ) ? ';path=' + path : '') +
					( ( domain ) ? ';domain=' + domain : '' ) +
					';expires=Thu, 01-Jan-1970 00:00:01 GMT';
		},
		
		buildCookieArr: function(str) {
			var a = str.split("&");
			if(a.length<=1) return str;
			var x = {};
			for(var i=0, mi=a.length; i<mi; ++i) {
				var item = a[i].split("=");
				x[item[0]] = item[1];
			}
			return x;
		}
	}
	Function.prototype.bind = function() {
	  var __method = this, args = $A(arguments), object = args.shift();
	  return function() {
		return __method.apply(object, $A(arguments).concat(args));
	  }
	}
	function addEvent(obj, evType, fn, useCapture){
	  if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	  } else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	  } else {
		alert("Handler could not be attached");
	  }
	}
	function $$() {
	  var elements = new Array();
	  for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
		  element = document.getElementById(element);
		if (arguments.length == 1)
		  return element;
		elements.push(element);
	  }
	  return elements;
	}
	var $A = Array.from = function(iterable) {
	  if (!iterable) return [];
	  if (iterable.toArray) {
		return iterable.toArray();
	  } else {
		var results = [];
		for (var i = 0; i < iterable.length; i++)
		  results.push(iterable[i]);
		return results;
	  }
	}
	
	
/* ** END OF BASE ** */


function getExpandedState(item) {
	return Cookies.get("EXPANDED_" + item);
}
function setExpandedState(item, expanded) {
	Cookies.set("EXPANDED_" + item, expanded);
	return expanded;
}





function trim(str)
{
	return str.replace(/^(\s)+/, "").replace(/(\s)+$/, "");
}

function verifyOrgId(n)
{
	var ma = /^([0-9]{6})-([0-9]{4})$/.exec(n);
	return (ma && (calculateCheckDigit(ma[1] + ma[2].substring(0,3)) == ma[2].charAt(3)));
}

function verifyCreditCard(n) {
	var ma = n.match(/^(\d{4}-){3}|(\d{4} ){3}\d{4}|\d{15,16}|\d{4} \d{2} \d{4} \d{5}|\d{4}-\d{2}-\d{4}-\d{5}$/)
	if(ma) {
		return true;
	}
	return false;
}

function isNumeric(str) {
	return str.length ? !isNaN(str.replace(/\s/,"z")/1) : true
}


// 850709 - correct, 851300 - incorrect
var ValidateSSNDate = function(ssndate) {
		var switchYear = 10;
	var m = ssndate.match(/^(18|19|20)?(\d{2})(\d{2})(\d{2})$/);
	if(!m) return false;

	// Attempt to validate the entered date
	var d = new Date(); d.setFullYear((m[1]||(m[2]>switchYear?"19":"20"))+m[2]); d.setMonth(m[3]-1); d.setDate(m[4]);
	return (d.getFullYear()==((m[1]||(m[2]>switchYear?"19":"20"))+m[2]) && (d.getMonth()+1)==m[3] && d.getDate()==m[4]);
}

var ValidateSSNDate2 = function(ssndate) {
	var switchYear = 10;
	var m = ssndate.match(/^(\d{2})(\d{2})(\d{2})$/);
	if(!m) return false;

	// Attempt to validate the entered date
	//var d = new Date(); d.setFullYear((m[1]||(m[2]>switchYear?"19":"20"))+m[2]); d.setMonth(m[3]-1); d.setDate(m[4]);
	//return (d.getFullYear()==((m[1]||(m[2]>switchYear?"19":"20"))+m[2]) && (d.getMonth()+1)==m[3] && d.getDate()==m[4]);
	return true;
}


var SSN = Base.extend({
	ssn: null,		// compat. - validated ssn number (YYMMDDXXXX)
	errmsg: null,   // compat. - suitable error message
	valid: false,   // compat. - is the ssn valid
	
	messages: {
		nomatch: "Ifyllt personnummer verkar inte vara korrekt formaterat.",
		invaliddate: "Datumet i ifyllt personnummer verkar inte stämma.",
		checkdigit: "Ifyllt personnummer är inte korrekt."
	},
	
	segments: {
		full: null,
		year: null,
		month: null, // 1 based. (1 = January)
		date: null,
		checkdigit: null,
		birthnumber: null
	},
	
	constructor: function(num) {
		var switchYear = 10;
		var num = (num||"").replace(/\D/g, "");
		var m = num.match(/^(18|19|20)?((\d{2})(\d{2})(\d{2})\d{3})(\d{1})$/);
		this.ssn = num;
		
		// Attempt to match the ssn
		if(!m) { this.errmsg = this.messages.nomatch; return; }
		// Attempt to validate the entered date
		var d = new Date(); 
		d.setFullYear((m[1]||(m[3]>switchYear?"19":"20"))+m[3],parseFloat(m[4])-1,parseFloat(m[5])); 
		
		if(!(d.getFullYear()==(m[1]||(m[3]>switchYear?"19":"20"))+m[3] 
			&& (d.getMonth()+1)==m[4] 
			&& d.getDate()==m[5])) { 
			
			this.errmsg = this.messages.invaliddate; return;
			
		}
		
		// Attempt to validate the control number
		if(calculateCheckDigit(m[2]) != m[6]) { this.errmsg = this.messages.checkdigit; return; }
		
		// Our SSN is validated, fill in any required information.
		this.ssn = (m[1]||(m[3]>switchYear?"19":"20")) + m[2] + m[6];
		this.segments.full = this.ssn;
		this.segments.year = (m[1]||(m[3]>switchYear?"19":"20")) + m[3];
		this.segments.month = parseInt(m[4]);
		this.segments.date = parseInt(m[5]);
		this.segments.checkdigit = parseInt(m[6]);
		this.valid = true;
	}
});
var personnummer = SSN;


/*
function personnummer(nr) {
	nr = nr.replace(/-|\+/g, "");
	//var re = new RegExp("/^(18|19|20)?((\d{2})(\d{2})(\d{2})(\d{3})(\d{1}))$/")
	var match = nr.match(/^(18|19|20)?((\d{2})(\d{2})(\d{2})\d{3})(\d{1})$/);
	
	if(match)
	{	
		this.valid = (calculateCheckDigit(ma[2] + ma[3].substring(0,3)) == ma[3].charAt(3));
		this.ssn = (ma[1]?ma[1]:19) + ma[2] + ma[3];
		this.errmsg = "";
	}
	else
	{
		this.errmsg = "Personnummer ska anges med århundrade och bindestreck, t.ex. 19640823–3233";
		this.valid = false;
		this.ssn = nr;
	}
}
*/


function checkContactNumber(nr)
{
	this.valid = false;
	this.number = nr;
	nr = nr.replace(/[\s\-]*/g, "");
	var ma = nr.match(/^(0\d{6,12})$/)
	if(ma)
	{
		this.valid = true;
		this.number = nr;
	}

}

function formatNumber(obj)
{
	var ccn = new checkContactNumber(obj.value);
	obj.value = ccn.number;
}

function calculateCheckDigit(num)
{
    var i, n, sum = 0, l;
    
    num = num.toString();
    l = num.length;
    for(i = l - 1; i >= 0; i--)
    {
        n = parseInt(num.charAt(i)) * (2 - ((l + 3 - i) % 2));
        sum += parseInt(Math.floor(n / 10) + (n % 10));
	}
	return (10 - (sum % 10)) % 10;
}

function verifyEmail(email)
{
	return /^.+@.+\..+$/.test(email);
}

function verifyEmail_Verify(email1, email2)
{
	if(email1.toLowerCase() == email2.toLowerCase())
	 {
		return /^.+@.+\..+$/.test(email2);
	 }else{
		return false;
	 }
}

function verifyPhone(phone)
{
	return /^\d+$/.test(phone);
}


function verifyName(sName)
{
	if (!sName) return false;
	var Name = sName.replace(/^\s+|\s+$/g, '');
	if(Name.length>1)
	{
		for(var i=0; i<Name.length; ++i) {
		  var ch = Name.charAt(i);
		  if(ch==" " || ch=="-" || ch== "'") continue;
		  if(ch.toUpperCase() == ch.toLowerCase())
		      return false;   
		}
		return true;
	}
	return false;
}


function parseFloatEx(f)
{
	return parseFloat(f.toString().replace(",", "."));
}

function parseDate(dstr)
{
	var re = /^([0-9]{4})-([0-1][0-9])-([0-3][0-9])$/ig;
	var match = re.exec(dstr);
	if(!match) return null;
	if(match[2] < 1 || match[2] > 12) return null;
	var days = new Array(31,(parseInt(match[1]) % 4 ? 28 : 29),31,30,31,30,31,31,30,31,30,31);
	if(match[3] < 1 || match[3] > days[match[2] - 1]) return null;
	return new Date(match[1], match[2], match[3]);
}

Math.roundEx = function(number, numdecdig)
{
	if (numdecdig == null) return number;
	
	var n = Math.pow(10, numdecdig);
	
	number = Math.round(number * n);
	number = number / n;
	
	return number;
}

function coalesce(val1, val2)
{
	if (val1 != null && trim(val1) != "")
		return val1;
	else
		return val2;
}

Math.roundUp = function(number)
{
	var i = parseInt(number);
	if (i < number) i++;
	return i;
}

function min(value1, value2)
{
	return (value1 < value2 ? value1 : value2);
}

function max(value1, value2)
{
	return (value1 > value2 ? value1 : value2);
}

function formatPrice(price)
{
	price = Math.roundEx(price, 2);
	price = price.toString().split(".");
	var newPrice = "", j = 0;
	for (var i = price[0].length - 1; i >= 0; i--)
	{
		if(j && (j % 3) == 0) newPrice = "&nbsp;" + newPrice;
		newPrice = price[0].charAt(i) + newPrice;
		j++;
	}
	
	if (price.length == 2)
	{
		var dec = price[1];
		if (dec.length == 1) dec += "0";
		newPrice += "," + dec;
	}
	
	return newPrice;
}

function radio_getSelectedValue(sel)
{
	if (!sel.length)
		sel = new Array(sel);
	
	for(var i = 0; i < sel.length; i++)
	{
		if (sel[i].checked)
			return sel[i].value;
	}
}

function getAll( obj ) {
	if (document.getElementsByTagName) {
		x = document.getElementsByTagName(obj);
	} else { 
		if (document.all) {
			x = document.all.tags(obj);
		}
	}
	return x;
}

function getObject( obj ) {
    if (document.getElementById) {
        return document.getElementById(obj);
    } else if(document.layers) {
        return document.layers[obj];
    } else if(document.all) {
        return document.all[obj];
    } else {
        throw 'Inkompatibel webbläsare!';
    }
}

function hideObject( obj ) {
	var tmp = getObject(obj);
	if (tmp)
		tmp.style.display = tmp.style.display = 'none';
}

function ShowObject( obj ) {
	var tmp = getObject(obj);
	if (tmp)
		tmp.style.display = tmp.style.display = '';
}

function ShowHideObject( obj ) {
	var tmp = getObject(obj);
	$(tmp).toggle('slow');
	/*if (tmp)
		if (tmp.style.display == '')
		{
			hideObject(obj);
		}
		else
		{
			ShowObject(obj);
		}
	*/
}


function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function validateIMEI(imei) {
	imei = String(imei);
	cs = 0;

	for(var i=0;i<14;i+=2) {
		var dodd = parseInt(imei.charAt(i+1)<<1);
		cs += parseInt(imei.charAt(i)) + parseInt((dodd/10)+(dodd%10));
	}
	
	cs = (10-(cs%10))%10;

	return(String(cs)==imei.charAt(14))
}

function validateICC(iccid) 
{
	var length = iccid.length;
	var sum = 0;
	var weight = 2;
	var ICCOk = false;
	var x = 0;
	if( ( length == 20 ) && ( iccid.substring(0,5) == "89462" ) )
	{		
		for(i=0; i<19; i++)
		{
			x = parseInt(iccid.charAt((i))) * weight;
			if(x >= 10)
			{
				x = x - 9;
			}
			sum = sum + x;
			weight = (weight % 2) + 1;
		}
		sum = sum % 10;
		if(sum != 0)
		{
			sum = 10 - sum;
		}
		
		ICCOk = parseInt(iccid.charAt(19)) == sum;
		
	}
	else
	{
		ICCOk = false;
	}
	
	return ICCOk;
}

function validatePhoneNo(phoneno)
{
	//a number that is 8-10 digits, starts with zero and second digit isn't zero/seven
	return /^0[12345689]\d{6,8}$/.test(trim(phoneno));
}

function validateCellPhoneNo(cellphoneno)
{
	//a number that is 10 digits and starts with 07
	return /^07\d{8}$/.test(trim(cellphoneno));
}

function orderWait(baseUrl)
{
	var imgUrl = baseUrl + "/images/button/order_wait.gif";
	
	var el = document.getElementById("orderbutton_container");
	
	if (el)
		el.innerHTML = "<img src=\"" + imgUrl + "\" alt=\"Vänta...\" width=\"115\" height=\"53\" border=\"0\">";
}

var lastConfirm = null;

function leaveConfirm()
{
	if (lastConfirm != null)
		return false;
	else
	{
		var c = confirm("Du lämnar nu webbutiken. Vill du fortsätta?");
		lastConfirm = c;
		setTimeout("lastConfirm = null;", 500);
		return c;
	}
}

function leave(url)
{
	if (leaveConfirm())
		location.href = url;
}

function showCpsServices()
{
	alert("CPS");
}

function showFixedServices()
{
	alert("Fixed");
}

function saveCookie(name, value)
{
    if(name)
    {
        document.cookie = name + "=" + escape(value) + "; path=/";
    }
}

function ChooseAndLeave( inp ) {
	 var email;
	 var bMailok
	 email=document.frm.PU_Email.value;
	 bMailok = verifyEmail(email);
	 //alert(sMailok);
	 if (bMailok)
	 {
		location.href = inp+email;
	 }
	 else
		alert("Kontrollera epostadressen");
	// this.close();
}

function PoupTerminate() {
	this.close();
}

function trySubmit(frm) {
	var result = true;
	if(frm.onsubmit)
		result = frm.onsubmit();
	if(result) frm.submit();
}

function setFieldSelected(id)
{	

	var el = document.getElementById(id);
	if(!el){ 
	return false;
	}
	
	if (el&&el.type!='hidden'){
	
		el.focus();
		/*if(el.defaultChecked) el.checked = true;*/
	}

}

function imgPopup(url,x,y,namn){   
	MyWin = window.open("","","width=" + x + ",height=" + y + ",toolbar=no,location=no,directories=no,status=no,menubar=no");
	with(MyWin.document){
	open();
	write("<ht"+"ml>\n<he"+"ad>\<tit"+"le>"+namn+"</tit"+"le>\n</he"+"ad>\n<bo"+"dy marginwidth=0 marginheight=0 leftmargin=0 topmargin=0 rightmargin=0>\n");
	write("<img src=\"" + url + "\" width=\"" + x + "\" height=\"" + y + "\">\n");
	write("</bo"+"dy>\n</ht"+"ml>\n");
	close();
	}
}



