var hdrBase = "bildspel/Bildspel420x320px-";
var hdr = Array(
		"01.jpg",
		"03.jpg",
		"07.jpg",
		"46b.jpg",
		"23.jpg",
		"08.jpg",
		"26.jpg",
		"11.jpg",
		"51.jpg",
		"64.jpg",
		"57.jpg"
//		"14.jpg",
//		"20.jpg",
//		"27.jpg",
//		"29.jpg",
//		"40.jpg",
//		"41.jpg",
//		"66.jpg"
	);

var	hbg = 0;

var splashLoaded = false;

var rel = null;
var submenu = null;
var submenue = null;
var thisScript = ( thisScript == undefined ) ? 'index.php' : thisScript;


$(document).ready( function() {

	var ts = $('<div id="tabshade" />').addClass('png_bg').insertAfter( $('div#flags') );

	$('body div#wrapper div.menu a').hover( function() {
		tsTop = $(this).offset().top - 16 + $(this).height() + parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'));
		ts.css('top', tsTop+'px').show();
	}, function() {
		ts.hide();
	});

	initPage();

});



function initPage() {

	//
	//	Se till att dropdown stängs
	//	när ny sida laddas in
	//
	if( submenu ) {
		clearTimeout( submenu );
	}
	if( submenue ) {
		submenue.css({display:"none"});
		$("#dropdown").css({backgroundColor:"white",color:"black"});
	}
	submenu = null;
	submenue = null;

	//
	//	Startar släckning/nertoning av submenu
	//
	$("#submenu, #dropdown").mouseleave( function() {
		submenue = $("#submenu");
		submenu = setTimeout( function(){
			if( submenue ) {
				submenue.css({display:"none"});
				$("#dropdown").css({backgroundColor:"white",color:"black"});
			}
			submenu = null;
			submenue = null;
		}, 1500 );
	})

	//
	//	Sköter om visning och submenu och avbryter även släckning/nertoning om den är startad
	//	
	$("#submenu, #dropdown").mouseenter( function() {
		if( submenu ) {
			clearTimeout( submenu );
			submenu = null;
			submenue = null;
		} else {
			$("#submenu").css({display:"block"});
		}
		$("#dropdown").css({backgroundColor:"silver",color:"black"});
	})


	//
	//	Rensa ut onödigt innehåll i HTML-koden för scrollers
	//
	$("div.scrollwrap div").each( function() {
		$(this).html( $.trim( $(this).html() ).replace(/\>\s+\</g, '><') );
	})


	//
	//	Kontrollera hur många IMG vi har i scrollern, lagra totalbredden i REL
	//
	$("div.scrollwrap").each( function() {
		var tImg = $(this).children("div").find("img").length;
		$(this).attr("rel", tImg * 227);
		$(this).children("div").css({width: ( tImg * 227 ) + "px"});
	})


	//
	//	Initiera FancyBox
	//
	$("a.fancybox").fancybox({
		type			: 'image',
		cyclic			: true,
		titlePosition	: 'over',
		titleFormat		: function(title, currentArray, currentIndex, currentOpts) {
			return '<span id="fancybox-title-over">Bild ' + (currentIndex + 1) + ' av ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		},
		onComplete		: function() {
			var thisHref = this.href;
			$("img#fancybox-img").css("cursor","pointer").bind("click", function() {
				window.open( thisHref );
			});
		}
	});

	//
	//	Göm alla delsektioner utom den första, samt lagra namnet på den aktiva
	//
	$("div.produktsegment:gt(0)").hide().addClass("hidden");
	$("div.produktsegment:first").addClass("shown");
	rel = $("div.produktsegment:first").attr("id");
	$("span.subsection a[rel='" + rel + "']").addClass("curTab");


	$("div#quicknav a").each( function() {
		$(this).on('focus', function() {
			this.blur();
		})
		$( this ).on( 'click', function( e ) {
			e.preventDefault();
			e.stopPropagation();
			var relT = $(this).attr("rel");
			if( relT != rel ) {
				$('span.subsection a').removeClass('curTab');
				$(this).addClass('curTab');
				$('div.produktsegment.shown').hide().addClass('hidden');
				$('div.produktsegment#' + relT).fadeIn().addClass('shown');
				rel = relT;
			}
		});
	});

/*
	$("#content a").each( function() {
		$(this).bind('focus', function() {
			this.blur();
		})
		var attr = $( this ).attr("href");
		
		if( typeof attr != "undefined" && attr.substr(0,7) != "mailto:" ) {
			if( attr == "#" && $(this).attr("rel") != "" ) {
				if( !( $(this).hasClass('icnPho') || $(this).hasClass('icnPdf') || $(this).hasClass('icnFil') ) ) {
//				} else {
					$( this ).click( function(e) {
						e.preventDefault();
						var relT = $(this).attr("rel");
//						$.dynload.addSub( relT );
						if( relT != rel ) {
							$("span.subsection a").removeClass("curTab");
							$(this).addClass("curTab");
							$("div.produktsegment.shown").hide().addClass("hidden");
							$("div.produktsegment#" + relT).fadeIn().addClass("shown");
							rel = relT;
						}
					});
				}
			} else if( attr != "#" && attr.substr(0,7) != "http://" && $(this).attr("target") != "_blank" ) {
				$( this ).click( function(e) {
					attr = $( this ).attr("href");
//					e.preventDefault();
//					$.dynload.load( attr );
				});
			}
		}
	});
*/

	$('a.icnPho, a.icnPdf, a.icnFil').bind( 'click', function( e ) {
		if( e.preventDefault ) {
			e.preventDefault();
			e.stopPropagation();
		} else {
			e.returnValue = false;
		}
		if( $(this).hasClass('icnPho') ) {
			lType = 'icnPho';
		} else if( $(this).hasClass('icnPdf') ) {
			lType = 'icnPdf';
		} else if( $(this).hasClass('icnFil') ) {
			lType = 'icnFil';
		} else {
			return false;
		}
		var o = $(this).parent('div').offset();

		if( $('div#bloop').length == 0 ) {
			$('<div></div>').attr('id','bloop').appendTo( $('body') );
			$('<div></div>').attr('id','bloom').appendTo( $('body') );
			$('<div></div>').attr('id','blooc').appendTo( $('body') );
			$('<div></div>').attr('id','bloot').appendTo( $('body') );
			$('div#bloop').css('left', o.left+'px');
			$('div#bloom').css('left', (o.left - 618)+'px');
			$('div#blooc').css('left', o.left+'px').addClass('png_bg');
			$('div#bloot').css('left', (o.left - 618)+'px');
		}
		$('div#blooc').css('top', '-1000px');
		$('div#bloot').css('top', '-1000px');
		$('div#bloop').css('top', o.top+'px');
		$('div#bloom').css('top', (o.top - 40)+'px').html('<p>Ett ögonblick, hämtar information...</p>');
		$('div#bloom').css('height', '62px');
		$('div#bloom').css('min-height', '40px');
		var h = $('div#bloom').outerHeight();
		ht = ( o.top + 14 ) - ( h / 2 );
		$('div#bloom').css('top', ht+'px');
		$('div#bloop, div#bloom').show();

		aID = $(this).attr('rel');
		if( aID.indexOf(',') != -1 ) {
			tID = aID.match(/(\d+),(\d+)/);
			if( tID != null ) {
				aID = tID[1];
				pID = tID[2];
			}
		} else {
			pID = null;
		}
		$.getJSON( thisScript, { aid: aID, prid: pID }, function( data ) {
			if( data['artnr'].length != 0 ) {
				$('div#bloot').html( data['artnr'] );
			}
			if( data['foton'].length == 0 && lType == 'icnPho' ) {
				return false;
			}
			if( data['filer'].length == 0 && lType == 'icnFil' ) {
				return false;
			}
			if( data['broschyrer'].length == 0 && lType == 'icnPdf' ) {
				return false;
			}
			switch( lType ) {
				case 'icnPho':
					var t = '<div class="popInfo">Klicka på foto för större bild</div>';
					for( var f = 0; f < data['foton'].length; f++ ) {
						mt = data['foton'][f]['height'] * ( 160 / data['foton'][f]['width'] );
						mt = mt < 100 ? ' style="margin-top: '+Math.round( ( 100 - mt ) / 2 )+'px;"' : '';
						t += '<a class="artPho" href="cache.php?id='+data['foton'][f]['id']+'" rel="artikel"><img src="cache.php?id='+data['foton'][f]['id']+'&mw=160&mh=100" title="'+( data['foton'][f]['kommentar'] != null ? data['foton'][f]['kommentar'] : '' )+'"'+mt+' /></a>';
					}
					$('div#bloom').html( t );
					var r = Math.floor( data['foton'].length / 3 );
					if( data['foton'].length % 3 > 0 ) {
						r++;
					}
					r = (r * 116) + 40;
					r = r > 388 ? 388 : r;
					$('div#bloom').css({
						'height'		: r+'px',
						'min-height'	: '156px',
						'max-height'	: '388px'
					});
					$("a.artPho").fancybox({
						type			: 'image',
						cyclic			: true,
						titlePosition	: 'over',
						titleFormat		: function(title, currentArray, currentIndex, currentOpts) {
							return '<span id="fancybox-title-over">Bild ' + (currentIndex + 1) + ' av ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
						},
						onComplete		: function() {
							var thisHref = this.href;
							$("img#fancybox-img").css("cursor","pointer").bind("click", function() {
								window.open( thisHref );
							});
						}
					});
					break;
				case 'icnPdf':
					var t = '<div class="popInfo">Klicka på broschyr för att ladda ner</div>';
					for( var f = 0; f < data['broschyrer'].length; f++ ) {
						t += '<a class="artPdf" href="cache.php?id='+data['broschyrer'][f]['broschyr']+'&dl"><img class="rotis" src="cache.php?id='+data['broschyrer'][f]['foton']+'&mw=160&mh=226" width="160" height="226" title="'+data['broschyrer'][f]['rubrik']+'" /><div>'+data['broschyrer'][f]['rubrik']+'</div></a>';
					}
					$('div#bloom').html( t );
/*
					var r = Math.floor( data['broschyrer'].length / 3 );
					if( data['broschyrer'].length % 3 > 0 ) {
						r++;
					}
					r = (r * 126) + 22;
					r = r > 274 ? 274 : r;
					$('div#bloom').css({
						'height'		: r+'px',
						'min-height'	: '138px',
						'max-height'	: '274px'
					});
*/
					$('div#bloom').css({
						'height'		: '292px',
						'min-height'	: '292px',
						'max-height'	: '292px'
					});
					break;
				case 'icnFil':
					var t = '<div class="popInfo">Klicka på filnamn för att ladda ner</div>';
					t += '<table border="0" cellpadding="4" cellspacing="0" width="100%">';
					for( var f = 0; f < data['filer'].length; f++ ) {
						t += '<tr valign="top"' + ( f == 0 ? ' class="first"' : '' ) + '><td><a class="artFil" href="cache.php?id='+data['filer'][f]['id']+'&dl">'+data['filer'][f]['originalnamn']+'</a></td>';
						t += '<td style="text-align: right;" nowrap="nowrap">'+Math.round( data['filer'][f]['filstorlek'] / 1024 )+' kB</td>';
						t += '<td>'+( data['filer'][f]['kommentar'] != null ? data['filer'][f]['kommentar'] : '' )+'</td></tr>';
						if( f > 2 ) break;
					}
					$('div#bloom').html( t );
					var r = data['broschyrer'].length * 22;		// approximation
					r = r > 264 ? 264 : r;
					$('div#bloom').css({
						'height'		: r+'px',
						'min-height'	: '138px',
						'max-height'	: '264px'
					});
					break;
				default:
					return false;
					break;
			}
			var h = $('div#bloom').outerHeight();
			ht = ( o.top + 14 ) - ( h / 2 );
			
			o = $('body').height();
			if( (h + ht) > (o - 10) ) {
				ht = o - ( h + 10 );
			}
			if( ht < 10 ) {
				ht = 10;
			}
			$('div#bloom').css('top', ht+'px');
			$('div#blooc').css('top', ht+'px');
			$('div#bloot').css('top', ((ht+6) - $('div#bloot').outerHeight()) + 'px');
			$('div#bloop, div#bloom, div#blooc, div#bloot').show();
		});
		return false;
	});
	$('body').bind('click', function( e ) {
		if( $(e.target).closest('div#bloom').length == 0 && $(e.target).closest('div#fancybox-wrap').length == 0 ) {
			if( $('div#bloom:visible').length ) {
				$('div#bloop, div#bloom, div#blooc, div#bloot').hide();
			}
		}
	});

	$('select#pageselect').removeAttr('disabled').bind(($.browser.msie && $.browser.version < 9) ? 'propertychange': 'change', function() {
		location = thisScript + '?fg&p=' + this.options[this.selectedIndex].value;
	});

	if( $('div.miniProd, div.miniProdLast').length > 0 ) {
		var onMiniProd = 0;
		var inFancyMini = false;
		var hookFancyMini = function() {
			$('div.miniProd a.fancybox, div.miniProdLast a.fancybox').fancybox({
				type			: 'image',
				titlePosition	: 'over',
				titleFormat		: function(title, currentArray, currentIndex, currentOpts) {
					return title.length ? '<span id="fancybox-title-over">' + title + '</span>' : '';
				},
				onStart			: function() {
					inFancyMini = true;
				},
				onComplete		: function() {
					var thisHref = this.href;
					$("img#fancybox-img").css("cursor","pointer").bind("click", function() {
						window.open( thisHref );
					});
				},
				onClosed		: function() {
					inFancyMini = false;
				}
			});
		}
		var updateMiniProd = function() {
			if( inFancyMini ) {
				setTimeout( updateMiniProd, 5000 );
			} else {
				var ids = [];
				$('div.miniProd, div.miniProdLast').each( function() {
					ids.push( $(this).attr('rel') );
				});
				ids = '-'+ids.join(',');
				$.getJSON( thisScript + '?mid='+ids, function( d ) {
					var e = $( d.htmldata );
					var f = $('div.miniProd, div.miniProdLast', e);
					var r = f.attr('rel');
					var h = f.html();
					$('div.miniProd, div.miniProdLast').eq(onMiniProd).attr('rel',r).html( h );
					onMiniProd++;
					if( onMiniProd == $('div.miniProd, div.miniProdLast').length ) onMiniProd = 0;
					hookFancyMini();
					setTimeout( updateMiniProd, 12000 );
				});

			}
		}
		hookFancyMini();
		setTimeout( updateMiniProd, 12000 );
	}

	//
	//	Om vi är på introsidan skall vi köra bildspelet
	//
	if( $("div#splashcontainer").length == 1 ) {

		//
		//	Kolla vilken bakgrund vi visade sist
		//
		hbg = getCookie("hdrbg");
		hbg = hbg && parseInt( hbg ) < hdr.length ? parseInt( hbg ) : Math.floor(Math.random()*hdr.length);	// slumpa vilken banner som visas först

		//
		//	Lägg till bakgrunden till huvudet, starta igång
		//	det automatiska bytet av bakgrundsbild
		//
		$("<div class=\"splash\" id=\"hdrbg"+hbg+"\"></div>").hide().css({"backgroundImage":"url("+hdrBase+hdr[hbg]+")"}).prependTo("div#splashcontainer");
		for( var i = 0; i < hdr.length; i++ ) {
			if( i != hbg ) {
				$("<div class=\"splash\" id=\"hdrbg"+i+"\" rel=\""+hdrBase+hdr[i]+"\"></div>").hide().prependTo("div#splashcontainer");
			}
		}

		$("div#hdrbg"+hbg).show();
		loadNextSplash( hbg );

		setTimeout( function() {
			var tcb = arguments.callee;
			if( splashLoaded ) {
				var nbg = hbg + 1 == hdr.length ? 0 : hbg + 1;
				loadNextSplash( nbg );
				setCookie("hdrbg", nbg, false, "/", "", "");
				$("div#hdrbg"+nbg).insertAfter("div#hdrbg"+hbg).fadeIn(5000, function() {
					$("div#hdrbg"+hbg).hide();
					hbg = nbg;
					setTimeout( tcb, 10000 );
				});
			} else {
				setTimeout( tcb, 2000 );
			}
		}, 10000 );
	}


	$('div.jplayer').each( function() {
		var src = $(this).html();
		$(this).empty();
		var vol = 0.5;
		if( src != '' ) {
			var c = $('<div class="jcontainer"><div class="jcontrols"><a href="#" class="jplay"></a><a href="#" class="jpause"></a><a href="#" class="jmute"></a><a href="#" class="junmute"></a></div><div class="jvolcont"><div class="jvolume"><div class="jcurvol"></div></div></div></div>').insertAfter( $(this) );
			var t = this;
			$('div.jcurvol', c).css({
				'width' : (vol*100)+'%'
			});
			c.on('click', '.jplay', function() {
				$(t).jPlayer('play');
				$('.jplay', c).hide();
				$('.jpause', c).show();
			});
			c.on('click', '.jpause', function() {
				$(t).jPlayer('pause');
				$('.jpause', c).hide();
				$('.jplay', c).show();
			});
			c.on('click', '.jmute', function() {
				$(t).jPlayer('mute');
				$('.jmute', c).hide();
				$('.junmute', c).show();
				$('.jcurvol', $(this).parent().parent()).css({
					'width' : '0%'
				});
			});
			c.on('click', '.junmute', function() {
				$(t).jPlayer('unmute');
				$('.junmute', c).hide();
				$('.jmute', c).show();
				$('.jcurvol', $(this).parent().parent()).css({
					'width' : (vol*100)+'%'
				});
			});
			c.on('click', '.jvolume', function(e) {
				var offset = $(this).offset();
				var pct = (e.pageX - offset.left) / $(this).width();
				pct = pct > 1 ? 1 : pct;
				pct = pct < 0.005 ? 0 : pct;
				vol = pct;
				$('.jcurvol', $(this)).css({
					'width' : (vol*100)+'%'
				});
				$(t).jPlayer('volume', vol);
			});
			$(this).jPlayer({
				swfPath: 'javascript',
				volume: vol,
				solution: 'flash, html',
				ready: function() {
					$(this).jPlayer('setMedia', {
						mp3: src
					});
				}
			});
		}
	});


	/*
	**
	**	KUNDINLOGGNING
	**
	*/
	function prepareKL( e ) {
		e.preventDefault();
		e.stopPropagation();
		if( $('div#klBG').length == 0 ) {
			var bg = $('<div id="klBG"></div>').hide().appendTo( $('body') );
		} else {
			var bg = $('div#klBG');
		}
		bg.css({
			'z-index'		: '50000',
			'position'		: 'absolute',
			'top'			: '0px',
			'left'			: '0px',
			'width'			: '100%',
			'height'		: '100%'
		}).fadeIn('slow');
		if( $('div#klWin').length == 0 ) {
			var kl = $('<div id="klWin"></div>').hide().appendTo( $('body') );
		} else {
			var kl = $('div#klWin').hide();
		}
		kl.css({
			'z-index'		: '50001',
			'position'		: 'absolute'
		});
		return {'bg' : bg, 'kl' : kl};
	}

	$('body').on('click', 'a#kundlogin', function( e ) {
		var k = prepareKL( e );
		$.ajax({
			url			: 'login.php',
			dataType	: 'json',
			data		: {'mode':'loginHTML'},
			success		: function( json ) {
				if( json.success ) {
					k.kl.html( json.html );
					var ml = k.kl.css('margin-left');
					k.kl.css('margin-left', '-20000px');
					var wh = k.kl.outerHeight();
					k.kl.css({
						'margin-left'	: ml,
						'margin-top'	: '-'+(wh/2)+'px'
					}).show();
				} else {
					alert( json.error );
					k.kl.hide();
					k.bg.hide();
				}
			}
		});
		return false;
	});

	$('body').on('click', 'div#klWin a#klbCancel', function( e ) {
		var kl = $('div#klWin'),
			bg = $('div#klBG');

		if( kl.length != 0 ) kl.fadeOut('fast');
		if( bg.length != 0 ) bg.fadeOut('fast');
	});

	$('body').on('click', 'div#klWin a#klbForgot', function( e ) {
		var k = prepareKL( e );
		$.ajax({
			url			: 'login.php',
			dataType	: 'json',
			data		: {'mode':'forgotHTML'},
			success		: function( json ) {
				if( json.success ) {
					k.kl.html( json.html );
					var ml = k.kl.css('margin-left');
					k.kl.css('margin-left', '-20000px');
					var wh = k.kl.outerHeight();
					k.kl.css({
						'margin-left'	: ml,
						'margin-top'	: '-'+(wh/2)+'px'
					}).show();
				} else {
					alert( json.error );
					k.kl.hide();
					k.bg.hide();
				}
			}
		});
	});
	/*
	**
	**	SLUT: KUNDINLOGGNING
	**
	*/

}

function loadNextSplash( c ) {
	var n = c + 1 == hdr.length ? 0 : c + 1;
	$("div#hdrbg"+n).each( function() {
		if( $(this).attr("rel") != undefined ) {
			var that = this;
			splashLoaded = false;
			var tempImg = $("<img>");
			tempImg.one("load", function() {
				$(that).css("backgroundImage", "url("+$(that).attr("rel")+")");
				$(that).removeAttr("rel");
				splashLoaded = true;
				$(this).remove();
			});
			tempImg.attr("src", $(this).attr("rel"));
		} else {
			splashLoaded = true;
		}
	});
	return n;
}

function setCookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
		if the expires variable is set, make the correct
		expires time, the current script below will set
		it for x number of days, to make it for hours,
		delete * 24, for minutes, delete * 60 * 24
	*/
	if( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for( i = 0; i < a_all_cookies.length; i++ ) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if( cookie_name == check_name ) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if( a_temp_cookie.length > 1 ) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if( !b_cookie_found ) {
		return null;
	}
}

