/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;

var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};

function validateForm() {
	if(document.getElementById('user-name').value != "" && document.getElementById('user-email').value != "") {
		document.getElementById('register-form').submit();
	}
	else {
		alert("Kontrollera att namn och e-post är ifyllt korrekt.");
	}
}

function toggleDisplay(id) {
	var object, vis;
	if(document.getElementById) {
		object = document.getElementById( id );
	}
	else if(document.all) {
		object = document.all[id];
	}
	else if(document.layers) {
		object = document.layers[id];
	}
	vis = object.style;
	if(vis.display == '' && object.offsetWidth != undefined && object.offsetHeight != undefined) {
		vis.display = (object.offsetWidth != 0 && object.offsetHeight != 0) ? 'block' : 'none';
	}
	vis.display = (vis.display == '' || vis.display == 'block') ? 'none' : 'block';
}

function updateUser(id) {
	if(document.getElementById('profile_delete').checked == true) {
		if(confirm("Är du säker på att du vill radera din användare?")) {
			return true;
		}
		else {
			return false;
		}
	}
	else {
		return true;
	}
}

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;

			if (jQuery.isFunction(label)) {
				if (!times)
					times = fn;
				fn = label;
				label = interval;
			}

			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}

			times = times || 0;
			belay = belay || false;

			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});

			if (!timers[label])
				timers[label] = {};

			fn.timerID = fn.timerID || this.guid++;

			var handler = function() {
				if (belay && this.inProgress)
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};

			handler.timerID = fn.timerID;

			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);

			this.global.push( element );

		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;

			if ( timers ) {

				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}

					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}

				for ( ret in timers ) break;
				if ( !ret )
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});

$(function() {
	$("#submit_form input").keypress(function (e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$('#submit_form').submit();
			return false;
		} else {
			return true;
		}
    });
});

function bindCloseNotification()
{
	$(".closeNotification").unbind();
	$(".closeNotification").click(function(event) {
		event.preventDefault();
		$("#notification").hide();
	});
}


$(document).ready(function() {
	$("#dibs_submit").click(function(event) {
		event.preventDefault();
		// Grey down the button and remove bind so it cant be clicked again
		$("#dibs_submit").removeClass("pink").addClass("grey").html("...").unbind();
		var cart_id = $("input[name=orderNo]").val();
		setTimeout("document.getElementById('order_form').submit();",3000);
		$.ajax({
			type: "GET",
			url: "/scripts/reserve_products.php",
			data:{id:cart_id},
			dataType: "html",
			success: function(data) {
				$("input[name=timerStart]").val(data);
				document.getElementById('order_form').submit();
			}
		});
	});
	
	$(".blogAbout").click(function(event) {
		event.preventDefault();
		var product_id = $(this).attr("title");
		$.get("/scripts/blog_product.php", {product: product_id},
		   function(data){
		     	$("#notification").html(data);
				$("#notification").dialog({
					width: 300,
					modal: true
				});
				$("#notification").dialog('open');
		});
	});
	$(".tipAFriend").click(function(event) {
		event.preventDefault();
		$("#tip-a-friend").dialog({
			autoOpen: false,
			width: 300,
			modal: true,
			buttons: {
				"Skicka": function() {
					$('#tip_product').submit();
				}
			}
		});
		$("#tip-a-friend").dialog('open');
	});

        $(".getGmail").click(function(event) {
		event.preventDefault();
		$("#import_contacts").dialog({
			autoOpen: false,
			width: 300,
			modal: true,
			buttons: {
				"Skicka": function() {
					$('#tip_product').submit();
				}
			}
		});
		$("#import_contacts").dialog('open');
	});

	$(".klarna-more-info").click(function(event) {
		event.preventDefault();
		$("#klarna-about").dialog({
			autoOpen: false,
			width: 300,
			modal: true
		});
		$("#klarna-about").dialog('open');
	});
	$('#select_salary').change(function() {
		if($('#payment_split').attr('checked')) {

			var payment = $('#select_salary option:selected').val();

			// 495
			if(payment == 215 || payment == 387) {
				fixPrice(495);
			}

			// 395
			else if(payment == 265) {
				fixPrice(395);
			}

			// 295
			else if(payment == 117 || payment == 118) {
				fixPrice(295);
			}

			// 195
			else if(payment == 293 || payment == 427) {
				fixPrice(195);
			}

			// 95
			else if(payment == 115) {
				fixPrice(95);
			}

			// 39.95

			else if(payment == 241) {
				fixPrice(39.95);
			}

			// 29.95

			else if(payment == 425 || payment == 210) {
				fixPrice(29.95);
			}

			// 19.95

			else if(payment == 428) {
				fixPrice(19.95);
			}

			// 0
			else if(payment == 373 || payment == 496 || payment == 495) {
				fixPrice(0);
			}
		}
	});

	$('#payment_split').click(function() {
		var orgprice = roundNum($('#totprice_field').val(), 2);
		if(!$('#payment_split').attr('checked')) {
			$('#cart_service_sum').text(0);
			$('#handling_fee').hide();
			$('#select_salary').val("0");
			$('#cart_total_sum').html(orgprice);
		}
		else {
			$('#handling_fee').show();
		}
	});

	$('#dialog').dialog({
		autoOpen: false,
		width: 300,
		modal: true,
		buttons: {
			"Skicka": function() {
				$('#tips_campaign').submit();
			}
		}
	});

	$('.dialog_login_se').dialog({
		autoOpen: false,
		width: 300,
		modal: true,
		buttons: {
			"Logga in": function() {
				$('#dialog_login_form').submit();
			}
		}
	});

	$('.dialog_login_no').dialog({
		autoOpen: false,
		width: 300,
		modal: true,
		buttons: {
			"Logg inn": function() {
				$('#dialog_login_form').submit();
			}
		}
	});

	$('.dialog_login_fi').dialog({
		autoOpen: false,
		width: 300,
		modal: true,
		buttons: {
			"Kirjaudu": function() {
				$('#dialog_login_form').submit();
			}
		}
	});

	$('.dialog_login_dk').dialog({
		autoOpen: false,
		width: 300,
		modal: true,
		buttons: {
			"Log ind": function() {
				$('#dialog_login_form').submit();
			}
		}
	});

	$('.send_tips_dialog').click(function() {
		var target = $(this).attr("id");
		target = target.substr(5, (target.length-5));
		$('#tips_target').val(target);
		$('#dialog').dialog('open');
		return false;
	});

	$('.open_login').click(function() {
		$('#dialog_login').dialog('open');
		$('#dialog_username').focus();
		return false;
	});

	var service_sum = $('#cart_service_sum').text();

	function fixPrice(price) {
		var orgprice = roundNum($('#totprice_field').val(), 2);
		var price = roundNum(price, 2);
		var total = orgprice+price;

		if(price > 0) {
			$('#cart_service_sum').show();
			$('#cart_service_sum').html(price);
		}
		$('#cart_total_sum').empty();
		$('#cart_total_sum').html(total);
	}

	function roundNum(num, dec) {
		num = parseFloat(num);
		var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
		return result;
	}
});

var xmlhttp = false;
try {
	// Firefox, Opera 8.0+, Safari
	xmlhttp = new XMLHttpRequest();
}
catch (e) {
	// Internet Explorer
	try {
    	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
	catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
    	catch (e) {
			alert("Your browser does not support AJAX!");
			xmlhttp = false;
		}
	}
}


function nextImage(id,num) {
	var reciever = document.getElementById("imgCont");
	xmlhttp.open("POST", "/scripts/slideshow.php?id="+id+"&num="+num);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			reciever.innerHTML = "";
			reciever.innerHTML = "<a href=\"#\" onclick=\"tb_show(this.getAttribute('name'),'/images/products/"+xmlhttp.responseText+"')\"><img src=\"/images/products/400_"+xmlhttp.responseText+"\" alt=\"Produktbild\" width=\"320\" height=\"400\" class=\"product_image_large\" /></a>";
		}
	}
	xmlhttp.send(null);
}

function initColor(){
	var c=0;
	var lastOption = null;
	$("#prod-color > option").each(function(){
		if(0!=this.value){
			c++;
			lastOption = this;
		}
	});
	if(1==c && null!=lastOption){
		$("#prod-color").val(lastOption.value);
		$("#prod-color").change();
		$("#prod-color").replaceWith('<input type="hidden" name="prod_color" id="prod-color" value="'+lastOption.value+'" /><p class="product_property">'+lastOption.innerHTML+'</p>');
	}
}

function colorSize(color,id) {
	var reciever = document.getElementById("prod-sizes");
	xmlhttp.open("POST", "/scripts/colorsize.php?id="+id+"&color="+color);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			if(xmlhttp.responseText.indexOf('rel="No Size"')>=0){ //if it's no size we also want to remove the label
				$("#prod-sizes").parent().html(xmlhttp.responseText);
			}else{
				$("#prod-sizes").html(xmlhttp.responseText);
			}
		}
	}
	xmlhttp.send(null);
}

function updateCart(id,amount,user) {

	var paytype = $("input[@name='payment_type']:checked").val();

	$.ajax({
		type: "GET",
		url: "/scripts/updatecart.php",
		data:{id:id,amount:amount,uid:user,type:paytype},
		dataType: "html",
		success: function() {
			/*if(data != "") {
				$("#cart_table").empty();
				$(data).appendTo("#cart_table");
			}*/
			//document.location = "/cart/";
                        document.location.reload();
		}
	});
}

function updateTime() {
	var reciever = document.getElementById("tleft");
	xmlhttp.open("POST", "/scripts/timeleft.php");
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			reciever.innerHTML = "";
			reciever.innerHTML = xmlhttp.responseText;
		}
	}
	xmlhttp.send(null);
}

function saveUsername(user) {
	var reciever = document.getElementById("remember-me");
	xmlhttp.open("POST", "/scripts/remember.php?email="+user);
	xmlhttp.onreadystatechange = function() {

		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			if(xmlhttp.responseText == "success") {
				reciever.style.display = "none";
			}
		}
	}
	xmlhttp.send(null);
}

/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var tb_pathToImage = "/images/loader.gif";
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
//on page load call tb_init
$(document).ready(function(){
  tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
  imgLoader = new Image();// preload image
  imgLoader.src = tb_pathToImage;
});
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
  $(domChunk).click(function(){
  var t = this.title || this.name || null;
  var a = this.href || this.alt;
  var g = this.rel || false;
  tb_show(t,a,g);
  this.blur();
  return false;
  });
}
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
  try {
    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
      $("body","html").css({height: "100%", width: "100%"});
      $("html").css("overflow","hidden");
      if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
        $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
        $("#TB_overlay").click(tb_remove);
      }
    }else{//all others
      if(document.getElementById("TB_overlay") === null){
        $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
        $("#TB_overlay").click(tb_remove);
      }
    }

    if(tb_detectMacXFF()){
      $("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
    }else{
      $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
    }

    if(caption===null){caption="";}
    $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
    $('#TB_load').show();//show loader

    var baseURL;
     if(url.indexOf("?")!==-1){ //ff there is a query string involved
      baseURL = url.substr(0, url.indexOf("?"));
     }else{
         baseURL = url;
     }

     var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
     var urlType = baseURL.toLowerCase().match(urlString);
    if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images

      TB_PrevCaption = "";
      TB_PrevURL = "";
      TB_PrevHTML = "";
      TB_NextCaption = "";
      TB_NextURL = "";
      TB_NextHTML = "";
      TB_imageCount = "";
      TB_FoundURL = false;
      if(imageGroup){
        TB_TempArray = $("a[@rel="+imageGroup+"]").get();
        for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
          var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
            if (!(TB_TempArray[TB_Counter].href == url)) {
              if (TB_FoundURL) {
                TB_NextCaption = TB_TempArray[TB_Counter].title;
                TB_NextURL = TB_TempArray[TB_Counter].href;
                TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
              } else {
                TB_PrevCaption = TB_TempArray[TB_Counter].title;
                TB_PrevURL = TB_TempArray[TB_Counter].href;
                TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
              }
            } else {
              TB_FoundURL = true;
              TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);
            }
        }
      }
      imgPreloader = new Image();
      imgPreloader.onload = function(){
      imgPreloader.onload = null;

      // Resizing large images - orginal by Christian Montoya edited by me.
      var pagesize = tb_getPageSize();
      var x = pagesize[0] - 150;
      var y = pagesize[1] - 150;
      var imageWidth = imgPreloader.width;
      var imageHeight = imgPreloader.height;
      if (imageWidth > x) {
        imageHeight = imageHeight * (x / imageWidth);
        imageWidth = x;
        if (imageHeight > y) {
          imageWidth = imageWidth * (y / imageHeight);
          imageHeight = y;
        }
      } else if (imageHeight > y) {
        imageWidth = imageWidth * (y / imageHeight);
        imageHeight = y;
        if (imageWidth > x) {
          imageHeight = imageHeight * (x / imageWidth);
          imageWidth = x;
        }
      }
      // End Resizing

      TB_WIDTH = imageWidth + 30;
      TB_HEIGHT = imageHeight + 60;
      $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>X</a> / Esc</div>");

      $("#TB_closeWindowButton").click(tb_remove);

      if (!(TB_PrevHTML === "")) {
        function goPrev(){
          if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
          $("#TB_window").remove();
          $("body").append("<div id='TB_window'></div>");
          tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
          return false;
        }
        $("#TB_prev").click(goPrev);
      }

      if (!(TB_NextHTML === "")) {
        function goNext(){
          $("#TB_window").remove();
          $("body").append("<div id='TB_window'></div>");
          tb_show(TB_NextCaption, TB_NextURL, imageGroup);
          return false;
        }
        $("#TB_next").click(goNext);

      }
      document.onkeydown = function(e){
        if (e == null) { // ie
          keycode = event.keyCode;
        } else { // mozilla
          keycode = e.which;
        }
        if(keycode == 27){ // close
          tb_remove();
        } else if(keycode == 190){ // display previous image
          if(!(TB_NextHTML == "")){
            document.onkeydown = "";
            goNext();
          }
        } else if(keycode == 188){ // display next image
          if(!(TB_PrevHTML == "")){
            document.onkeydown = "";
            goPrev();
          }
        }
      };

      tb_position();
      $("#TB_load").remove();
      $("#TB_ImageOff").click(tb_remove);
      $("#TB_window").css({display:"block"}); //for safari using css instead of show
      };

      imgPreloader.src = url;
    }else{//code to show html

      var queryString = url.replace(/^[^\?]+\??/,'');
      var params = tb_parseQuery( queryString );
      TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
      TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
      ajaxContentW = TB_WIDTH - 30;
      ajaxContentH = TB_HEIGHT - 45;

      if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window
          urlNoQuery = url.split('TB_');
          $("#TB_iframeContent").remove();
          if(params['modal'] != "true"){//iframe no modal
            $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>X</a> / Esc</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
          }else{//iframe modal
          $("#TB_overlay").unbind();
            $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
          }
      }else{// not an iframe, ajax
          if($("#TB_window").css("display") != "block"){
            if(params['modal'] != "true"){//ajax no modal
            $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>X</a> / Esc</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
            }else{//ajax modal
            $("#TB_overlay").unbind();
            $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
            }
          }else{//this means the window is already up, we are just loading new content via ajax
            $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
            $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
            $("#TB_ajaxContent")[0].scrollTop = 0;
            $("#TB_ajaxWindowTitle").html(caption);
          }
      }

      $("#TB_closeWindowButton").click(tb_remove);

        if(url.indexOf('TB_inline') != -1){
          $("#TB_ajaxContent").append($('#' + params['inlineId']).children());
          $("#TB_window").unload(function () {
            $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
          });
          tb_position();
          $("#TB_load").remove();
          $("#TB_window").css({display:"block"});
        }else if(url.indexOf('TB_iframe') != -1){
          tb_position();
          if($.browser.safari){//safari needs help because it will not fire iframe onload
            $("#TB_load").remove();
            $("#TB_window").css({display:"block"});
          }
        }else{
          $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
            tb_position();
            $("#TB_load").remove();
            tb_init("#TB_ajaxContent a.thickbox");
            $("#TB_window").css({display:"block"});
          });
        }

    }
    if(!params['modal']){
      document.onkeyup = function(e){
        if (e == null) { // ie
          keycode = event.keyCode;
        } else { // mozilla
          keycode = e.which;
        }
        if(keycode == 27){ // close
          tb_remove();
        }
      };
    }

  } catch(e) {
    //nothing here
  }
}
//helper functions below
function tb_showIframe(){
  $("#TB_load").remove();
  $("#TB_window").css({display:"block"});
}
function tb_remove() {
   $("#TB_imageOff").unbind("click");
  $("#TB_closeWindowButton").unbind("click");
  $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
  $("#TB_load").remove();
  if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
    $("body","html").css({height: "auto", width: "auto"});
    $("html").css("overflow","");
  }
  document.onkeydown = "";
  document.onkeyup = "";
  return false;
}
function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
  if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
    $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
  }
}
function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}
function tb_getPageSize(){
  var de = document.documentElement;
  var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
  var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
  arrayPageSize = [w,h];
  return arrayPageSize;
}
function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
/*christmas campaign 2009*/
$(document).ready(function() {
  $("a.popMail").click(function(){
  	$("div#popEmailForm").show();
  });
  $("div#popEmailForm button").click(function(){
  //	$("div#popEmailForm form").hide();
  //	$("div.emailConfirmation").show();
  });
  $("div#popEmailForm a#cancel, a#okClose").click(function(){
  	$("div#popEmailForm").hide();
  });
});
/*footer capmpaigns ticker*/
$(document).ready(function(){

	var first = 0;
	var speed = 900;
	var pause = 3500;

		function removeFirst(){
			first = $('ul#brandList li:first').html();
			$('ul#brandList li:first')
			.animate({opacity: 0}, speed)
			.fadeOut('slow', function() {$(this).remove();});
			addLast(first);
		}

		function addLast(first){
			last = '<li style="display:none">'+first+'</li>';
			$('ul#brandList').append(last)
			$('ul#brandList li:last')
			.animate({opacity: 1}, speed)
			.fadeIn('slow')
		}

	interval = setInterval(removeFirst, pause);
});

function Reminder(campaign){
	this.campaign = campaign;
	this.mail = false;
	this.google = false;
	this.outlook = false;
	this.setMail = function(mail){
		this.mail = mail;
	}
	this.setGoogle = function(google){
		this.google = google;
	}
	this.setOutlook = function(outlook){
		this.outlook = outlook;
	}
	this.getMail = function(){
		return this.mail;
	}
	this.getGoogle = function(){
		return this.google;
	}
	this.getOutlook = function(){
		return this.outlook;
	}

}

function Reminders(){}
Reminders.cache = {};
Reminders.showRemindBox = function(link){
	if(link!=Reminders.link){
		Reminders.closeBox();
	}
	if(Reminders.member==null){
		$.ajax({
			url:'/scripts/getMemberInfo.php',
			success:function(data){
				Reminders.member = jQuery.parseJSON(data);
				Reminders.setEmail(Reminders.member.email);
			}
		});
	}
	Reminders.campaign = link.attr('rel');
	Reminders.link = link;
	box = Reminders.getBox();

	$('#remindMail').parent().removeClass('checked');
	$('#remindOutlook').parent().removeClass('checked');
	$('#remindGoogleCalendar').parent().removeClass('checked');
	if(Reminders.cache[Reminders.campaign]){
		if(Reminders.cache[Reminders.campaign].getOutlook()) $('#remindOutlook').parent().addClass('checked');
		if(Reminders.cache[Reminders.campaign].getGoogle()) $('#remindGoogleCalendar').parent().addClass('checked');
		if(Reminders.cache[Reminders.campaign].getMail()) $('#remindMail').parent().addClass('checked');		
	}else{
		Reminders.cache[Reminders.campaign] = new Reminder(Reminders.campaign);
	}
	
	position = $(link).offset();
	$(box).css({"left":position.left-$(box).width()/2+$(link).width()/2+10,"top":position.top-$(box).height()-5});
	
	$('#remindOutlook').attr('href',"/scripts/ics.php?c_id="+Reminders.campaign);
	$('#remindGoogleCalendar').attr('href',"/scripts/gcal.php?c_id="+Reminders.campaign);
	
	$(box).fadeIn(500);
	
	return false;
}
Reminders.getBox = function(){
	if(Reminders.box!=null){
		return Reminders.box;
	}else{
		$('body').append('<div id="reminderBox"><h4>'+__("Påminn mig via...")+'</h4><a href="" title="'+__("Stäng")+'" id="closeReminder">'+__('Stäng')+'</a><ul class="reminderOptions"><li><a href="" id="remindMail" class="">E-mail<span id="remindEmailAddress"></span></a></li><li><a href="" id="remindGoogleCalendar" class="" target="_blank">Google Calendar</a></li><li><a href="" id="remindOutlook" class="">iCal / Outlook Calendar</a></li></ul></div>');
		Reminders.box = $('#reminderBox');
		$('#remindMail').click(Reminders.setMailReminder);
		$('#remindOutlook').click(Reminders.outlookClick);
		$('#remindGoogleCalendar').click(Reminders.googleClick);
		$('#closeReminder').click(function(){Reminders.closeBox(); return false;});
		$('body').click(Reminders.closeBox);
		$(Reminders.box).click(function(event){
			event.stopPropagation();
		});
		Reminders.populateCache();
		return Reminders.box;
	}
}
Reminders.closeBox = function(){
	if(Reminders.box!=null){
		$(Reminders.box).hide();
	}
}
Reminders.fadeBox = function(){
	if(Reminders.box!=null){
		$(Reminders.box).fadeOut(1000);
	}
}
Reminders.setEmail = function(email){
	$('#remindMail').attr('title',email);
	if(email.length>12)	email = email.substr(0,9)+"...";
	$('#remindMail').text("E-mail ("+email+")");	
}
Reminders.setMailReminder = function(){
	$('#remindMail').parent().addClass("loading");
	$.ajax({
		url:'/scripts/addCampaignReminder.php?c_id='+Reminders.campaign,
		success:function(data){
			$('#remindMail').parent().removeClass("loading");
			$('#remindMail').parent().addClass("checked");
			Reminders.cache[Reminders.campaign].setMail(true);
		}
	});
	return false;
}
Reminders.populateCache = function(){
	$.ajax({
		url:'/scripts/getMemberReminders.php',
		success:function(data){
			var reminders = jQuery.parseJSON(data).result;
			for(i in reminders){
				if(Reminders.cache[reminders[i]]){
					Reminders.cache[reminders[i]].setMail(true);
					$('#remindMail').parent().addClass('checked');
				}else{
					var r = new Reminder(reminders[i]);
					r.setMail(true);
					Reminders.cache[reminders[i]] = r;
				}
			}
		}
	});
}
Reminders.outlookClick = function(){
	Reminders.cache[Reminders.campaign].setOutlook(true);
	$('#remindOutlook').parent().removeClass('checked').addClass('checked');
	Reminders.fadeBox();
}
Reminders.googleClick = function(){
	Reminders.cache[Reminders.campaign].setGoogle(true);
	$('#remindGoogle').parent().removeClass('checked').addClass('checked');
	Reminders.fadeBox();
}


$(document).ready(function(){
	/*shoping cart pop*/
	$("div#shoppingCart a.cTotal").hover(function(){
		//$("div#cartPop").fadeIn();
		
		showCart();
	});

	function showCart(){
		//$("div#cartPop").fadeIn();
		$("#nav_new, #sub-nav,#content,#footer").animate({opacity:0.5}, 300); 
		$("div#cartPop").fadeIn().animate({top: "45px",opacity:1}, 600);
	};

	$('body').click(function(){
	 	$("#nav_new, #sub-nav,#content,#footer").animate({opacity:1}, 400); 
		$("div#cartPop").animate({top: "-30px",opacity:0}, 400).fadeOut();
	});

	$('div#cartPop').click(function(event){
		 event.stopPropagation();
	});

	/* Campaign info popup */
	$('#slideshowCampaign a.campInfoButton').click(function(){
		$(this).parent().find('div.infoTip').fadeIn();
		return false;
	});

	$('div.campaign_container a.campInfoButton').click(function(){
		$(this).prev().fadeIn();
		return false;
	});

	$('a.closeButton').click(function(){
		$(this).parent().fadeOut();
		return false;
	});
	
	/* Reminders */
	$('a.remind').click(function(event){
		return Reminders.showRemindBox($(this));
	});
	
	
	/* Product info tabs */
	$("div#prodTabs h3").click(function(){
		$(this).addClass("selected");
		$(this).siblings().removeClass("selected");
		return false;
	});
	$("h3.pdTab").click(function(){
		$("p.prodInfoText").fadeIn();
		$("p.prodInfoText").siblings().hide();
	});
	$("h3.pgTab").click(function(){
		$("div.prodGuideText").fadeIn();
		$("div.prodGuideText").siblings().hide();
	});
	$("h3.piTab").click(function(){
		$("p.prodMoreinfoText").fadeIn();
		$("p.prodMoreinfoText").siblings().hide();
	});
	/*read more panel*/
	$("a#read_more_button").click(function(){
		$("div.whiteBoxIndex div.infoTip").fadeIn();
		return false;
	});

	/* Cart page - /cart/ */

	/*
	var cart_amount = $('input[id^="cart_amount"]');
	var pattern, me;

	pattern = new RegExp('cart_amount[1-9][0-9]*');

	cart_amount.each(function () {
		me = $(this);

		if (pattern.test(me.attr('id'))) {
			me.keydown(function (e) {
				e.stopPropagation();

				console.log('%s', e.which);

				if (e.which == 13) { // ENTER
					console.log('ENTER');
					e.preventDefault();
				}
			});
		}
	});
	alert(cart_amount.length +'.'+ is_ok);
	*/

});

function show_video (video_url) {
	var video = $('#slideshowCampaign .campVideoButton');

	if (video_url == '' || (video.length == 0)) {
		return;
	}

//	var html='<object type="application/x-shockwave-flash" data="http://sb-campadre.abcdn.net/apps/resources/swf/flash_9.swf"';
//	html+= ' width="580" height="310" id="flash_9">';
//    html+= '<param name="movie" value="http://sb-campadre.abcdn.net/apps/resources/swf/flash_9.swf" />';
//    html+= '<param name="FlashVars" value="customer=sb-campadre&amp;bitrates=350|750&amp;contentType=video/flash&amp;loadStream={URL}" />'
//    html+= '<param name="allowScriptAccess" value="always" />';
//    html+= '<param name="allowFullScreen" value="true" />';
//    html+= '<param name="wmode" value="transparent" />';
//    html+= '<param name="quality" value="high" />';
//    html+= '<param name="bgcolor" value="#000000" />';
//    html+= '<param name="scale" value="exactfit" />';
//	html+= '</object>';

	//html = html.replace(/\{URL\}/, video_url);

        html =video_url;
        
	video.removeClass('hide');

	video.click(function (e) {
		e.preventDefault();
		$(this).parent().empty().html(html);
		$("div#cs-buttons-slideshowCampaign").hide();
	});
}

function show_small_video (video_id, video_url) {
	//var video_width = 400, video_height = 230;
	var video_small = $('#video_button_'+video_id);

//	if (video_url == '' || (video_small.length == 0)) {
//		return;
//	}

//	var html='<object class="campaign_image" type="application/x-shockwave-flash" data="http://sb-campadre.abcdn.net/apps/resources/swf/flash_9.swf"';
//	html+= ' width="' + video_width + '" height="' + video_height + '" id="flash_9">';
//    html+= '<param name="movie" value="http://sb-campadre.abcdn.net/apps/resources/swf/flash_9.swf" />';
//    html+= '<param name="FlashVars" value="customer=sb-campadre&amp;bitrates=350|750&amp;contentType=video/flash&amp;loadStream={URL}" />'
//    html+= '<param name="allowScriptAccess" value="always" />';
//    html+= '<param name="allowFullScreen" value="true" />';
//    html+= '<param name="wmode" value="transparent" />';
//    html+= '<param name="quality" value="high" />';
//    html+= '<param name="bgcolor" value="#000000" />';
//    html+= '<param name="scale" value="exactfit" />';
//	html+= '</object>';

	//html = html.replace(/\{URL\}/, video_url);
        var html = video_url;
	video_small.click(function (e) {
		e.preventDefault();

//		console.log('click!');

		$(this).parent().find('a:first').empty().html(html);
		$(this).parent().children(':not(a:first, .os3)').remove();

                $("#flash_9").parent().click(function(){
                    return false;
                })
	});
}


$(function() {

	// startpage: rundtur och signup

	// validate form om start page. 
	// submit if ok.
	$("#home_register_btn").click(function() {
		var isok = true;
		
		var name = $.trim( $("#home_register_name").attr("value") );
		var email = $.trim( $("#home_register_email").attr("value") );	
		if (name == "" || email == "" || email == "E-postadress") {
			isok = false;
		}
		
		if (isok) {
			$("#home_register").submit();
		} else {
			alert("För att bli medlem måste du fylla i både namn och epost.");
		}
		return false;
	});
	
	// add fancybx
	$(".fancybox").fancybox({
		"width": 930,
		"height": 425,
		"xtransitionIn": "elastic",
		"speedIn": 250,
		"scrolling": "no",
		"titleShow": false,
		"onStart": function() {
			// hide cs-buttons-slideshoW
			$("#cs-buttons-slideshoW").hide();
		},
		"onClosed": function() {
			// show slideshow again
			$("#cs-buttons-slideshoW").show();
		}
	});

	// Google Analytics: track external links
	$("a[href^='http://']").live("click", function() {
		var link = $(this).attr("href");
		if (
			link.match(/^http:\/\/www\.campadre\.com/) || link.match(/^http:\/\/www\.campadre\.com/)
			|| link.match(/^http:\/\/www\.campadre\.se/) || link.match(/^http:\/\/www\.campadre\.se/)
			|| link.match(/^http:\/\/www\.campadre\.fi/) || link.match(/^http:\/\/www\.campadre\.fi/)
			|| link.match(/^http:\/\/www\.campadre\.no/) || link.match(/^http:\/\/www\.campadre\.no/)
			|| link.match(/^http:\/\/www\.campadre\.dk/) || link.match(/^http:\/\/www\.campadre\.dk/)
		) {
		} else {
			pageTracker._trackEvent("links", "external", $(this).attr("href"), 0);
		}
		
	});
	
	// cycle/slideshow for wine-campaigns
	$(".slideshowCycleCampaignSmallClass ul").cycle({
		"fx": "fade",
		"timeout": 4000
	});
	
//checkout activate alternative addresses
	$("#useDefautAddress").live("click",function(){
	$("#memberAddressForm2").toggle();
});

});

//update alternative address
function saveMemberInfo(){
	$.post('/scripts/updateAddress.php', {
		u_id: memberAddressForm1.u_id.value,
		idnr: memberAddressForm1.idnr.value,
		email: memberAddressForm1.email.value,
		firstname: memberAddressForm1.firstname.value,
		lastname: memberAddressForm1.lastname.value,
		address: memberAddressForm1.address.value,
		zipcode: memberAddressForm1.zipcode.value,
		city: memberAddressForm1.city.value,
		care_of: memberAddressForm1.care_of.value,
		phone: memberAddressForm1.phone.value
		 },
	function(output){
	$('#memberAddressForm1').html(output).show();
	$('#billing_address_update').hide();
    $('#billing_address_view').show();
	});
}

// show update member address form
function changeMemberInfo(){
	$('#billing_address_view').hide();
	$('#billing_address_update').show();
	$('#billing_address').addClass('addressesEdit');	
};

//update alternative address
function updateAddress(){
	$.post('/scripts/updateAlternativeAddress.php', {
		cart_id: memberAddressForm2.cart_id.value,
		u_id: memberAddressForm2.u_id.value,
		firstname: memberAddressForm2.firstname.value,
		lastname: memberAddressForm2.lastname.value,
		address: memberAddressForm2.address.value,
		zipcode: memberAddressForm2.zipcode.value,
		city: memberAddressForm2.city.value,
		care_of: memberAddressForm2.care_of.value,
		phone: memberAddressForm2.phone.value
		 },
	function(output){
	$('#memberAddressForm2').html(output).show();
	$('#addressesUpdate').hide();
    $('#addressesView').show();
	});
}	

function addAddress(){
	$.post('/scripts/updateAlternativeAddress.php?action=add', {
		cart_id: memberAddressForm2.cart_id.value,
		u_id: memberAddressForm2.u_id.value,
		firstname: memberAddressForm2.firstname.value,
		lastname: memberAddressForm2.lastname.value,
		address: memberAddressForm2.address.value,
		zipcode: memberAddressForm2.zipcode.value,
		city: memberAddressForm2.city.value,
		care_of: memberAddressForm2.care_of.value,

		phone: memberAddressForm2.phone.value
	},
	function(output){
	$('#memberAddressForm2').html(output).show();
	$('#addressesUpdate').hide();
    $('#addressesView').show();

	});
}

//update alternative address
function activateAddressForm(){
	$('#addressesView').hide();
	$('#addressesUpdate').show();
	$('#billing_address2').addClass('addressesEdit');	
};
//update alternative address
function saveAddressFormOK(){
	$('#billing_address2').removeClass('addressesEdit');	
};

/*
 * Used for text that should be translated
 */
function __(phrase){
	return Language.translate(phrase);
	//return phrase;
}

function Language(){}
Language.inited = false;
Language.phrases = {};
Language.lang = 'se'; //default
Language.init = function(){
	
	Language.phrases['se']={};
	Language.phrases['no']={};
	Language.phrases['fi']={};
	Language.phrases['dk']={};
	
	Language.phrases['se']['Stäng'] = "Stäng";
	Language.phrases['no']['Stäng'] = "Lukk";
	Language.phrases['fi']['Stäng'] = "Sulje";
	Language.phrases['dk']['Stäng'] = "Luk";

	Language.phrases['se']['Påminn mig via...'] = 'Påminn mig via...';
	Language.phrases['no']['Påminn mig via...'] = 'Påminn meg via...';
	Language.phrases['fi']['Påminn mig via...'] = 'Muistuta minua ...';
	Language.phrases['dk']['Påminn mig via...'] = 'Påmind mig via ...';

	Language.phrases['se']['Ort'] = 'Ort';
	Language.phrases['no']['Ort'] = 'Poststed';
	Language.phrases['fi']['Ort'] = 'Paikkakunta';
	Language.phrases['dk']['Ort'] = 'By';
	
	Language.phrases['se']['Du måste välja en betalningsmetod'] = 'Du måste välja en betalningsmetod';
	Language.phrases['no']['Du måste välja en betalningsmetod'] = 'Välj hur du vill betala';
	Language.phrases['fi']['Du måste välja en betalningsmetod'] = 'Choose a payment method';
	Language.phrases['dk']['Du måste välja en betalningsmetod'] = 'Vælg hvordan du vil betale';

	Language.phrases['se']['Du måste välja ett utlämningsställe'] = 'Du måste välja ett utlämningsställe';
	Language.phrases['no']['Du måste välja ett utlämningsställe'] = 'Velg leveringsted';
	Language.phrases['fi']['Du måste välja ett utlämningsställe'] = 'Valitse noutopaikka';
	Language.phrases['dk']['Du måste välja ett utlämningsställe'] = 'Choose a service location';
	
	
}
Language.translate = function(phrase){
	if(!Language.inited) Language.init();
	if(Language.phrases[Language.lang][phrase]){ 
		return Language.phrases[Language.lang][phrase];
	}else{
		return phrase;
	}
}

ServiceLocation = function(id,city,street,name){
	this.id=id;
	this.city = city;
	this.street = street;
	this.name = name;
}

function ServiceLocationFilter(){}; 
ServiceLocationFilter.locations = new Array();
ServiceLocationFilter.selected = null;
ServiceLocationFilter.cities = {};
ServiceLocationFilter.cityToServiceLocationMap = {};
ServiceLocationFilter.init = function(selectElement){
	ServiceLocationFilter.eSelect = selectElement;
	for(i in ServiceLocationFilter.eSelect.childNodes){
		//if(ServiceLocationFilter.eSelect.childNodes[i] instanceof HTMLOptionElement){ //not supported by IE
		if(ServiceLocationFilter.eSelect.childNodes[i].nodeType == 1){ //Node.ELEMENT_NODE (skip TEXT_NODEs)
			var id = ServiceLocationFilter.eSelect.childNodes[i].value;
			if(id!=0){ //skip select default option
				//expecting a string that looks like this: "Hägersten - Fruängsgången 10 - Matxtra fruängen"
				var textArr = ServiceLocationFilter.eSelect.childNodes[i].innerHTML.split(" - ");
				var city = textArr[0];
				var street = textArr[1];
				var name = textArr[2];
				var serviceLocation = new ServiceLocation(id,city,street,name);
				ServiceLocationFilter.locations.push(serviceLocation);
				if(ServiceLocationFilter.eSelect.childNodes[i].selected){
					ServiceLocationFilter.selected = serviceLocation;
				}
				ServiceLocationFilter.cities[city]='';
				if(ServiceLocationFilter.cityToServiceLocationMap[city]){
					ServiceLocationFilter.cityToServiceLocationMap[city].push(serviceLocation);
				}else{
					ServiceLocationFilter.cityToServiceLocationMap[city] = new Array(serviceLocation);
				}
			}
		}
	}

	newSelect = document.createElement('SELECT');
	newSelect.name="city";
	newSelect.id="city";
	newSelect.className = "servicelocation";
	newSelect.options[0] = new Option(__("Ort"),"0");
	var c = 1;
	for(city in ServiceLocationFilter.cities){
		newSelect.options[c] = new Option(city,city);
		c++;
	}
	
	newSelect.onchange = ServiceLocationFilter.select;
	newSelect.onkeyup = ServiceLocationFilter.select;
	
	ServiceLocationFilter.eCitySelect = newSelect;
	selectElement.parentNode.replaceChild(ServiceLocationFilter.eCitySelect,selectElement);
	
	//if we had a selected option we want it selected in the new select-box too
	if(ServiceLocationFilter.selected!=null && ServiceLocationFilter.selected.id!=0){
		newSelect.value = ServiceLocationFilter.selected.city;
		ServiceLocationFilter.select();
	}
	
}
ServiceLocationFilter.select = function(){
	var city = ServiceLocationFilter.eCitySelect.value;

	if(!ServiceLocationFilter.eServiceSelect){
		ServiceLocationFilter.eServiceSelect = document.createElement('SELECT');
		ServiceLocationFilter.eServiceSelect.name = "service_location";
		ServiceLocationFilter.eServiceSelect.id = "service_location";
		ServiceLocationFilter.eServiceSelect.className = "servicelocation";
		ServiceLocationFilter.eCitySelect.parentNode.appendChild(ServiceLocationFilter.eServiceSelect);
	}
	ServiceLocationFilter.eServiceSelect.options.length = 0; //unset all options
	for(i in ServiceLocationFilter.cityToServiceLocationMap[city]){
		serviceLocation = ServiceLocationFilter.cityToServiceLocationMap[city][i];
		ServiceLocationFilter.eServiceSelect.options[i] = new Option(serviceLocation.name.replace("&amp;","&")+' ('+serviceLocation.street+')',serviceLocation.id);
	}
	
	if(ServiceLocationFilter.selected!=null && ServiceLocationFilter.selected.id!=0){
		ServiceLocationFilter.eServiceSelect.value = ServiceLocationFilter.selected.id;
		ServiceLocationFilter.selected=null; //reset
	}
	CheckoutValidator.removeServiceLocationError();
}


function CheckoutValidator(){}; 
CheckoutValidator.validateServiceLocation = function(){
	if(!document.getElementById("service_location") && !document.getElementById("city")){
		return true; //we don't have any service locations (we're probably in denmark)
	}
	if(serviceLocation = document.getElementById("service_location")){
		if(serviceLocation.value>0){
			return true;
		}
	}
	return false;
}
CheckoutValidator.validatePaymentType = function(){
	paymentTypes = document.getElementById("order_form").elements['payment_type'];
	paymentType=null;
	for(var i=0; i<paymentTypes.length; i++){
		if(paymentTypes[i].checked){
			paymentType = paymentTypes[i].value;
		}
	}
	return paymentType!=null;
}
CheckoutValidator.validateBank = function(){
	var radio = document.getElementById("dibs_direct");
	if(radio && radio.checked){
		return document.getElementById("dibs_direct_method").value != 0;
	}else{
		return true;
	}
}
CheckoutValidator.getErrors = function(){
	var errors = new Array();

	if(!CheckoutValidator.validatePaymentType()){
		errors.push(__("Du måste välja en betalningsmetod"));
	}

	if(!CheckoutValidator.validateBank()){
		errors.push(__("Du måste välja en bank"));
	}
	
	if(!CheckoutValidator.validateServiceLocation()){
		errors.push(__("Du måste välja ett utlämningsställe"));
	}
	
	
	return errors;
}

CheckoutValidator.validate = function(){
	var valid = true;

	if(!CheckoutValidator.validatePaymentType() || !CheckoutValidator.validateBank()){
		valid = false;
		$('#pay_type_error_frame').removeClass("error").addClass("error");
	}else{
		$('#pay_type_error_frame').removeClass("error");
	}
	
	
	if(!CheckoutValidator.validateServiceLocation()){
		valid = false;
		$('#service_location_error_frame').removeClass("error").addClass("error");
	}else{
		$('#service_location_error_frame').removeClass("error");
	}
	
	if(!valid){
		CheckoutValidator.showPopup(document.getElementById("cart_confirm"));
	}
	
	return valid;
}

CheckoutValidator.removePayTypeError = function(){
	$('#pay_type_error_frame').removeClass("error");
	CheckoutValidator.updateButton();
	$("#checkout_hover_error").hide();
	//CheckoutValidator.showPopup(document.getElementById("cart_confirm"));
}
CheckoutValidator.removeServiceLocationError = function(){
	$('#service_location_error_frame').removeClass("error");
	CheckoutValidator.updateButton();
	$("#checkout_hover_error").hide();
	//CheckoutValidator.showPopup(document.getElementById("cart_confirm"));
}

CheckoutValidator.updateButton = function(){
	if(CheckoutValidator.getErrors().length==0){
		$('#cart_confirm').removeClass("disabled").addClass("pink");
	}else{
		$('#cart_confirm').removeClass("pink").addClass("disabled");
	}
}


CheckoutValidator.showErrors = function(errors){
	var errorStr = "";
	for(i in errors){
		errorStr += "<p>"+errors[i]+"</p>";
	}
	
	el = document.getElementById("checkout_error");
	if(!el){
		el = document.createElement('DIV');
		el.id="checkout_error";
		document.getElementsByTagName('BODY')[0].appendChild(el);
	}else{
		$(el).show();
	}

	el.innerHTML = errorStr;
	setTimeout('$(el).fadeOut(2500)',2000);
}

CheckoutValidator.hover = function(button){
	var errors = CheckoutValidator.getErrors();
	
	if(errors.length>0){
		errorStr = "";
		for(i in errors){
			errorStr += "<p>"+errors[i]+"</p>";
		}
		
		el = document.getElementById("checkout_hover_error");
		if(!el){
			el = document.createElement('DIV');
			el.id="checkout_hover_error";
			document.getElementsByTagName('BODY')[0].appendChild(el);
		}else{
			$(el).show();
		}
		el.innerHTML = errorStr;
		
		position = $(button).offset();
		$(el).css({"left":position.left-$(el).width()+$(button).width()+20,"top":position.top-$(el).height()-8});
		button.onmouseout = function(){
			$(el).fadeOut(800);
		}
		
	}
}

CheckoutValidator.showPopup = function(button){
	var errors = CheckoutValidator.getErrors();
	
	if(errors.length>0){
		errorStr = "";
		for(i in errors){
			errorStr += "<p>"+errors[i]+"</p>";
		}
		
		el = document.getElementById("checkout_hover_error");
		if(!el){
			el = document.createElement('DIV');
			el.id="checkout_hover_error";
			document.getElementsByTagName('BODY')[0].appendChild(el);
		}else{
			$(el).show();
		}
		el.innerHTML = errorStr;
		
		position = $(button).offset();
		$(el).css({"left":position.left-$(el).width()+$(button).width()+20,"top":position.top-$(el).height()-8});
		//setTimeout("$(el).fadeOut(1800)",5000);
		
	}
}


