﻿var SYS = {};
var UI = {};


/* ON DOM LOAD
-----------------------------------------------------------------------*/
$(document).ready(function() {
	SYS.Init();
	UI.Init();
	initNewsFlow();
	initFade();
	initFadeModalUpdate();
	initProgressModal();
	initCloseModalKey();
	initTranslateMenu();
	initLoadMoreNews();
	initHideCol();
	initTooltip();
	Twitter.init();
	LnkTarget.init();
});    

//Global vars
var currentPosition = 0;
var itemCount = 0;
var winH = 0;
var winW = document.documentElement.offsetWidth;

/* 
-----------------------------------------------------------------------*/
SYS.Init = function() {
    this.mouseX = 0;
    this.mouseY = 0;
    $(document).mousemove(function(e) {
        SYS.mouseX = e.pageX;
        SYS.mouseY = e.pageY;
    });
};

/* 
-----------------------------------------------------------------------*/
UI.Init = function() {


    $.ajax({
        type: 'POST',
        url: '/Templates/Services/ModuleZones.asmx/IsAdmin',
        cache: false,
        data: "{ }",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        error: function(xhr, status, error) {
            alert('Ooops! Something went wrong. Call for Admin ' + status + ' ' + error);
        },
        success: function(result) {
            if (result.d) {
                $('#rightcol').sortable({
                    placeholder: 'module-highlight',
                    items: '.module',
                    connectWith: '#leftcol',
                    opacity: 0.95,
                    distance: 30,
                    revert: true,
                    tolerance: 'pointer',
                    forcePlaceholderSize: true,
                    stop: function(e, ui) {
                        $(ui.item).effect('highlight', {}, 800);
                        var moduleParentId = $(ui.item).parent().attr('id').toString();
                        var moduleId = $(ui.item).attr('id').toString();
                        var modulePosition;
                        $('#' + moduleParentId + ' .module').each(function(i, elm) {
                            if ($(elm).attr('id') == moduleId) {
                                modulePosition = i.toString();
                                return false;
                            }
                        });
                        $.ajax({
                            type: 'POST',
                            url: '/Templates/Services/ModuleZones.asmx/SetModuleLocation',
                            cache: false,
                            data: "{ 'moduleId':'" + moduleId + "', 'targetContainer':'" + moduleParentId + "', 'position':'" + modulePosition + "' }",
                            contentType: "application/json; charset=utf-8",
                            dataType: 'json',
                            error: function() {
                                alert("Ooops! Something went wrong when updating the module position.");
                            },
                            success: function(result) {

                            }
                        });
                    }
                });
                $('#leftcol').sortable({
                    placeholder: 'module-highlight',
                    items: '.module',
                    connectWith: '#rightcol',
                    opacity: 0.95,
                    distance: 30,
                    revert: true,
                    tolerance: 'pointer',
                    forcePlaceholderSize: true,
                    stop: function(e, ui) {
                        $(ui.item).effect('highlight', {}, 800);
                        var moduleParentId = $(ui.item).parent().attr('id').toString();
                        var moduleId = $(ui.item).attr('id').toString();
                        var modulePosition;
                        $('#' + moduleParentId + ' .module').each(function(i, elm) {
                            if ($(elm).attr('id') == moduleId) {
                                modulePosition = i.toString();
                                return false;
                            }
                        });
                        $.ajax({
                            type: 'POST',
                            url: '/Templates/Services/ModuleZones.asmx/SetModuleLocation',
                            cache: false,
                            data: "{ 'moduleId':'" + moduleId + "', 'targetContainer':'" + moduleParentId + "', 'position':'" + modulePosition + "' }",
                            contentType: "application/json; charset=utf-8",
                            dataType: 'json',
                            error: function() {
                                alert("Ooops! Something went wrong when updateing the box position.");
                            },
                            success: function(result) {

                            }
                        });
                    }
                });
                $('.moduleinner').css({ cursor: 'move' });
            }
        }
    });
}

/* 
-----------------------------------------------------------------------*/
var initHideCol = function() {
    var hideWrapper = $('#hidecol');
    if (hideWrapper.length == 0) return;

    $(hideWrapper).animate({
        opacity: 0.5,
        left: 219
    }, 1300, 'swing', function() {
        $(this).css({ borderLeft: '1px solid #dcdcdc' });
        $(this).append('<div class="arrow"></div>');
        $('#hidecol .arrow').animate({
            left: -26
        });
        $('#hidecol .arrow').mouseenter(function() {
            $(this).animate({
                left: -30
            }).mouseleave(function() {
                $(this).animate({
                    left: -26
                });
            });
        });
        $('#hidecol .arrow').bind('click', function() {
            $(hideWrapper).animate({
                opacity: 1,
                left: 0
            }, 600, 'swing', function() {
                $(hideWrapper).css({ borderLeft: 'none' });
            });
            $('#hidecol .arrow').fadeOut('fast');
        });
    });
}


/* UPDATE MODAL ITEM PROGRESS LOADER
-----------------------------------------------------------------------*/
var initProgressModal = function() {
    if ($('#modalprogress').length == 0) return;
    $('#modalprogress').css({ 'top': winH + 50, 'display': 'block' });
    $('#modalprogress').css('left', winW / 2 - 307);
    //$('#modalprogress').css('left', winW / 2 - $('#modalprogress').width() / 2); 614
}

/* "FADE DOWN" SITE
-----------------------------------------------------------------------*/
var initFade = function() {

    //select all the a tags with name equal to modal
    $('a[name=modal]').click(function(e) {
        initProgressModal();    
        //Cancel the link behavior
        //e.preventDefault();
        //set lik href to not point to chanel
        $('a[name=modal]').attr('href', '#modalprogress');

        //Get the screen height and width  
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set heigth and width to mask to fill up the whole screen  
        $('#fade').css({ 'width': maskWidth, 'height': maskHeight });

        //show faded site overlay
        $('#fade').show();
        $('#fade').css('opacity', 0.7);

        //find flash on page and hide it
        toggleFlash();
    });
}

/* SERVICE ITEM MODAL POPUP
-----------------------------------------------------------------------*/
var initCloseModalKey = function() {
    //if esc button on keyboard is clicked
    $(document).keydown(function(e) {
        if (e.keyCode == '27' && $('#modal').css('display') != 'none' || $('#modal').length > 0) {
            //Reset slide position and item count
            currentPosition = 0;
            itemCount = 0;
            $('#fade, .modal').hide();
            //find flash on page and show it
            toggleFlash();
        }
    });
}

/* SERVICE ITEM MODAL POPUP
-----------------------------------------------------------------------*/
var initServiceItemModal = function() {

    initSlideNavigation();
    initExtendedInfo();


    //if close button is clicked  
    $('.modal .close').click(function(e) {
        //Cancel the link behavior  
        e.preventDefault();
        //Reset slide position and item count
        currentPosition = 0;
        itemCount = 0;
        $('#fade, .modal').hide();
        //find flash on page and show it
        toggleFlash();
    });

    //if mask is clicked
    $('#fade').bind('click', function() {
        // do click only if service modal is visible    
        if ($('#modal').css('display') == 'block') {
            //Reset slide position and item count
            currentPosition = 0;
            itemCount = 0;
            $(this).hide();
            $('.modal').hide();
            //find flash on page and show it
            toggleFlash();
        }
    });

    //Cancel the link behavior  
    //e.preventDefault();
    var id = '#modal';

    //Get the window height and width
    //var winH = $(window).scrollTop();
    winW = document.documentElement.offsetWidth;

    //Set the popup window to center
    $(id).css('top', winH + 50);
    $(id).css('left', winW / 2 - $(id).width() / 2);

    //show modal pop up
    $(id).fadeIn();
    //$(id).slideDown('slow');

    //Set length of service slide
    var slide = $('.serviceslide');
    if (slide.length == 0) return;
    //Reset position
    slide.css({ 'left': 0 });
    var serviceItems = $('.serviceslide .servicethumb');
    if (serviceItems.length == 0) return;


    //Number of service items with 10px margin
    $(slide).css({ 'width': serviceItems[0].offsetWidth * serviceItems.length + serviceItems.length * 10 });
    $('#modal .slideleft').css({ 'display': 'none' });
    $('#modal .slideright').css({ 'display': 'none' });
    //Check if slide contains hidden items. If so, display navigation arrow
    if (slide.width() > $(id).width()) {
        $('#modal .slideright').css({ 'display': 'block' });
    }


    var itemDescription;
    var itemViews;
    var itemTitle;
    $('a[name=tooltip]').click(function(e) {
        //Cancel the link behavior
        e.preventDefault();
        $(this).blur();

        // get all the hidden inputfield containing item information
        itemInfoArray = $(this).siblings();
        //loop through the object, extract the values and assign them to their varibles
        $(itemInfoArray).each(function(i) {
            // Switch case the type of object
            switch ($(itemInfoArray[i]).attr('class')) {
                case 'description':
                    itemDescription = $(itemInfoArray[i]).attr('value');
                    break;
                case 'title':
                    itemTitle = $(itemInfoArray[i]).attr('value');
                    break;
                case 'views':
                    itemViews = $(itemInfoArray[i]).attr('value');
                    break;
                default: ;
            }
        });

        //get the active item graphics (image, flash etc)
        var currentImage = $('#modal .currenitem').children()[0];
        //if loading layer does not exist, create it...
        if ($('#itemcover').length == 0) var tempItemCover = '<div id="itemcover"></div>';
        //... and add it to html tree
        $('.currenitem').append(tempItemCover);
        //Get the A tag href of clicked thumnail
        var servicePath = $(this).attr('href');
        // animate the active item graphics
        $(currentImage).animate({ opacity: '0' }, function() {
            //add loading class to loading layer
            $('#itemcover').addClass('loading');
            $(currentImage).css({ 'visibility': 'hidden' });

            // Switch case the type of object
            switch (currentImage.tagName.toLowerCase()) {
                // if active object is an immage                                    
                case 'img':
                    // wrap our new image in jQuery
                    $(currentImage)
                    // once the image has loaded, execute this code
                    .load(function() {
                        // get the eight of the new image
                        var newHeight = this.offsetHeight;
                        // remove old image
                        $(currentImage).remove();
                        // then insert our new image
                        $('.currenitem').append(this);
                        // remove the loading class (so no background spinner)
                        $('#itemcover').remove();
                        $(this).css({ 'visibility': 'visible' });
                        // animate container with new image loaded
                        $('.currenitem').animate({ height: newHeight });
                        // and show new image
                        $(this).animate({ opacity: '1' });
                    })
                    //if there was an error loading the image, react accordingly
                    .error(function() {
                        alert('Oups, some error ocurred. Please reload your browser');
                    })
                    // finally, set the src attribute of the new image to our image
                    .attr('src', servicePath);
                    // set item title
                    $('.iteminfo h3').text(itemTitle);
                    // set item description
                    $('.iteminfo p').text(itemDescription);
                    break;
                // if active object is a Flash   
                case 'object':
                    // if active object is a Flash in IE WITH data attribute add new 
                    if ($.browser.msie) {
                        var flashArray = $(currentImage).children();
                        $('#itemcover').remove();
                        var currentFlashIE = $('#modal .currenitem');
                        currentFlashIE.remove();
                        var newFlashEmbed = '<EMBED style="FILTER: alpha(opacity=0); VISIBILITY: hidden; ZOOM: 1" src="' + servicePath + '" width=320 height=265 type=application/x-shockwave-flash allowfullscreen="true" allowscriptaccess="always"></EMBED>'
                        $('#modalinner').prepend('<div class="currenitem">' + newFlashEmbed + '</div>');
                        $('#modal .currenitem embed').css({ 'visibility': 'visible' });
                        $('#modal .currenitem embed').animate({ opacity: '1' });
                        $('.iteminfo h3').text(itemTitle);
                        $('.iteminfo p').text(itemDescription);
                    } else {
                        // get all nodes in object tag
                        var flashArray = $(currentImage).children();
                        $(flashArray).each(function(i) {
                            // if node contains the attribute name:movie
                            if ($(flashArray[i]).attr('name') == 'movie') {
                                $(flashArray[i]).attr('value', servicePath);
                            }
                            if ($(flashArray).parent().attr('data').length > 0) {

                                $(flashArray[i]).parent().attr('data', servicePath);
                            }
                            // if node is an emed tag
                            if (flashArray[i].tagName.toLowerCase() == 'embed') {
                                $(flashArray[i]).attr('src', servicePath);
                            }
                        });
                        // remove the loading class (so no background spinner)
                        $('#itemcover').remove();
                        $(this).css({ 'visibility': 'visible' });
                        $(this).animate({ opacity: '1' });
                        // set item title
                        $('.iteminfo h3').text(itemTitle);
                        // set item description
                        $('.iteminfo p').text(itemDescription);
                    }
                    break;
                // if active object is a Flash in IE WITHOUT data attribute                          
                case 'embed':
                    // *IE SOLUTION* FOR REPLACING SRC IN AN EMBED TAG
                    // get all nodes (embed) in object tag
                    var flashArray = $(currentImage).children();
                    // remove the loading class (so no background spinner)
                    $('#itemcover').remove();
                    // get wrapper for flash object
                    var currentFlashIE = $('#modal .currenitem');
                    // delete flash object including its wrapper
                    currentFlashIE.remove();
                    // create anew embed string with updated src
                    var newFlashEmbed = '<EMBED style="FILTER: alpha(opacity=0); VISIBILITY: hidden; ZOOM: 1" src="' + servicePath + '" width=320 height=265 type=application/x-shockwave-flash allowfullscreen="true" allowscriptaccess="always"></EMBED>'
                    // add new flash object and its wrapper
                    $('#modalinner').prepend('<div class="currenitem">' + newFlashEmbed + '</div>');
                    $('#modal .currenitem embed').css({ 'visibility': 'visible' });
                    $('#modal .currenitem embed').animate({ opacity: '1' });
                    // set item title
                    $('.iteminfo h3').text(itemTitle);
                    // set item description
                    $('.iteminfo p').text(itemDescription);
                    break;
                default: ;
            }
        });
    });
}

/* FIND FLASH CONTENT AND HIDE ID. FIX FOR Z-INDEX ISSUE WITH FLASH IN BROWSER
-----------------------------------------------------------------------*/
var toggleFlash = function() {
    var flasObjekt = $('.flash');
    if (flasObjekt.length < 1) return;
    //if flash exists on page
    for (var i = 0; i < $(flasObjekt).length; ++i) {
        if ($(flasObjekt[i]).css('visibility') == 'visible') {
            $(flasObjekt[i]).css({ 'visibility': 'hidden' });
        } else {
            $(flasObjekt[i]).css({ 'visibility': 'visible' });
        }
    }
}

/* UPDATE POPUP LOCATION WHEN SCROLLING AND UPDATE MASK WHEN RESIZING WINDOW
-----------------------------------------------------------------------*/
var initFadeModalUpdate = function() {
    $(window).scroll(function() {
        //update winH if window is scrolled  
        winH = $(window).scrollTop();
        if ($('#fade').css('display') == 'block') {

            //Get the screen height and width  
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();
            //Get the window height and width  
            var winW = document.documentElement.offsetWidth;
            //Set the popup window to center  and resize the mask
            $('#fade').css({ 'width': maskWidth, 'height': maskHeight });
            $('#modal').css('left', winW / 2 - $('#modal').width() / 2);
        }
    });
    $(window).resize(function() {
        if ($('#fade').css('display') == 'block') {
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();
            winW = document.documentElement.offsetWidth;
            $('#fade').css({ 'width': maskWidth, 'height': maskHeight });
            $('#modal').css('left', winW / 2 - $('#modal').width() / 2);
        }
    });

}
/* SLIDE NAVIGATION FOR SERVICE ITEMS
-----------------------------------------------------------------------*/
var initSlideNavigation = function() {

    if ($('span[name=serviceslide]').length < 1) return;

    //select all the a tag with name equal to slide
    $('span[name=serviceslide]').click(function(e) {
        //Cancel the link behavior
        e.preventDefault();
        $(this).blur();

        //get slide wrapper and its items
        var slide = $('.serviceslide');
        var serviceItems = $('.serviceslide .servicethumb');

        /*
        item margin:10, 
        visible items:4
        */
        if (this.className == 'slideright') {
            $(slide).animate({ left: currentPosition - serviceItems[0].offsetWidth - 10 }, 'normal', function() {
                currentPosition = currentPosition - serviceItems[0].offsetWidth - 10;
                if (currentPosition < 0) $('#modal .slideleft').css({ 'display': 'block' });
                itemCount++;
                if (itemCount + 4 == serviceItems.length) $('#modal .slideright').css({ 'display': 'none' });
            });
        } else if (this.className == 'slideleft') {
            $(slide).animate({ left: currentPosition + serviceItems[0].offsetWidth + 10 }, 'normal', function() {
                currentPosition = currentPosition + serviceItems[0].offsetWidth + 10;
                if (currentPosition >= 0) $('#modal .slideleft').css({ 'display': 'none' });
                itemCount--;
                if (itemCount + 4 < serviceItems.length) $('#modal .slideright').css({ 'display': 'block' });
            });
        }

    });
}
/* OPEN/CLOSE ADDITIONAL INFO IN SERVICE POPUP
----------------------------------------------------------------------*/
var initExtendedInfo = function() {
	//get more info link  
	var moreInfoLink = $('a[name=extendedinfo]');
	/*var cloneMoreInfoLink = $(moreInfoLink).clone(true);
	$(cloneMoreInfoLink).text('Less info');
	$(cloneMoreInfoLink).insertAfter($(moreInfoLink));*/
    $(moreInfoLink).click(function(e) {
		//Cancel the link behavior  
        e.preventDefault();
		$('.extendedinfo').slideToggle('normal', function(){
			$('a[name=extendedinfo]').text() == 'More info' ? 'Less info' : 'More info';
		});
	});
}

/* MOUSE OVER SERVICE ITEM
----------------------------------------------------------------------*/
var initTooltip = function() {
    if ($('.tooltip').length == 0) {
        $('body').append('<em class="tooltip"></em>');
    }
    $('.tooltip').css({ opacity: 0.9 });

    $('.serviceslide [title]').live('mouseover', function() {
        $('.tooltip').html($(this).attr('title'));
        $('.tooltip').css({ display: 'block' });
        $(this).attr('title', '');
        $(this).children().attr('alt', '');
    });

    $('.serviceslide [title=""]').live('mouseout', function() {
        $(this).attr('title', $('.tooltip').html());
        $('.tooltip').css({ display: 'none' });
        $('.tooltip').html('');
    });

    $('.serviceslide [title=""]').live('mousemove', function() {
        if (SYS.mouseX + $('.tooltip').width() + 35 > SYS.winWidth) {
            $('.tooltip').css({
                top: SYS.mouseY + 8,
                left: SYS.mouseX - 30 - $('.tooltip').width()
            });
        } else {
            $('.tooltip').css({
            top: SYS.mouseY + 8,
            left: SYS.mouseX + 15
        });
        }
    });
};

/* FILTER TYPE OF NEWS FLOW
----------------------------------------------------------------------*/
var initNewsFlow = function() {
    $('ul.mediatypes').css({ 'display': 'block' })

    var prm = $('#newsflow .prm');
    //get more info link
    var newsFlowLink = $('a[name=newsflow]');
    if ($(newsFlowLink).length < 1) return;



    $(newsFlowLink).click(function(e) {
        //Cancel the link behavior  
        e.preventDefault();
        //get parent class name
        var thisParentClass = $(this).parent().attr('class');
        if (thisParentClass == 'selected') return;
        //get all menu items
        var menuItemsArray = $(this).parent().parent().children();
        //remove menu item classname selected
        $(menuItemsArray).each(function(i) {
            $(menuItemsArray).removeClass('selected');
        });
        //get the selected media to keep in filter
        var selectedFlow = $(this).attr('class');
        //set class name of selected media parent to selected
        $(this).parent().addClass('selected');

        var mediaFlow = $('#newsflow .newsitemdiv');
        //filter out media flow

        var url = window.location.href;


        mediaFlow
			.hide()
			.filter('#newsflow .' + selectedFlow)
			.show();

        if (url.indexOf('/en') == -1) {
            if (selectedFlow == 'newsitem') {
                Twitter.init();
                var current;
                mediaFlow.each(function(i) {
                    current = $(mediaFlow[i]);
                    current.removeAttr('style');
                });
                prm.hide();
            } else if (selectedFlow == 'blogs') {
                Twitter.clear();
            } else if (selectedFlow == 'prm') {
                prm.show();
            }
        }
    });
}

/* GOOGLE TRANSLATE MENU
----------------------------------------------------------------------*/
var initTranslateMenu = function() {

    //Get Translate menu and show it
    var translateWrapper = $('.translate');
    if ($(translateWrapper).length < 1) return;
    $(translateWrapper).css({ 'display': 'block' });

    //Open up translate menu
    var translate = $('.gettranslatemenu');
    $(translate).click(function() {
        toggleFlash();
        $('.lang').parent().parent().slideDown("fast");
    });

    // get clicked language
    var selectedLanguage = '';
    var langItem = $('a[name=lang]').click(function(e) {
        e.preventDefault();
        $(this).blur();
        selectedLanguage = $(this);
    });

    // language menu items
    $('.lang').click(function() {
        toggleFlash();
        $('.lang').parent().parent().slideUp("fast", function() {
            // call google translate function and pass through clicked language
            initTranslate(selectedLanguage);
        });
    });

    // close button
    $('.close').click(function() {
        toggleFlash();
        $('.lang').parent().parent().slideUp("fast");
    });
}
/* GOOGLE TRANSLATE CONTENT
----------------------------------------------------------------------*/
var initTranslate = function(lang) {
    // show disclaimer only if it is not yet added
    if ($('.error').length < 1) $('#centercol').prepend('<div class="error">Denna sida är översatt med Google translate. Fel kan förekomma.</div>');
    // get laguage code from clicked link
    var language = lang.parent().attr('rel');
    // translate content
    $('#centercol').translate(language, {
        start: function() {
            $('.translate .visible .gettranslatemenu').after('<img src="/Templates/Styles/gfx/loading.gif" class="loading" alt="" />');
        },
        complete: function() {
            $('.translate .visible img').remove();
        }
    });
    //translate disclaimer
    $('.error').translate(language);
}

var Twitter = {
    init: function() {
        if (window.location.href.indexOf('/en') == -1) {
            var items = $('#newsflow .twitteruser');
            var current, currentUser, previousUser, div;

            var url = window.location.href;
            var msg = 'Visa fler Twitter-uppdateringar';

            if (url.indexOf('/en') > -1) msg = 'Show more Twitter updates';

            items.each(function(i) {
                current = $(items[i]);
                currentUser = $(items[i]).text();
                if (i > 0) previousUser = $(items[i - 1]).text();
                Console.Info(current);
                if (currentUser == previousUser) {
                    div = current.parent().parent();
                    var prevDiv = div.prev();

                    if (prevDiv.hasClass('twitter')) div.addClass('hidden');

                    if (!prevDiv.hasClass('hidden') && prevDiv.hasClass('twitter') && !prevDiv.find('a.toggler').length) prevDiv.append('<a onclick=\"Twitter.toggle(\'t' + i + '\')\" id=\"t' + i + '\" class=\"expand toggler\">' + msg + '</a>');
                }
            });
        } 
    },
    clear: function() {
        var items = $('#newsflow .twitteruser');
        var current;

        items.each(function(i) {
            current = $(items[i]);
            div = current.parent().parent();
            $(div.find('.toggler')).remove();
            div.removeClass('hidden');
        });
    },
    toggle: function(elm) {
        elm = $('#' + elm);

        var url = window.location.href;
        var msg = 'Visa fler Twitter-uppdateringar';
        var msgExpanded = 'Visa färre Twitter-uppdateringar';

        if (url.indexOf('/en') > -1) {
            msg = 'Show more Twitter updates';
            msgExpanded = 'Show fewer Twitter updates';
        }

        if (elm.hasClass('expand')) {
            elm.removeClass('expand');
            elm.addClass('minimize');
            elm.text(msgExpanded);
        }
        else {
            elm.removeClass('minimize');
            elm.addClass('expand');
            elm.text(msg);
        }

        var firstDiv = elm.parent();
        var sib = firstDiv.nextAll('.twitter');
        var current, currentUser, currentSibUser, previousSibUser;
        currentUser = firstDiv.find('.twitteruser').text();

        sib.each(function(i) {
            current = $(sib[i]);
            if (i > -1) currentSibUser = current.find('.twitteruser').text();
            if (current.hasClass('hidden') && (currentSibUser == currentUser)) {
                current.toggle('fast');
            } else {
                return false;
            }
        });
    }
};


function parseXml(xml) {
    if (jQuery.browser.msie) {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.loadXML(xml);
        xml = xmlDoc;
    }
    return xml;
}


/* Open specific links in new window */
var LnkTarget = {
	init: function(att, val) {
		if (document.getElementById && document.createElement && document.appendChild) {
			var strAtt = ((typeof att == 'undefined') || (att == null)) ? 'class' : att;
			var strVal = ((typeof val == 'undefined') || (val == null)) ? 'newwindow' : val;
			var arrLinks = document.getElementsByTagName('a');
			var oLink;
			var oRegExp = new RegExp("(^|\\s)" + strVal + "(\\s|$)");
			for (var i = 0; i < arrLinks.length; i++) {
				oLink = arrLinks[i];
				if ((strAtt == 'class') && (oRegExp.test(oLink.className)) || (oRegExp.test(oLink.getAttribute(strAtt)))) {
					oLink.onclick = LnkTarget.openWin;
				}
			}
		}
	},
	openWin: function(e) {
		var event = (!e) ? window.event : e;
		if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
		else {
			var oWin = window.open(this.getAttribute('href'), '_blank');
			if (oWin) {
				if (oWin.focus) oWin.focus();
				return false;
			}
			oWin = null;
			return true;
		}
	}
};


/* LOAD MORE NEWS "PAGINATION"
----------------------------------------------------------------------*/
var initLoadMoreNews = function() {
	$('a[name=morenews]').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		//$('a[name=morenews]').attr('href', '#more');

		$(".morenews").before('<div class="morenewsitems"></div>');
		// add loading spinner
		$(".morenews").after('<img src="/Templates/Styles/gfx/loading-more-news-transparent.gif" class="loading" alt="" />');

		//get all .morenewsitems
		var moreItemsArray = $(".morenewsitems");


		var currentNewsflow = $('.mediatypes').find('.selected').children().attr('class');

		var offset = $('#newsflow').find('.' + currentNewsflow).length;

		var url = window.location.href;
		var lang = 'sv';

		if (url.indexOf('/en') > -1) lang = 'en';

		$.ajax({
			type: 'POST',
			url: '/Templates/Services/News.asmx/GetNewsListingItems',
			cache: false,
			data: "{'offset':'" + offset + "','media':'" + currentNewsflow + "','language':'" + lang + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: 'html',
			error: function() {
				alert("Ooops! Something went wrong when retrieving more news items.");
			},
			complete: function() {
				// remove loading spinner
			$("#newsflow img.loading").remove();
			if (currentNewsflow != 'blogs') Twitter.init();
			},
			success: function(xml) {

				$(moreItemsArray[moreItemsArray.length - 1]).append($(xml));
				// apply effect only on the last created class, .morenewsitems
				$(moreItemsArray[moreItemsArray.length - 1]).css('display', 'none').fadeIn();
				// if shortcut nav exist
				if ($('#newslistshortcut').length > 0) {
					// remove it
					$('#newslistshortcut').remove();
				}
				// then add it to its new location
				$(moreItemsArray[moreItemsArray.length - 1]).before('<ul id="newslistshortcut"><li class="pagedown"><a name="pagedown" href="#" title="Go to bottom of page"><span>Bottom</span></a></li><li class="pageup"><a name="pageup" href="#" title="Go to top of page"><span>Top</span></a></li></ul>');
				$('#newslistshortcut').css('display', 'none').fadeIn('slow');
				// scroll to top
				$('a[name=pageup]').click(function(e) {
					//Cancel the link behavior
					e.preventDefault();
					$('html,body').animate({ scrollTop: 0 }, 500);
				});
				// scroll to bottom
				$('a[name=pagedown]').click(function(e) {
					//Cancel the link behavior
					e.preventDefault();
					$('html,body').animate({ scrollTop: $(document).height() }, 500);
				});
			}
		});
	});
}

var Console = function() {
	return {
		Log: function(msg, args) { if (typeof console == 'undefined') return false; if (!args) args = ''; console.log(msg, args) },
		Info: function(msg, args) { if (typeof console == 'undefined') return false; if (!args) args = ''; console.info(msg, args) },
		Warn: function(msg, args) { if (typeof console == 'undefined') return false; if (!args) args = ''; console.warn(msg, args) },
		Error: function(msg, args) { if (typeof console == 'undefined') return false; if (!args) args = ''; console.error(msg, args) }
	}
} ();
