/**
 * 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() {
	$(".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: {
			"Logga in": 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 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) {
			reciever.innerHTML = "";
			reciever.innerHTML = 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);
});


$(document).ready(function(){
	/*shoping cart pop*/
	$("div#shoppingCart a.cTotal").hover(function(){
		$("div#cartPop").fadeIn();
	});

	$('body').click(function(){
		$('div#cartPop').fadeOut('fast');
	});

	$('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;
	});

	/* 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);

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

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