var MAX_COLUMN_HEIGHT = 370;
var MODAL_CONTAINER_ID = "#modalContainer";
var MODAL_CONTENT_ID = "#modalContent";
var SWIPE_ENABLED = false;
var phoneTimeout = null;
var subnavDimensions = new Array();

/** INDEX.HTML **/
function initClientSideImage()
{
	jQuery("#sideColumnFrame a img").bind("mouseover", function(){
		var src = jQuery(this).attr("src");
		
		if(stringEndsWith(src, "_bw.png"))
		{
			jQuery(this).attr("src", src.replace("_bw", ""));	
		}
	}).bind("mouseout", function(){
		var src = jQuery(this).attr("src");
		
		if(!stringEndsWith(src, "_bw.png"))
		{
			var newSrc = src.substring(0, src.length - 4) + "_bw.png";
			
			jQuery(this).attr("src", newSrc);	
		}
	});
}

function sendAnEmail(name, companyName, phone, email, message)
{
	
	jQuery(".sendEmailButton").attr("disabled", false);
	
	var params = {
		name: name,
		companyName: companyName,
		phone: phone,
		email: email,
		message: message
	};
	
	jQuery.ajax({ 
		url: EMAIL_URL, 
		type: "POST",
		cache: false,
		data: params,
		success: function(msg)
		{
			if(msg == MESSAGE_SENT)
			{
				var rootPath = getRootPath();
				logInfo('Root path: ' + rootPath);

				if('sv' == currentLanguage)
				{
					paintAlert("Meddelandet skickades!");
				}
				else if('no' == currentLanguage)
				{
					paintAlert('Melding sent!');
				}
				else
				{
					paintAlert("Message sent!");
				}

				jQuery('<div />', {id: 'conversionTrackerParent'}).appendTo('body');
				jQuery('<iframe />', { name: 'conversionTracker', id: 'conversionTracker', src: rootPath + 'conversiontracker.html'}).appendTo('div#conversionTrackerParent');
			}
			else if(stringStartsWith(msg, "error"))
			{
				logInfo("Response was: " + msg);
				
				if(msg == MISSING_PARAMETERS)
				{
					if('sv' == currentLanguage)
					{
						paintAlert("Du måste fylla i samtliga fält för att skicka meddelandet.");
					}
					else if('no' == currentLanguage)
					{
						paintAlert("Du må fylle ut alle feltene for å sende meldingen");
					}
					else
					{
						paintAlert("You havent filled in all necessary fields.");
					}
				}
				else if(msg == INVALID_EMAIL)
				{
					if('sv' == currentLanguage)
					{
						paintAlert("Du har angett en ogiltig epostadress.");
					}
					else if('no' == currentLanguage)
					{
						paintAlert("Du skrev inn en ugyldig e-postadresse.");
					}
					else
					{
						paintAlert("Your email seems to have invalid characters, please try again.");
					}
					
				}
				else if(msg == INVALID_PHONE_NUMBER)
				{
					if('sv' == currentLanguage)
					{
						paintAlert("Du har angett ett ogiltigt telefonnummer!");
					}
					else if('no' == currentLanguage)
					{
						paintAlert("Du skrev inn et ugyldig telefonnummer");
					}
					else
					{
						paintAlert("Your phone number seems invalid, please try again.");
					}
				}
				else if(msg == SEND_ERROR)
				{
					if('sv' == currentLanguage)
					{
						paintAlert("Ett fel inträffade och meddelandet skickades inte, var god försök igen.");
					}
					else if('no' == currentLanguage)
					{
						paintAlert("En feil oppstod, og meldingen ble ikke sendt, prøv igjen.");
					}
					else
					{
						paintAlert("An error occurred. Please try again!");
					}
				}
				else if(msg == UNKNOWN_ERROR)
				{
					if('sv' == currentLanguage)
					{
						paintAlert("Ett fel inträffade och meddelandet skickades inte, var god försök igen.");
					}
					else if('no' == currentLanguage)
					{
						paintAlert("En feil oppstod, og meldingen ble ikke sendt, prøv igjen.");
					}
					else
					{
						paintAlert("An error occurred. Please try again!");
					}
				}
				else
				{
					if('sv' == currentLanguage)
					{
						paintAlert("Ett fel inträffade och meddelandet skickades inte, var god försök igen.");
					}
					else if('no' == currentLanguage)
					{
						paintAlert("En feil oppstod, og meldingen ble ikke sendt, prøv igjen.");
					}
					else
					{
						paintAlert("An error occurred. Please try again!");						
					}
				}
			}
			else
			{
				logInfo('Bad reply from system: ' + msg);
				
				if('sv' == currentLanguage)
				{
					paintAlert("Ett fel inträffade och meddelandet skickades inte, var god försök igen.");
				}
				else if('no' == currentLanguage)
				{
					paintAlert("En feil oppstod, og meldingen ble ikke sendt, prøv igjen.");
				}
				else
				{
					paintAlert("An error occurred. Please try again!");						
				}
			}

			jQuery(".sendEmailButton").attr("disabled", false);
		},
		error: function(req, textStatus, errorThrown)
		{
			logInfo("Error thrown in while sendign message. XMLHTTPRequest HTTP status : " + req.statusText + ", error: " + errorThrown);
			jQuery(".sendEmailButton").attr("disabled", false);
		}
	});   
}

function initAbout()
{
	
}

function getRootPath()
{
	var pathname = window.location.href;
	
	if(pathname.indexOf('/sv/') > 0)
	{
		pathname = pathname.substring(0, pathname.indexOf('/sv/') + 4);
	}
	else if(pathname.indexOf('/no/') > 0)
	{
		pathname = pathname.substring(0, pathname.indexOf('/no/') + 4);
	}
	else if(pathname.indexOf('/en/') > 0)
	{
		pathname = pathname.substring(0, pathname.indexOf('/en/') + 4);
	}
	
	return pathname;
}

//http://docs.jquery.com/Tutorials:PNG_Opacity_Fix_for_IE6
function fixPng(png)
{
	 // get src
	   var src = png.src;
	   // set width and height
	   if (!png.style.width) { png.style.width = jQuery(png).width(); }
	   if (!png.style.height) { png.style.height = jQuery(png).height(); }
	   // replace by blank image
	   png.onload = function() { };
	   png.src = blank.src;
	   // set filter (display original image)
	   png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";

}

function initServices()
{
	var pageName = window.location.pathname.substring(window.location.pathname.lastIndexOf("/") + 1, window.location.pathname.lastIndexOf('.html'));
	
	var isMajorServicePage = false;
	var currentBoxId = null;
	
	if(pageName == 'sms')
	{
		isMajorServicePage = true;
		currentBoxId = "smsBoxNav";
	}
	else if(pageName == 'email')
	{
		isMajorServicePage = true;
		currentBoxId = "emailBoxNav";
	}
	else if(pageName == 'apps')
	{
		isMajorServicePage = true;
		currentBoxId = "appsBoxNav";
	}
	else if(pageName == 'mobileadvice')
	{
		isMajorServicePage = true;
		currentBoxId = "mobileadviceBoxNav";
	}

	if(isMajorServicePage)
	{
		jQuery("#" + currentBoxId).css('backgroundPosition', '0 -184px');
	}
	
	jQuery(".serviceSideBox").hover(
			function(ev){
				var imgSrc = jQuery(this).children("a").children("img").attr("src");
	            imgSrc = imgSrc.substring(0, imgSrc.indexOf('.png')) + '_on.png';
	            jQuery(this).children("a").children("img").attr("src", imgSrc);
			}, 
			function(ev){
				var imgSrc = jQuery(this).children("a").children("img").attr("src");
	            imgSrc = imgSrc.replace("_on", "");
	            jQuery(this).children("a").children("img").attr("src", imgSrc);
			}
		);
	
	jQuery("#boxNav nav ul li").hover(
			function(ev){
				if(jQuery(this).attr("id") != currentBoxId)
				{
		            jQuery(this).css('backgroundPosition', '0 -184px');
				}
			}, 
			function(ev){
				if(jQuery(this).attr("id") != currentBoxId)
				{
		            jQuery(this).css('backgroundPosition', '0 0');
				}
			}
		);
	
	//Set extra padding for sidecolumn to make boxes align to paragraph
	//jQuery("#sideColumn").css("paddingTop", 220);
}

function initClients()
{
}



function paintNextLinkItem()
{
	if(linkItemTimeout != null)
	{
		clearTimeout(linkItemTimeout);
	}
	
	if(currentlyDisplayedLinkItem == linkItems.length)
	{
		currentlyDisplayedLinkItem = 0;
	}

	var linkItem = linkItems[currentlyDisplayedLinkItem];

	if(linkItem != null)
	{
		jQuery("#alertRow span").fadeOut("fast", function(){
			jQuery("#alertRow span").html(linkItem.getDescription() + ': <a href="' + linkItem.getUrl() + '" target="_blank" title="' + linkItem.getDescription() + '">' + linkItem.getUrl() + '</a ').fadeIn("fast");
		});
	}
	else
	{
		logInfo("Link item at index " + currentlyDisplayedLinkItem + " was null.");
	}

	currentlyDisplayedLinkItem++;
	
	linkItemTimeout = setTimeout("paintNextLinkItem();", linkItemTimeoutInterval);
}

function newsListSorter(a, b)
{
	var aDate = a != null && a.getReleaseDate() != null ? a.getReleaseDate() : new Date(0);
	var bDate = b != null && b.getReleaseDate() != null ? b.getReleaseDate() : new Date(0);
	
	if(aDate.getTime() < bDate.getTime())
	{
		return 1;
	}
	else
	{
		return -1;
	}
	
	return 0;
}

function formatNewsDate(date)
{
	if(date != null)
	{
		var y = '' + date.getFullYear();
		var m = '' + (date.getMonth() + 1);
		var d = '' + date.getDate();
		var h = '' + date.getHours();
		var min = '' + date.getMinutes();

		if(m.length == 1)
		{
			m = "0" + m;
		}
		if(d.length == 1)
		{
			d = "0" + d;
		}
		if(h.length == 1)
		{
			h = "0" + h;
		}
		if(min.length == 1)
		{
			min = "0" + min;
		}
		
		if(currentLanguage == 'sv')
		{
			return y + "-" + m + "-" + d + " " + h + ":" + min;
		}
		else if(currentLanguage == 'no')
		{
			return y + "-" + m + "-" + d + " " + h + ":" + min;
		}
		else
		{
			return d + "/" + m + "/" + y + " " + h + ":" + min;
		}
	}
	else
	{
		return "";
	}
}


/** Init functions **/
function initNav()
{
	if(currentLanguage == 'sv' || currentLanguage == 'en')
	{
		//Append link for job applications in the footer. This is done in pure javascript until Send 5.0 is installed. 
		jQuery('#footerAddress').append('<a id="jobsfooterLink" href="/web/content/' + currentLanguage + '/jobs/sales.html"><img src="/web/content/res/img/jobs_footer_off_' + currentLanguage + '.png" alt="LINK Mobile Solutions"></a>');
	
	 	jQuery("#footerAddress img").bind('mouseover', function(){
			jQuery(this).attr("src", jQuery(this).attr("src").replace('_off_', '_on_'));
	 	}).bind('mouseout', function(){
	 		jQuery(this).attr("src", jQuery(this).attr("src").replace('_on_', '_off_'));
	 	});
	}
	jQuery("#navigation ul li a").bind("mousedown", function(){
		jQuery(this).css("padding-top", 1);
	}).bind("mouseup", function(){
		jQuery(this).css("padding-top", 0);
	});
	
	//Init main navigation mouseover effect
	jQuery('#navigation ul li a').bind('mouseenter', function(e){
		jQuery(this).children('img.inactiveNavigationItem').css('margin-top', '0px');
	}).bind('mouseleave', function(e){
		jQuery(this).children('img.inactiveNavigationItem').css('margin-top', '-34px');
	});
	
	if(jQuery('#subNav').length > 0)
	{
		jQuery('#subNav ul li a').bind('mouseenter', function(e){
			jQuery(this).children('img.inactiveSubnavItem').css('margin-top', '0px');
		}).bind('mouseleave', function(e){
			jQuery(this).children('img.inactiveSubnavItem').css('margin-top', '-25px');
		}).bind('mousedown', function(e){
			var c = jQuery(this).children('img.inactiveSubnavItem');
			c.css('margin-top', c.css('margin-top') + 1);
		}).bind('mouseup', function(e){
			var c = jQuery(this).children('img.inactiveSubnavItem');
			c.css('margin-top', c.css('margin-top') - 1);
		});
	}
}

function getWidthAndPositionLogString(element)
{
	var log = '';
	
	if(element != null)
	{
		if(typeof(element) == 'string')
		{
			element = jQuery("#" + element);
		}
		
		var offset = element.offset();
		
		log = 'Dimension (w: ' + element.width() + ', h: ' + element.height() + '), Position (t: ' + offset.top + ', l: ' + offset.left;
	}
	
	return log;
}

/** Standard functions **/

function logInfo(stringToLog)
{
	if ( this.console && typeof(console.log) != 'undefined' ) 
	{ 
		// IE8, Firebug, Safari, etc. 
		console.log(stringToLog); 
	}
}

function trimString(s)
{
	return (s.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
}

function stringStartsWith(target, prefix)
{
	if(typeof(target) == 'undefined' || target == null || typeof(prefix) == 'undefined' || prefix == null )
	{
		return false;
	}
	
	return (target.toLowerCase().match("^" + prefix.toLowerCase()) == prefix.toLowerCase());
}

function stringEndsWith(target, prefix)
{
	if(typeof(target) == 'undefined' || target == null || typeof(prefix) == 'undefined' || prefix == null )
	{
		return false;
	}
	
	return (target.toLowerCase().match(prefix.toLowerCase() + "$") == prefix.toLowerCase());
}

function getDialogCSSObject(id)
{
	var pageScroll = getPageScroll();
	var scrollTop = pageScroll[1];
	var element = jQuery('#' + id);
	var dheight = element.height();
	var dwidth = element.width();
	var wheight = jQuery(window).height();
	var wwidth = jQuery(window).width();
	
	var cssObj = {
        "top": ((wheight / 2) - (dheight / 2)) * 0.8 + scrollTop,
        "left": (wwidth / 2) - (dwidth / 2),
        "position": "absolute"
   	}
	
	return cssObj;
}

function getScrollTop()
{
	getPageScroll()[0];
}

function uriEncodeParam(param)
{
	var regExp = '[A-Za-z0-9]';
	var returnParam = '';
	
	if(param != null)
	{
		for(var i = 0; i < param.length; i++)
		{
			var s = param.charAt(i);
			if(s != null && !s.match(regExp))
			{
				returnParam = returnParam + encodeURIComponent(s);
			}
			else if(s != null)
			{
				returnParam = returnParam + s;
			}
		}
	}
	return returnParam;
}

function validateMobileNumber(mobileNumber)
{
	if(mobileNumber == null || typeof(mobileNumber) != 'string' || mobileNumber.length < 7 || mobileNumber.length > 19)
	{
		return false;
	}
	
	var digitCount = 0;
	
	for(var i = 0; i < mobileNumber.length; i++)
	{
		var next = mobileNumber.charAt(i);
		
		if(!isNaN(next))
		{
			digitCount++;
		}
	}
	
	if(digitCount > 7)
	{
		return true;
	}
	
	return false;
}

function safeString(s)
{
	if(s != null)
	{
		s = wafReplaceAll(s, '"', '\"');

		return s;
	}
	
	return '';
}

function wafReplaceAll(theString, oldChar, newChar)
{
 	if(theString != null && theString.length > 0)
 	{
 		while(theString.indexOf(oldChar) != -1)
 		{
 			theString = theString.replace(oldChar, newChar);
 		}
 	}

 	return theString;
} 


//getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
}

// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
    var windowHeight
    if (self.innerHeight) { // all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
}

//MODAL WINDOW
function paintModalWindow(contentId, width, height)
{
	if(jQuery("#" + MODAL_CONTAINER_ID).length == 0)
	{
		jQuery("body").append('<div id="' + MODAL_CONTAINER_ID + '"><a class="modalCloseImg" title="Close"></a><div class="modalInnerContainer"><div class="modalContent"></div></div></div>');
	}
	
	var container = jQuery("#" + MODAL_CONTAINER_ID);
	
	if(width != null && typeof(width) == 'number')
	{
		container.css('width', width);
	}
	
	if(height != null && typeof(height) == 'number')
	{
		container.css('height', height);
	}	
	
	var cssObj = getDialogCSSObject(id);
	
	container.css(cssObj).fadeIn("fast");
}

function paintAlert(message)
{
	 if(jQuery("#alertDialog").length == 0)
	 {
		 jQuery('body').append('<div id="alertDialog"><span id="alertDialogCloseIcon"></span><span id="alertDialogBody"></span></div>');
		 
		 jQuery("#alertDialogCloseIcon").click(function(){
			hideOverlay();
			jQuery("#alertDialog").fadeOut("fast");
		});
	 }

	 jQuery("#alertDialogBody").html(message);
	 
	 var alertCss = getDialogCSSObject("alertDialog");
	 showOverlay();
	 jQuery("#alertDialog").css(alertCss).fadeIn("fast");
}

function showOverlay()
{
	var height = jQuery(document).height();
	var width = jQuery(document).width();
	
	var overlayDiv = wafSafeGetDialogWindow("overlay");
	
	if(jQuery("#overlay").length == 0)
	{
		jQuery('body').append('<div id="overlay"></div>');
		
		jQuery("#overlay").live("click", function(){
			hideOverlay();
		});
	 }
	 
 	if(jQuery.browser.msie && jQuery.browser.version < 9 )
 	{
 		overlayDiv.css({'filter' : 'alpha(opacity=50)', 'height' : height, 'width' : width}).fadeIn("fast");
 	}
 	else
 	{
 		overlayDiv.height(height).width(width).fadeIn("fast");
 	}
}

function hideOverlay()
{
	jQuery("#overlay").fadeOut("fast").width(1).height(1);
} 

function wafSafeGetChildDiv(elementId, parentId, className)
{
	 if(elementId != null && typeof(elementId) == 'string')
	 {
		 if(jQuery("#" + parentId + " #" + elementId).length == 0)
		 {
		 	if(className != null && typeof(className) == 'string')
			{
		 		jQuery('#' + parentId).append('<div id="' + elementId + '" class="' + className + '"></div>')
			}
			else
			{
				jQuery('#' + parentId).append('<div id="' + elementId + '"></div>')
			}
		 }

		 return jQuery("#" + elementId);
	 }

	 return null;
}

function wafSafeGetDialogWindow(elementId, className)
{
 if(elementId != null && typeof(elementId) == 'string')
 {
 if(jQuery("#" + elementId).length == 0)
{
 if(className != null && typeof(className) == 'string')
 {
 jQuery('body').append('<div id="' + elementId + '" class="' + className + '"></div>')
 }
 else
 {
 jQuery('body').append('<div id="' + elementId + '"></div>')
 }
 }

 return jQuery("#" + elementId);
 }

 return null;
} 


//GOOGLE MAPS API

var marker;
var map;

function initMap(office) 
{
	var stockholm = new google.maps.LatLng(59.32522, 18.07002);
	var oslo = new google.maps.LatLng(59.914031,10.741324);
	//Tallinn: sll=37.0625,-95.677068&sspn=57.379893,79.013672
	var tallinn = new google.maps.LatLng(57.379893,79.013672);
	//Riga: ll=56.943125,24.067655&spn=0.009785,0.01929&sll=37.926868,-95.712891&sspn=55.27658,79.013672
	var riga = new google.maps.LatLng(56.943125,24.067655);
	
	var currentArea = null;
	
	if('oslo' == office)
	{
		currentArea = oslo;
	}
	else if('tallinn' == office)
	{
		currentArea = tallinn
	}
	else if('riga' == office)
	{
		currentArea = riga;
	}
	else
	{
		currentArea = stockholm;
	}
	
	office != null && office != 'oslo' ? stockholm : oslo;
	
	var mapOptions = {
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: currentArea
  };

  map = new google.maps.Map(document.getElementById("phoneDisplay"),
      mapOptions);

  marker = new google.maps.Marker({
    map:map,
    draggable:true,
    animation: google.maps.Animation.DROP,
    position: currentArea
  });
  google.maps.event.addListener(marker, 'click', toggleBounce);
  
  /*
  var mapOverlayDiv = wafSafeGetChildDiv("officeMapOverlay", "phoneDisplay");
  var sthlmSrc = null;
  var osloSrc = null;
  var html = '';
  
  if('oslo' == office)
  {
	  //html += '<a href="javascript:void(0);" onclick="initMap(\'stockholm\');"><img id="mapOverlayStockholm" src="../res/img/mapOverlayStockholm.png" alt="Stockholm" /></a>';
  }
  else
  {
	  //html += '<a href="javascript:void(0);" onclick="initMap(\'oslo\');"><img id="mapOverlayOslo" src="../res/img/mapOverlayOslo.png" alt="Oslo" /></a>';
  }
  
  //mapOverlayDiv.html(html);
  */
}

function toggleBounce() {

  if (marker.getAnimation() != null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}
