/*
* Load jQuery from web servers if gooogleCode isnt available 
*/
if(typeof(jQuery) == 'undefined')
	document.write('<script type="text/javascript" src="/template/www/javascript/jquery_min.js"></script>');


/*
 * Open external websites in an iframe with link back to norran.se
 */
function outFrame(href)
{
	if(href.match('norran.se') || href.match('anp.se'))
		return true;
	else
	{
		document.location = '/?service=outframe&from='+escape(document.location.href)+'&show='+escape(href);
		return false;
	}
}

/*
* Insert older articles in newsbill
*/
function getMoreArticles(date, link, path)
{
	link.attr('class', 'more_articles_active');
	link.html('<img src="/template/www/images/ajax-loader-more.gif" />');
	
	$.ajax
	({
		 type: "GET",
		 url: path + '?service=maincontent&from=' + date,
		 mode: 'queue',
		 cache: true,
		 dataType: "html",
		 success: function(resp)
		 {
			link.parent().remove();
			$('#content').append('<div class="ajaxincoming">'+resp+'</div>');

			$('.ajaxincoming a').each(function() {
				if($(this).attr('href').indexOf('maincontent') == -1)
				{
					if($(this).attr('href').indexOf('?') == -1)
						$(this).attr('href', $(this).attr('href') + '?service=maincontent');
					else
						$(this).attr('href', $(this).attr('href') + '&service=maincontent');
				}
				
				$(this).click(function() {
					if($(this).attr('href').match('.ece') != null)
					{
						// Add article css if in section
						if($('#article_css').length == 0)
						{
							$('head').append('<link rel="stylesheet" href="/template/www/css/article.css" type="text/css" id="article_css" />');
							if(typeof(flowplayer) == 'undefined')
								$('head').append("<script type=\"text/javascript\" src=\"/template/www/javascript/flowplayer-3.1.4.min.js\"></script>");
						}
						
						thisParent = $(this).parent();
						for(i=0; i < 10; i++)
						{
							if(thisParent.hasClass('newsbill'))
							{
								thisParent.css({
										'height' : thisParent.height() + 'px',
										'margin' : '0px',
										'padding' : '0px'
									});
								
								thisParent.html('<p style="text-align:center; padding-top:15px;"><img src="/user/images/ajax-loader.gif" /></p>');
								thisParent.css('overflow', 'hidden');
								
								$.ajax
								({
									 type: "GET",
									 url: $(this).attr('href'),					 
									 cache: true,
									 success: function(resp)
									 {
										var show = function () { 
														thisParent.css('height', 'auto'); 
														thisParent.html(resp);
														$('.article_container').css('padding', '0 10px 10px 10px');
														$('.article_container').css('margin', '0');
													};
													
										setTimeout(show, 1000);
									 },
									 error : function(err, e)
									 {
										document.title = 'Error, status:' +err.status;
									 }
								});
								
								return false;
							}
							
							thisParent = thisParent.parent();
						}
						
						document.location = $(this).attr('href');
					}
			});
				
			});
		 }
	});
	
	return false;
} 


/*
 * Toggle between collapsed and expanded div
 */
function expandToggler(id, link)
{
	if($('#'+id).attr('class') == 'nodisplay') 
	{
		$('#'+id).slideDown();
		$('#'+id).removeClass('nodisplay');
		link.html('Visa f\344rre <span class="red smaller_text">\u25B2</span>');
	} 
	else 
	{
		$('#'+id).slideUp();
		$('#'+id).addClass('nodisplay');
		link.html('Visa fler <span class="red smaller_text">\u25BC</span>');
	}
}


/*
* Covers the entire page with a black fade
*/
function fadePage(callBack)
{
	$('<div id="previewfader" style="display:none; z-index:999;position:absolute; top:0; left:0; background:#000; width:100%;height:'+$('body').height()+'px"></div>').appendTo('body');
    $('#previewfader').css({'opacity':0, 'display':'block'});
    $('object').css('visibility', 'hidden');
    $('embed').css('visibility', 'hidden');
    $('#previewfader').fadeTo('normal', 0.8, function() {
    	if(typeof(callBack) == 'function')
    		callBack();
    });
}


/*
 * Removes page fade
 */
function removePageFade(callBack)
{
	$('#previewfader').fadeOut('normal', function(){
        $(this).remove();
        $('object').css('visibility', 'visible');
        $('embed').css('visibility', 'visible');
        if(typeof(callBack) != 'undefined')
        	callBack();
	});
}


/*
 * show an image preview window
 */
function previewImage(imgSource, width, height)
{
	fadePage(function() {
		$('<img src="" id="previewimage" height="1" width="1"style="position:fixed; z-index:1000; top:35px; left:50%; border:#FFF solid 5px" />').appendTo('body');
		$('#previewimage').load(function() {
			$(this).animate ( 
				{
					'width' : width+'px',
					'height' : height+'px',
					'marginLeft' : '-'+(width / 2)+'px'
				},
				'normal',
				'swing'
			);
		});
		$('#previewimage').attr('src', imgSource);
		$('#previewimage').click(function() {removeImagePreview()});
		$('#previewfader').click(function() {removeImagePreview()});
    });
}


/*
 * Simple flash function
 */
function createFlash(src, height, width, flashvar)
{
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+width+'" height="'+height+'">');
	document.write('<param name="allowScriptAccess" value="sameDomain" />');
	document.write('<param name="allowFullScreen" value="false" />');
	document.write('<param name="allowFullScreen" value="false" />');
	document.write('<param name="movie" value="'+src+'" />');
	document.write('<param name="quality" value="high" />');
	document.write('<param name="flashvars" value="'+flashvar+'" />');
	document.write('<embed src="'+src+'" quality="high" flashvars="'+flashvar+'" width="'+width+'" height="'+height+'" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	document.write('</object>');
}

/*
* Remove image preview 
*/
function removeImagePreview()
{
	$('#previewimage').animate (
		{
	        'width' : '0px',
	        'height' : '0px',
	        'marginLeft' : '-5px'
		},
		'normal',
		'swing',
		function()
		{
	        $('#previewimage').fadeOut('normal', function(){
	                $(this).remove();
	        });
	        removePageFade();
		}
	);
}


/*
* Creates an image slideshow from an array ( 0 => (0 => url, 1=>text, 2 => name, 3=> img) )
*/
var campaignShow = function(cmpArray, cmpContainer)
{
	this.cmpContainer = cmpContainer;
	this.cmpIndex = 0;
	this.cmpUnits = cmpArray;
	this.cmpUnits.sort(function() {return 0.5 - Math.random()})
	var _self = this;
	
	$(this.cmpContainer).html('<a href=""><strong></strong><br /><em></em></a>');
	
	this.showNext = function() {
		if(typeof(_self.cmpUnits[_self.cmpIndex]) == 'undefined')
			_self.cmpIndex = 0;
		
		$(_self.cmpContainer).fadeOut(1500, function() {
			
			$(_self.cmpContainer+' a').attr('href', _self.cmpUnits[_self.cmpIndex][0]);
			$(_self.cmpContainer+' em').text(_self.cmpUnits[_self.cmpIndex][1]);
			$(_self.cmpContainer+' strong').text(_self.cmpUnits[_self.cmpIndex][2]);
			
			if(_self.cmpUnits[_self.cmpIndex][3] != '')
				$(_self.cmpContainer).css({ 'background-image' : 'url('+_self.cmpUnits[_self.cmpIndex][3]+')' });
			else
				$(_self.cmpContainer).css({ 'background-image' : 'none' });
			
			$(_self.cmpContainer).fadeIn(1500, function(){
				_self.cmpIndex++;
				setTimeout(_self.showNext, 10000);
			});
		});
	}
	
	this.showNext();
}

/*
 * Show most popular articles via the widget API
 */
function getMostPopular(reqParams, divObj)
{
	$.ajax({
		url : '/widget_api.jsp?widgets=8'+reqParams,
		cache : true,
		type : 'GET',
		mode: 'queue',
		success : function(xml) 
				{
					var items = xml.getElementsByTagName('item');
					var listHTML = '<ol>';
					for(var i = 0; i < items.length; i++)
						listHTML += '<li><a href="'+items[i].getAttribute('url')+'" title="'+nodeValue(items[i])+'">'+nodeValue(items[i]).shorten(32)+'</a></li>';
					
					divObj.html(listHTML + '</ol>');
				},
		error : function(xml) {

				}
	});
}

/*
 * Expand String object with function for shortening strings that is to long
 */
String.prototype.shorten = function(maxLength)
{
	if(this.length > (maxLength - 3))
		return this.substring(0, maxLength) + '...';
	else
		return this;
}


/*
 * Replaces all content in the main column with a 
 * lokus iframe and executes a search in the iframe
 */
function lokusFormSubmit(form, section)
{
	return insertTopFrame('http://lokus.norran.se/Exp_SearchStart.asp?strCounty=48&iCustomerType=-1&strFreeText='+escape(form.search.value)+( (section != '') ? '&strPortalAndProductType='+section:''));
}

function insertTopFrame(frameURL)
{
	children = $('#content').children();
	$('<iframe src="'+frameURL+'" frameborder="0" height="1000" width="469" style="margin-left:10px" name="contentframe" id="contentframe"></iframe>').insertBefore(children[0]);
	return false;
}


/*
 * Get value of XML node
 */
function nodeValue(node)
{
	if(node.data)
		return node.data;
	else if(node.nodeValue)
		return node.nodeValue;
	else if(node.innerHTML)
		return node.innerHTML;
	else if(node.textContent)
		return node.textContent;
	else if(node.text)
		return node.text;
	else
		return node.innerText;
}


/*
 * Open doc in a new window 
 */
function open_win(doc,width,height,scroller,resize,name)
{
	 name = (name) ? name:'';
	 width = (width) ? width:800;
	 height = (height) ? height:600;
	 scroller = (scroller) ? scroller:'no';
	 resize = (resize) ? resize:'no';
     win=window.open(doc, name, "screenX=100,screenY=100,scrollbars="+scroller+",resizable="+resize+",width="+width+",height="+height+",status=0,toolbar=0,menubar=0");
     win.focus();
}

// Global mouse position variables
var GLOB_mouseY = 0;
var GLOB_mouseX = 0;

window.onload = function()
{	
	// jQuery plugin that puts requests in queue  
	;(function($) {
		
		var ajax = $.ajax;
		var pendingRequests = {};
		var synced = [];
		var syncedData = [];
		
		$.ajax = function(settings) {
			settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings));	
			var port = settings.port;	
			switch(settings.mode) {
			case "abort": 
				if ( pendingRequests[port] ) {
					pendingRequests[port].abort();
				}
				return pendingRequests[port] = ajax.apply(this, arguments);
			case "queue": 
				var _old = settings.complete;
				settings.complete = function(){
					if ( _old )
						_old.apply( this, arguments );
					jQuery([ajax]).dequeue("ajax" + port );;
				};
			
				jQuery([ ajax ]).queue("ajax" + port, function(){
					ajax( settings );
				});
				return undefined;
			case "sync":
				var pos = synced.length;
		 
				synced[ pos ] = {
					error: settings.error,
					success: settings.success,
					complete: settings.complete,
					done: false
				};		
				syncedData[ pos ] = {
					error: [],
					success: [],
					complete: []
				};
			
				settings.error = function(){ syncedData[ pos ].error = arguments; };
				settings.success = function(){ syncedData[ pos ].success = arguments; };
				settings.complete = function(){
					syncedData[ pos ].complete = arguments;
					synced[ pos ].done = true;
			
					if ( pos == 0 || !synced[ pos-1 ] )
						for ( var i = pos; i < synced.length && synced[i].done; i++ ) {
							if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error );
							if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success );
							if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete );
			
							synced[i] = null;
							syncedData[i] = null;
						}
				};
			}
			return ajax.apply(this, arguments);
		};
		
	})(jQuery);
	
	// Easter egg
	var easterEgg = new Array(38,38,40,40,37,39,37,39,66,65);var eggIndex = 0; $(document).keydown(function(e){eggIndex++; if( (e.keyCode == 0 ? e.which:e.keyCode) != easterEgg[eggIndex - 1]){eggIndex = 0;}if(eggIndex == easterEgg.length){blink($('#logotype'), true);}});function blink(el, index){if(index){el.fadeOut('normal',function(){blink(el, false);});}else{el.fadeIn('normal',function(){blink(el, true);});}}
	
	// Load banner and third party js after page has loaded
	$('.bannercontainer').css({ 'display':'block' });
	$('.thirdparty').css({ 'display':'block' });
	
	// Mouse move
	$(document).mousemove(function(e){
		GLOB_mouseY = e.pageY;
		GLOB_mouseX = e.pageX;
	});
	
	// Article-banner
	if($('.banner_searchword').children().length < 3)
	{
		if($('.article_factbox_small').children().length < 2)
			$('.article_factbox_small').css({ 'display':'none' });
		else
			$('.banner_searchword').css({ 'display':'none' });
	}
	
	// Remove empty banner containers
	$('.bannercontainer').each(function() {
		numScripts = $(this).find('script').length + $(this).find('noscript').length;
		if(($(this).children().length - numScripts) == 0)
			$(this).hide();
	});
}

	

/* Gammal funktion vi inte längre ska använda... */
function open_win_scrollbar(doc,width,height)
{
     open_win(doc, width, height, 1);
}

function check_form(checkForm, spamcheckValue, fieldIds, fieldNames)
{
	for (var i = 0; i < fieldIds.length; i++)
	{
		var inputValue = new String($.trim(document.getElementById(""+fieldIds[i]).value));
		var strFieldId = new String(""+fieldIds[i]); 

		if (inputValue == "" || inputValue == "-1")
		{	
			alert("\"" + fieldNames[i] + "\" \344r obligatorisk");
			return false;
		}
		else if (strFieldId.indexOf('email') != -1)
		{	
			if (!is_valid_email(inputValue))
			{
				alert("\"" + fieldNames[i] + "\" inneh\345ller felaktigt format");
				return false;
			}
		}
		else if (strFieldId.indexOf('spamcheck') != -1)
		{	
			if (inputValue != spamcheckValue)
			{
				alert("\"" + fieldNames[i] + "\" inneh\345ller felaktigt v\344rde");
				return false;
			}
		}
	}
	
	checkForm.submit();
	return true;
}

function check_form_secure(checkForm, spamcheckValue, fieldIds, fieldNames)
{
	document.getElementById('secureCheck').value = "true";
	check_form(checkForm, spamcheckValue, fieldIds, fieldNames);
}

/* Start - Banner functions */
function create_banner_internet_seller(_version, sitepage, position, server)
{

	if (!(RN)) 
	{
		var RN = new String (Math.random());
		var RNS = RN.substring (2, 11);
	}
	var oas=server + '/RealMedia/ads/';
	var oaspage= sitepage + '/1' + RNS + '@' + position;
	
	if (_version < 11) 
	{
		document.write ('<A HREF="' + oas + 'click_nx.ads/'+ oaspage + '" TARGET="_top" ><IMG SRC="' + oas + 'adstream_nx.ads/' + oaspage + '" BORDER=0 WIDTH=300 HEIGHT=300 ALT="Klick!"></a>');
	} 
	else 
	{
		//alert(oas + 'adstream_jx.ads/' + oaspage);
		document.write ('<SCR'+'IPT LANGUAGE="JavaScript1.1" SRC="' + oas + 'adstream_jx.ads/' + oaspage + '">');
		document.write ('\<\!-- --\>');
		document.write ('\<\/SCRIPT\>');
		document.write ('\<\!-- --\>');
	}
}
/* End - Banner functions */


function eae_javascript_one_dot_one(loggerUrl,jsRt,jsObjId,jsType,jsCtxId,jsPubId,jsCat,jsMeta,jsTitle,jsUrl)
{
	var strStatistic = '<img src="' + loggerUrl + '?clientDT=' + (new Date()).getTime() + '&amp;rt=' + jsRt+ '&amp;objId=' + jsObjId  + '&amp;type=' + jsType + '&amp;ctxId=' + jsCtxId + '&amp;pubId=' + jsPubId + '&amp;cat=' + jsCat + '&amp;meta=' + jsMeta + '&amp;title=' + jsTitle + '&amp;url=' + jsUrl + '" width="1" height="1" alt=""/>';
	//alert(strStatistic);
	document.write(strStatistic);
}

function eae_javascript_ten(loggerUrl,jsRt,jsObjId,jsType,jsCtxId,jsPubId,jsCat,jsMeta,jsTitle,jsUrl)
{
	var strStatistic = '<img src="' + loggerUrl + '?rt=' + jsRt + '&amp;objId=' + jsObjId  + '&amp;type=' + jsType + '&amp;ctxId=' + jsCtxId + '&amp;pubId=' + jsPubId + '&amp;cat=' + jsCat +  '&amp;meta=' + jsMeta + '&amp;title=' + jsTitle + '&amp;url=' + jsUrl + '" width="1" height="1" alt=""/>';
	document.write(strStatistic);
}
