﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

var overSerpHeader; // Set in HeaderSearch.aspx
var contactPageUrlSv; // Set in ToolHeader.ascx.cs
var contactPageUrlEn; // Set in ToolHeader.ascx.cs
var currentLanguage; // Set in ToolHeader.ascx.cs

var SYS = {};
var TEMPLATES = {};
var FUNCTION = {};
var LANG = {};

/* EVENTHANDLER FOR DOMONLOAD
 ADD FUNCTIONS THAT SHOULD RUN ON DOM LOAD
----------------------------------------------------*/
$(document).ready(function () {
    //##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>##

    SYS.Init();
    LANG.Init();
    TEMPLATES.Init();

    $('#tools').InitTools();
    $('#primary-header li').InitMainDropMenu();
    $('fieldset').not('#order-report').TextfieldPlaceholders();
    $('#content.wide article.n1 li').not('#content.serp article.n1 li').InitInfoBoxes();
    $('#photos').InitImageCarousel();
    $('.financial-table').InitFinancialTable();
    $('.linkslider').InitLinkSlider();
    $('.linkslider .nav').LinkSlide();
    $('.link.show-more').ShowMore();
    $('.mailto').Obfuscate();

    $('body').InitFeedbackForm();

    $('body').bind('click', function () {
        if ($('#serp-header').size() > 0 && !overSerpHeader) {
            $('#search2').val('').trigger('blur');
            $('#serp-header').slideUp('fast').remove();
            $('#tool-header').slideUp('slow');

            $('.tab').find('a').removeClass('up');
            $('.tab').find('a').addClass('down');

            if (!overSerpHeader) {
                return false;
            }
        }
    });

    //##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>##

    initializeAddThis();

    setupPressReleaseFiltering();
    FUNCTION.RestyleTables();
    FUNCTION.FormRewrite();
    FUNCTION.SimpleFinancialTables();
    FUNCTION.TableHeaderScroll();
    FUNCTION.Tooltip();
    FUNCTION.Modal();
    FUNCTION.Promo();

    $('body').CampaignFlag();
});

/**
* Instace method: Init
* System settings
*/
SYS.Init = function () {
    this.$body = $('body');
    this.pageId = this.$body.attr('id');
    this.winWidth = $(window).width();
    this.winHeight = $(window).height();
    this.docHeight = $(document).height();
    this.scrollTop = $(window).scrollTop();
    this.lang = $('html').attr('lang');
    this.isBrowserIE = $.browser.msie;
    this.browserVersion = $.browser.version;

    // Used to pass into window timer function for executing local object calls 
    this.$tmrObject;

    $(window).bind('resize', function () {
        //$.fn.ImageResize();

        SYS.winWidth = $(window).width();
        SYS.winHeight = $(window).height();

        FUNCTION.ModalResize();
    });

    $(window).scroll(function () {
        SYS.scrollTop = $(window).scrollTop();
        FUNCTION.ModalScroll();
    });

    // SERP Endless Scroll
    if (this.pageId === 'serp-page') {
        this.SearchNextPage = $('#next-page').val();
        this.SearchPostsPerPage = $('#posts-per-page').val();

        FUNCTION.SearchPage.Init();
    }
};

/**
* Instace method: Init
* Script language settings
*/
LANG.Init = function () {

	if (SYS.lang === 'sv') {
		this.translations =
		{
			"forms":
			{
				"formGenericValidationErrorMessage": "Detta fält får inte vara tomt."
			},
			"orderReportMessage":
			{
				"orderSent": "Klart! Rapporten är på väg med posten.", "orderNotSent": "Oj, tyvärr gick något fel. Var vänlig och försök igen."
			}
		}
	} else {
		this.translations =
		{
			"forms":
			{
				"formGenericValidationErrorMessage": "This field must not be empty."
			},
			"orderReportMessage":
			{
				"orderSent": "Done! The report is in the mail.", "orderNotSent": "Oops, something went wrong. Please try again."
			}
		}
	}
};

TEMPLATES.Init = function () {
	if (SYS.pageId === 'serp-page') {
		this.serpListTemplate = '<li><a href="${Url}"><dl><dd><h4>${Title}</h4>${Description}<p class="publishdate">${Footer}</p></dd></dl></a></li>';
	}
};

/**
* Class method: Modal
* Description: Modal popup and transparent site covering layer
*				<span data-modal="iframe" data-modal-content="[Source link]"></span>				
*				<span data-modal="html-ajax" data-modal-content="[Client Content ID]"></span>
*				<span data-modal="json-ajax" data-modal-content="[Web Service ID]"></span>
*				<span data-modal="order-form" />
*/
FUNCTION.Modal = function () {
    var $fade = '',
		$modal = '',
		dataModal,
		href,
		$orderForm,
		$orderFormClone,
		hasOrderForm;
    //$('[name="modal"]').bind('click', function () {
    $('[data-modal]').bind('click', function (e) {
        e.preventDefault();
        dataModal = $(this).attr('data-modal');
        SYS.$body.append('<div id="fade" /><div id="modal"><span class="close"></span></div>');
        $fade = $('#fade').css({
            width: SYS.winWidth,
            height: SYS.docHeight,
            opacity: 0.7
        });
        $modal = $('#modal');
        $modal.attr('data-modal', dataModal);
        if (dataModal === 'iframe') {
            $modal.css({
                width: '600px',
                height: SYS.winHeight - 80 + 'px',
                top: 20 + 'px'
            });
            $modal.append('<iframe src="http://web1.mwtalent.com/i004/kungsleden/se/login.aspx" width="100%" height="100%" title="Jobbsök" scrolling="auto" id="jobbsearch" frameborder=0></iframe>');
        } else if (dataModal === 'html-ajax') {
            href = $(this).attr('href');
            $.ajax({
                type: "GET",
                url: href,
                data: "{'lang':'" + SYS.lang + "'}",
                contentType: 'application/html; charset=utf-8',
                dataType: 'html',
                beforeSend: function () { },

                error: function () { },

                success: function (html) {
                    $modal.css({
                        width: '600px',
                        height: SYS.winHeight - 80 + 'px'
                    });
                    $modal.append(html);
                }
            });
        } else if (dataModal === 'order-report') {
            var reportName = $(this).attr('data-reportname');
            $orderForm = $('#order-report');
            if (!hasOrderForm) {
                $orderFormClone = $orderForm.clone();
                hasOrderForm = true;
            }
            $orderFormClone.appendTo($modal).show();
            $modal.find('#report-name').text(reportName);
            $modal.css({
                top: SYS.scrollTop + SYS.winHeight / 2 - $modal.height() / 2,
                width: '300px'
            });
               FUNCTION.OrderForm($(this).attr('data-reportid'));
        }
        $modal.css({
            left: SYS.winWidth / 2 - $modal.width() / 2 + 'px'
        });
        $fade.one('click', function () {
            $(this).remove();
            $modal.remove();
        });
        $modal.find('.close').one('click', function () {
            $fade.remove();
            $modal.remove();
        });
    });
};

/**
* Class method: ModalResize
* Description: Modal popup and transparent site covering layer update
*/
FUNCTION.ModalResize = function () {
	var $fade = $('#fade'),
		$modal = $('#modal');

	if ($fade.length === 0) { return false; }
	
	$fade.css({
		width: SYS.winWidth,
		height: SYS.docHeight
	});
	if ($modal.attr('data-modal') === 'iframe') {
		$modal.css({
			height: SYS.winHeight - 80 + 'px'
		});
	} else {
		$modal.css({
			top: SYS.scrollTop + SYS.winHeight / 2 - $modal.height() / 2
		});
	}
	$modal.css({
		left: SYS.winWidth / 2 - $modal.width() / 2 + 'px'
	});
};

/**
* Class method: ModalResize
* Description: Modal popup and transparent site covering layer update
*/
FUNCTION.ModalScroll = function () {
	var $modal = $('#modal');

	if ($modal.length === 0) { return false; }

	if ($modal.attr('data-modal') !== 'iframe') {
		$modal.css({
			top: SYS.scrollTop + SYS.winHeight / 2 - $modal.height() / 2
		});
	}
};

/**
* Class method: OrderForm
* Description: Order financial reports and presentations
*/
FUNCTION.OrderForm = function (reportPageId) {
	var $orderForm = $('#modal fieldset'),
		$orderBtn = $orderForm.find('button'),
		$progressBoard,
		badInput,
		tmr;

    $orderBtn.unbind('click');

    $orderBtn.bind('click', function (e) {
        e.preventDefault();
        badInput = false;
        $orderForm.find('.error').remove();
        $orderForm.find('input.mandatory').each(function (i, elm) {
            if ($(elm).val() == '') {
                $(elm).before('<span class="error">' + LANG.translations.forms.formGenericValidationErrorMessage + '</span>');
                badInput = true;
            }
        });
        if (!badInput) {
            SYS.$tmrObject = $orderForm;
            $progressBoard = $('<div class="loading" />');
            $.ajax({
                type: "POST",
                url: '/Services/FinancialReportOrderService.asmx/OrderReport',
                data: "{'name':'" + $orderForm.find('#name').val() + "', 'streetAddress':'" + $orderForm.find('#street-address').val() + "', 'zipCode':'" + $orderForm.find('#zip').val() + "', 'city':'" + $orderForm.find('#city').val() + "', 'country':'" + $orderForm.find('#country').val() + "', 'language':'" + SYS.lang + "', 'reportPageId':" + parseInt(reportPageId) + "}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                beforeSend: function () {
                    $orderForm.append($progressBoard);
                },
                error: function () {
                    $progressBoard.removeClass('loading');
                    $progressBoard.addClass('error');
                    $progressBoard.append('<span>' + LANG.translations.orderReportMessage.orderNotSent + '</span>');
                    tmr = setTimeout("SYS.$tmrObject.find('div').remove();", 3000);
                },
                success: function (response) {
                    $progressBoard.removeClass('loading');
                    if (response.d) {
                        $progressBoard.addClass('pass');
                        $progressBoard.append('<span>' + LANG.translations.orderReportMessage.orderSent + '</span>');
                        tmr = setTimeout("SYS.$tmrObject.find('div').remove();SYS.$tmrObject.parent().find('.close').trigger('click');", 3000);
                    } else {
                        $progressBoard.addClass('error');
                        $progressBoard.append('<span>' + LANG.translations.orderReportMessage.orderNotSent + '</span>');
                        tmr = setTimeout("SYS.$tmrObject.find('div').remove();", 3000);
                    }
                }
            });
        } else {
            return false;
        }
    });
};

/**
* Class method: ValidateForm
* Description: 
*/
FUNCTION.ValidateForm = function ($input) {
	var badInput = false;
	$input.each(function (i, elm) {
		if ($(elm).id == 'zip') {
			if (!FUNCTION.ValidateZip($(elm).val())) {
				$(elm).prepend('<div>Detta fält får inte </div>');
			}
		} else {
			if (!FUNCTION.ValidateString($(elm).val())) {
				$(elm).prepend('<div>Detta fält får inte </div>');
			}
		}
	});
};

/**
* Class method: ValidateName
* Description: 
*/
FUNCTION.ValidateString = function (string) { 
	var regEx = /^[a-zA-Z|\s|-]+$/;
	var	match = string.match(regEx);
	if(match === null) {
		return false;
	} else {
		return true;
	}
};

/**
* Class method: ValidateName
* Description: 
*/
FUNCTION.ValidateZip = function (string) {
	var regEx = /^[0-9|\s|-]+$/;
	var match = string.match(regEx);
	if (match === null) {
		return false;
	} else {
		return true;
	}
};


/**
* Class method: FormRewrite
* Description: Custom form elements
*/
FUNCTION.FormRewrite = function () {

	var $selects = SYS.$body.find('select'),
		$selectDrop,
		$allSelectDrop,
		$options,
		$selectOpen,
		selectOffset;

	if ($selects.length === 0) { return false; }

	// <select />
	$selects.each(function (i, elm) {

		// Create a nested ul li that match the select
		$selectDrop = $('<ul class="select"><li><span></span><ul /></li>');
		$options = $(elm).find('option');
		$options.each(function (j, opt) {
			// Make the selected option the default value in the list
			if ($(opt).attr('selected')) {
				$selectDrop.find('span').append($(opt).text());
			}
			$selectDrop.find('ul').append('<li>' + $(opt).text() + '</li>');
		});

		// Click open drop down
		$selectOpen = $selectDrop.find('span');
		$selectOpen.bind('click', function (e) {
			e.stopPropagation();
			$allSelectDrop.each(function (k, elm) {
				if ($(this).next().is(':hidden')) {
					$(elm).hide();
				}
				FUNCTION.FormDropIe($(elm));
			});
			$(this).next().toggle();

			selectOffset = $(this).offset().top + $(this).height() + $(this).next().height() + 20 - SYS.scrollTop;
			// If drop down goes beyonnd the browser bottom, correct drop down position so it doesn't
			if (selectOffset > SYS.winHeight) {
				$(this).next().css({ 'margin-top': (selectOffset - SYS.winHeight) * -1 + 'px' });
			} else {
				$(this).next().css({ 'margin-top': 0 });
			}
			FUNCTION.FormDropIe($(this));
		});

		$selectDrop.find('ul li:first').addClass('first');

		// select value from drop down and make the corresponding option selected
		$selectDrop.find('ul li').bind('click', function () {
			$(this).parent().prev().text($(this).text());
			$(this).closest('ul.select').next().find('option').eq($(this).prevAll().length).attr('selected', 'selected');
			$(this).parent().toggle();
			$(elm).trigger('change');
			FUNCTION.FormDropIe($(this).parent());
		});

		$(elm).focus(function () {
			$(this).prev().find('li').not('li li').toggleClass('hover');
		}).blur(function () {
			$(this).prev().find('li').not('li li').toggleClass('hover');
		});

		// add custom select
		$(elm).before($selectDrop);
		// hide native select
		$(elm).css({
			position: 'absolute',
			left: '-9999em',
			opacity: 0
		});

	});

	// cache all drops
	$allSelectDrop = $selects.prev().find('ul');

	// close all open drops when scrolling window
	$(window).scroll(function () {
		$allSelectDrop.each(function (i, elm) {
			if ($(elm).is(':visible')) {
				$(elm).hide();
			}
		});
	});
	// close any open drop if clicking outside of it
	$(document).bind('click', function () {
		$allSelectDrop.each(function (i, elm) {
			if ($(elm).is(':visible')) {
				$(elm).hide();
				FUNCTION.FormDropIe($(elm));
			}
		});
	});
};

/**
* Class method: FormDropIe
* Description: This fixes the IE7 bug where the parent need a higher z-index value then the element itself. Used in all browsers anyway.
*/
FUNCTION.FormDropIe = function (obj) {
	obj.next().is(':visible') ? obj.parent().css({ 'z-index': '1000', 'position': 'relative' }) : obj.parent().css({ 'z-index': 'inherit', 'position': 'static' });
};


FUNCTION.SimpleFinancialTables = function () {

	var $wrapper = $('#simplefinancialtables');
	var $select = $wrapper.find('select');
	var $options = $select.find('option');
	var $tables = $wrapper.find('table');
	var pos = 0;

	$tables.not(':eq(0)').hide();

	$select.bind('change', function () {

		pos = $(this).parent().find('option[value=' + $(this).attr('value') + ']').prevAll().length;

		$tables.hide();
		$tables.eq(pos).show();

		return false;
	});
};

/**
* Class method: TableHeaderScroll
* Description: When scrolling a page with a large table body, make the table header stay fixed on page.
*/
FUNCTION.TableHeaderScroll = function () {
	var $scrollTables = $('.scroll-table'),
		$thead,
		$tbody,
		$clone,
		clone,
		offset;

	if ($scrollTables.length === 0 || (SYS.isBrowserIE && SYS.browserVersion == 7)) { return false; }

	$scrollTables.each(function (i, table) {
		$thead = $(table).find('thead');
		$clone = $thead.clone();
		clone = false;
		offset = $thead.offset();
		$(table).prepend($clone);
		$thead.find('td').each(function (j, td) {
			$clone.find('td').eq(j).css({ width: $(td).width() + 'px' });
		});
		$clone.css({ top: 0 }).addClass('hide');
		$(window).scroll(function () {
			if (offset.top + 20 < SYS.scrollTop) {
				if (clone === false) {
					$clone.css({
						position: 'fixed',
						display: 'block',
						width: $thead.width() + 'px !important'
					});
					clone = true;
				}
			} else if (offset.top + $thead.height() > SYS.scrollTop) {
				$clone.fadeOut();
				clone = false;
			}
		});
	});
};

/**
* Class method: Tooltip
* Description: Custom tooltip
*/
FUNCTION.Tooltip = function () {

	var $tooltip = $('.tooltip'),
		$tip = $('<span id="tooltip"></span>'),
		title,
		offset;

	if ($tooltip.length === 0) { return false; }

	$tooltip.mouseover(function () {
		offset = $(this).offset();
		title = $(this).attr('title');
		SYS.$body.append($tip.text(title));
		$(this).attr('title', '');
		$tip.css({
			top: offset.top + 20 + 'px',
			left: offset.left + 'px'
		});
	}).mouseout(function () {
		$(this).attr('title', title);
		$tip.remove();
	});

};

/**
* Class method: Promo
* Description: Promotional area
*/
FUNCTION.Promo = function () {
	var $promoArea = $('#promo'),
		$promoItems = $promoArea.find('.promo'),
		$text,
		$heading;


	if ($promoArea.length === 0) { return false; };

	$promoItems.each(function (i, elm) {
		$text = $(elm).find('p');
		$heading = $(elm).find('h2');
		$text.css({ width: $heading.innerWidth() - 20 + 'px' });
		$text.css({ top: $heading.position().top - $text.innerHeight() + 'px' });
	});

	$promoItems.bind('mouseover', function () {
		$(this).find('p').fadeIn(200);
	}).bind('mouseleave', function () {
		$(this).find('p').fadeOut(200);
	});

};

/* Add This settings */
var addthis_share =
{
    templates: { twitter: '{{title}}: {{url}} (via @kungsleden)' }
}

var addthis_config =
{
    ui_use_css: true,
    ui_click: true,
   // ui_cobrand: 'Kungsleden', This one removes close X, confusing when combined with ui_click=true
    services_compact: 'facebook,twitter,delicious,digg,pusha,wordpress,tumblr,blogger,print,favorites,email',
    services_expanded: ''
}

/* Initialize AddThis popup menu */

function initializeAddThis() {
    try
    {
        addthis.button('.addthis-button');
    }
    catch(err) {
       
    }
}

(function ($) {
    $.fn.Obfuscate = function () {
        $(this).each(function (i, elm) {
            var email = $(this).attr('href');

			var obfuscated = $.rotate13(email);
            var txt = $(this).text();

            if (txt.charAt(0) == '+') {
                $(this).text($.rotate13(txt.substr(1)));
            }
			
            $(this).attr('href', obfuscated);

        });
    };
})(jQuery);

/* Financialtable
----------------------------------------------------*/
(function ($) {
    $.fn.InitFinancialTable = function () {
        $(this).each(function () {
            var table = $(this);
            //table.find('tbody th span').css('width', 245);
            var width = table.width();
            $('.financial-table-wrapper').css('width',parseInt(width + 200));
        });
    };
})(jQuery);

/* Show more-link */
(function ($) {
    $.fn.ShowMore = function () {
        $(this).each(function () {
            $(this).bind('click', function () {
                $(this).parents().find('.hidden').toggle();  
                $(this).parents().find('.link.show-more').toggle();
            });   
        });
    };
})(jQuery);

(function ($) {
    $.fn.HeaderSearch = function () {
        if ($(this).val().length > 1) {
            var query = Url.encode($(this).val());
            $.ajax({
                url: '/Templates/ClientContent/HeaderSearch.aspx?q=' + query + '&lang=' + currentLanguage,
                success: function (data) {
                    var exists = $('#serp-header').size() > 0;
                    if (!exists) {
                        $(data).prependTo('#page').hide().slideDown();
                    } else {
                        $('#serp-header').html($(data).find('.wrap'));
                    }
                },
                beforeSend: function () {
                    $('#toolsloader').show();
                },
                complete: function () {
                    $('#toolsloader').hide();
                }

            });
        } else {
            $('#serp-header').slideUp().remove();
        }
    };
})(jQuery);

/* Linkslider
----------------------------------------------------*/
(function ($) {
    $.fn.InitLinkSlider = function () {
        $(this).each(function () {

            //IE fix TODO make each
            $(this).find('.items ul li').css('width',$(this).find('.items ul li img').width());

            //Calculate and set width of ul.
            var totalWidth = 0;
            var maxWidth= 0;
            var maxHeight = 0;

            $(this).find('li').each(function() {
                totalWidth = totalWidth + $(this).outerWidth();
                
                if(maxHeight < $(this).height())
                    maxHeight = $(this).height();
            });
            $ul = $(this).find('.items ul');
            $ul.css('width', totalWidth);
            $ul.css('height', maxHeight);
           
           //Calculate and set width of wrapper.
            wrapperWidth = $(this).width() - $(this).find('.prev').width() - $(this).find('.next').width();
            $wrapper = $(this).find('.items');
            $wrapper.css('width', wrapperWidth);
            $wrapper.css('height', maxHeight);  
        });
    };
})(jQuery);

(function ($) {
    $.fn.LinkSlide = function () {
        $(this).each(function () {
            $(this).bind('click', function () {
                $ul = $(this).parent().find('ul');
                $liWidth = $ul.find('li').first().outerWidth();
                
                //Get old margin
                if($ul.css('margin-left').indexOf('px') > 0)
                    $oldMargin = parseInt($ul.css('margin-left').substring(0,$ul.css('margin-left').indexOf('px')));
                else
                    $oldMargin = parseInt($ul.css('margin-left'));
                //Calculate new margin
                $newMargin = 0;
                if($(this).hasClass('prev')){
                    $newMargin = $oldMargin + $liWidth;
                    if ($newMargin > 0)
                        $newMargin = 0;
                }
                else if($(this).hasClass('next')){
                    $newMargin = $oldMargin - $liWidth;
                    $wrapper = $(this).closest('.linkslider').find('.items');      
                    $limit = -1 * ($ul.width()-$wrapper.width());
                    if ($newMargin < ($limit - $liWidth))
                        $newMargin = $oldMargin;
                }
                //Animate change
                $ul.animate({marginLeft: $newMargin + "px"}, 500, function() {});
                return false;
            });
        });
    };
})(jQuery);

/* INIT TOOLS
----------------------------------------------------*/
(function($) {
    $.fn.InitTools = function() {
        var tools = $(this);

        $('.searchform #search2').bind('keydown', function(e) {
            if(e.keyCode==13)
            {
                if(currentLanguage=='sv')
                {
                    window.location= contactPageUrlSv + "?q=" + $('#search2').val();
                }
                else
                {
                    window.location= contactPageUrlEn + "?q=" + $('#search2').val();
                }
            }
        });

        $('.searchform #search2').bind('keyup', function(e) {
            $(this).HeaderSearch();
        });

        tools.find('.tab').bind('click', function() {
            
                if ($('#tool-header').css('display') == 'none') {
                    $(this).find('a').removeClass('down');
                    $(this).find('a').addClass('up');
                    $('#tool-header').slideDown('slow');
                    $('#search2').val('').trigger('blur').trigger('focus');
                } else {
                    $(this).find('a').removeClass('up');
                    $(this).find('a').addClass('down');
                    $('#tool-header').slideUp('slow');
                    $('#search2').val('').trigger('blur');
                }
            
            return false;
        });
    };
})(jQuery);

/* INIT INFO BOXES
----------------------------------------------------*/
(function($) {
    $.fn.InitInfoBoxes = function() {
        this.each(function() {
            var box = $(this);
            box.find('a').not(':first').hide();
            box.bind('mouseenter', function() {
                $(this).addClass('active');
                box.find('a').fadeIn('fast');
            }).bind('mouseleave', function() {
                    $(this).removeClass('active');
                    box.find('a').not(':first').fadeOut('fast');
            });
        });
    };
})(jQuery);

/**
* Class method: CampaignFlag
* Description:
*/
(function($) {
    $.fn.CampaignFlag = function() {
        var enabled = $('#campaign-1-enabled');
        if(!enabled.length) {
            return;
        }
        var animation = $('#campaign-1-startpage');
        
        
        
        var $flag = $('<img src="/static/gfx/jakten-flag.png" id="campaign-flag" alt="">'),
            $button = $('<img src="/static/gfx/btn-jakten-2.png" id="campaign-button" alt="">'),$form,
            url;

        $flag.css({ top: SYS.winHeight / 2 - 115 + 'px' });
        $button.css({ top: SYS.winHeight / 2 - 165 + 'px' });
        if(animation.length) {
            $(this).append($flag);
            $('#campaign-flag').bind('click', function() {
                $('#campaign-form').animate({ opacity: 'toggle' });
            });
        }
        
        $(this).append($button);

        var text = $('<div />');
        text.append('<p><textarea id="campaign-text" cols="65" rows="6"></textarea></p>');
        text.append('<h2>Berätta gärna vem du är.</h2><input type="text" id="campaign-from" size="35" /><p><input type="button" value="Skicka" id="campaign-send"><a href="'+$('#campaign-1-link').val()+'">Läs mer om Jakten på O</a></p>');
         var html = $('<div />').html(text);
            
        $form = $('<div id="campaign-form" style="display:none"><div class="form">' + $('<div/>').html($('#campaign-1-text').val()).text() + html.html() + '<span class="close"></span></div></div>');
        $form.css({ top: (SYS.winHeight / 2 - 200) + 'px', left: (SYS.winWidth / 2 - 300) + 'px' });
        $(this).append($form);

        //# SHOW/HIDE
        $('#campaign-button').bind('click', function() {
            if (typeof (_gat) == "object") {
                var tracker = _gat._createTracker("UA-17361037-1");
                tracker._trackEvent("Popups", "Jakten på O", "Öppna", 1);
            }

            $('#campaign-form').animate({ opacity: 'toggle' });
        });
        $('#campaign-form .close').bind('click', function() {
            $('#campaign-form').animate({ opacity: 'toggle' });
        });

        if(animation.length) {
            // Show the flag for 3 seconds, then the button
            $('#campaign-flag').css({ opacity: 0 }).delay(1500).animate({
                    marginRight: '+=100',
                    opacity: 1
                }, 1500, function() {
                    $('#campaign-flag').delay(3000).animate({
                            marginRight: '-=100',
                            opacity: 0
                        }, 1500, function() { });

                    $('#campaign-button').css({ opacity: 0 }).delay(3000).animate({
                            marginRight: '+=50',
                            opacity: 1
                        }, 1500, function() {
                        });
                });
        }
        else {
            $('#campaign-button').css('margin-right','-10px');
        }
        //# POST
        $('#campaign-send').bind('click', function() {
            if (typeof (_gat) == "object") {
                var tracker = _gat._createTracker("UA-17361037-1");
                tracker._trackEvent("Popups", "Jakten på O", "Skicka", 1);
            }

            $('#campaign-form').find('.form').fadeTo('fast', 0.13);
            $('#campaign-form').append('<div id="feedback-sending"><img src="/legacy/templates/images/ajax-loader.gif" alt=""></div>');
            var url = '/handlers/feedback.ashx?ref='+ escape(location.href.toString())+'&msg=' + Url.encode($('#campaign-text').val())+'&campaign=1&sender='+Url.encode($('#campaign-from').val());
            jQuery.get(url, campaignThankyou(status));
            return false;
        });

        //# RESIZE
        $(window).bind('resize', function() {
            var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
            $('#campaign-flag').css('top', (viewportHeight / 2) - 115);
            $('#campaign-button').css('top', (viewportHeight / 2) - 165);
            $form.css({ top: (SYS.winHeight / 2 - 165) + 'px', left: (SYS.winWidth / 2 - 300) + 'px' });
        });

    };
})(jQuery);

/* INIT FEEDBACK FORM
----------------------------------------------------*/
(function($) {
    $.fn.InitFeedbackForm = function() {
		var button;
        /*
        var tracker = _gat._getTracker("UA-17361037-1");
        tracker._initData();
        tracker._trackEvent("Popups", "Feedback", location.href.toString(), 1);
        */
		//SYS.lang == 'sv' ? : ;

        //# BUTTON
		SYS.lang == 'sv' ?  button = $('<img src="/legacy/templates/images/tycktill-button.png" id="feedback-button" alt="" />') : button = $('<img src="/legacy/templates/images/feedback-button.png" id="feedback-button" alt="" />');

       
        var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
        button.css('top', (viewportHeight / 2) );
        $(this).append(button);

        //# FORM
        var html = $('<div></div>');
        SYS.lang == 'sv' ? html.append('<h2>Tyck till</h2><p>Tyck till om webbplatsen.</p>') : html.append('<h2>Feedback</h2><p>Leave feedback about the website.</p>');
        html.append('<p><textarea id="feedback-text" cols="55" rows="8"></textarea></p>');

		SYS.lang == 'sv' ?  html.append('<p><input type="button" value="Skicka" id="feedback-send"></p>'):  html.append('<p><input type="button" value="Send" id="feedback-send"></p>');

        var form = $('<div id="feedback-form" style="display:none"><div class="form">' + html.html() + '<span class="close"></span></div></div>');
        form.css('top', (viewportHeight / 2) );
        $(this).append(form);

        //# SHOW/HIDE
        $('#feedback-button').bind('click', function() {
            $('#feedback-form').animate({ opacity: 'toggle' });
        });
		 $('#feedback-form .close').bind('click', function() {
            $('#feedback-form').animate({ opacity: 'toggle' });
        });

        //# POST
        $('#feedback-send').bind('click', function() {
            $('#feedback-form').find('.form').fadeTo('fast', 0.13);
            $('#feedback-form').append('<div id="feedback-sending"><img src="/legacy/templates/images/ajax-loader.gif" alt=""></div>');
            var url = '/handlers/feedback.ashx?ref='+ escape(location.href.toString())+'&msg=' + Url.encode($('#feedback-text').val());
            jQuery.get(url, feedbackThankyou(status));
            return false;
        });

        //# RESIZE
        $(window).bind('resize', function() {
            var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
            $('#feedback-button').css('top', (viewportHeight / 2) );
            $('#feedback-form').css('top', (viewportHeight / 2) );
        });

    };
})(jQuery);


/* FEEDBACKTHANKYOU
----------------------------------------------------*/
var feedbackThankyou = function(stat) {
    $('#feedback-sending').html('<h3>Tack f&ouml;r din feedback!</h3>');
    setTimeout('$("#feedback-form").animate({ opacity: "toggle" });', 3000);
    setTimeout('$("#feedback-form").find(".form").attr("style", "");', 4000);
    setTimeout('$("#feedback-sending").remove();', 4000);
    $('#feedback-text').val('');
};

/* FEEDBACKTHANKYOU
----------------------------------------------------*/
var campaignThankyou = function(stat) {
    $('#feedback-sending').html('<h3>Tack f&ouml;r din feedback!</h3>');
    setTimeout('$("#campaign-form").animate({ opacity: "toggle" });', 3000);
    setTimeout('$("#campaign-form").find(".form").attr("style", "");', 4000);
    setTimeout('$("#feedback-sending").remove();', 4000);
    $('#feedback-text').val('');
};

/* TOGGLE FADE
----------------------------------------------------*/
(function($) {
    $.fn.toggleFade = function(settings) {
        return this.animate({ opacity: 'toggle' });
    };
})(jQuery);


/* INIT MAIN DROPMENU
----------------------------------------------------*/
(function($) {
    $.fn.InitMainDropMenu = function() {
        var eventType = 'click';
        

        return this.each(function() {
            $(this).bind('click', function() {
                var li = $(this);
                $('#primary-header').find('li').removeClass('over');
                $('#portable-menu-structure').remove();
                li.addClass('over');

                if(li.hasClass('foldout')) {
                    var portableMenu = $('<div id="portable-menu-structure"><span id="close"></span></div>');
                    var structureId = li.find('a:first').attr('class');
                    var structureClone = $('#' + structureId).clone(true);
                    structureClone.addClass('structure-clone');

                    portableMenu.append(structureClone);
                    portableMenu.appendTo($('#page'));

                    var over = true;
                   // portableMenu.bind("mouseleave", function() {
                   

                    $('body, #close').one("click", function() {
                        
                        /*over = false;
                        if (li.data('events').mouseout === 'undefined') {
                            $('#primary-header').find('li').removeClass('over');
                            $('#portable-menu-structure').remove();
                        }
                        li.one("mouseout", function() {
                            over = true;
                            $('#primary-header').find('li').removeClass('over');
                            $('#portable-menu-structure').remove();
                        });
                        if (li.data('events').mouseover === 'undefined' && over === true) {
                    
                        } 
                        */
                        $('#primary-header').find('li').removeClass('over');
                        $('#portable-menu-structure').remove();
                    
                    });

                    //portableMenu.bind("click", function() {
                        //return false;
                    //});

                }

                return false;
            });
            /*
            $(this).find('a:first').bind('focus', function() {
                $('#primary-header').find('li').removeClass('over');
                $('#portable-menu-structure').remove();
                $(this).parent().addClass('over');
                if($(this).hasClass('foldout')) {
                    var portableMenu = $('<div id="portable-menu-structure"></div>');
                    var structureId = $(this).parent().find('a:first').attr('class');
                    var structureClone = $('#' + structureId).clone(true);
                    structureClone.addClass('structure-clone');
                }
                portableMenu.bind("mouseleave", function() {
                    $('#primary-header').find('li').removeClass('over');
                    $('#portable-menu-structure').remove();
                });


                if($(this).hasClass('foldout')) {
                    portableMenu.append(structureClone);
                    portableMenu.appendTo($('#page'));
                }
                return false;
            });
            */
        });
    };
})(jQuery);

/* MISC FUNCTIONS
----------------------------------------------------*/

FUNCTION.Number = function(cnt) {
    var number = cnt.toString().replace(/\D+/ig, '');
    var n = number;
    var s = n.toString();
    var x, i;
    if (s.length >= 4) {
        x = s.split(/\D/);
        i = x[0].length % 3 || 3;
        x[0] = s.slice(0, i + (n < 0)) + x[0].slice(i).replace(/(\d{3})/g, ' $1');
        s = x;
    }
    return s;
};

FUNCTION.RestyleTables = function () {

    var $tableParent = $('div#page .wrapper');
    if ($tableParent.length == 0) { return false; }
    var $tables = $tableParent.find('table.restyle-table');
    var $tableHeader = '';
    var text = '';

    $tables.each(function (i, table) {
        $tableHeader = $(table).find('thead');
        if ($tableHeader.length > 0) { return false; }

        $(table).find('tr:first').find('td').each(function (j, td) {
            text = $(td).text();
            $(td).replaceWith('<th>' + text + '</th>');
        });

        $(table).find('tbody tr:even').addClass('alt');
    });

};

/* Textfield Placeholders v1.2 - jQuery Plugin
* Copyright (c) 2009 Palle Zingmark
* Author: Palle Zingmark, www.palleman.nu
*         Philip Hofstetter, www.gnegg.ch
* Released with the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
(function ($) {
    $.fn.TextfieldPlaceholders = function () {
        var $hasNativeSupport = ('placeholder' in document.createElement('input'));
        return this.each(function () {
            var $parent = $(this);
            $parent.find('input:text[value=""],input:password[value=""]').each(function (i) {
                var $input = $(this);
                var $placeholder = $input.attr('placeholder');
                var $basecolors = ['#000000', 'rgb(0, 0, 0)'];
                var $color = $input.css('color');
                var $hascolor = jQuery.inArray($color, $basecolors);
                if (typeof $placeholder == 'undefined' || $placeholder == '') {
                    $placeholder = $parent.find('label[for="' + $input.attr('id') + '"]').text();
                }
                if (typeof $placeholder == 'string' || $placeholder != '') {
                    if ($hasNativeSupport) {
                        $input.attr('placeholder', $placeholder);
                        return;
                    }
                    if ($input.attr('type') == 'password') {
                        var $proxy = $('<input type="text" />');
                        var $original_input = $input;
                        $proxy.attr('class', $input.attr('class'));
                        $proxy.attr('style', $input.attr('style'));
                        $proxy.insertAfter($input);
                        $input.hide();
                        $input = $proxy;
                    }
                    $input.attr('value', $placeholder);
                    $input.attr('title', $placeholder);
                    if ($hascolor || $hascolor != -1) {
                        $input.css('color', '#aeaeae');
                    }
                    $input.bind('focus', function () {
                        if ($input.attr('value') == $input.attr('placeholder')) {
                            if ($original_input) {
                                $input.hide();
                                $original_input.show();
                                $input = $original_input;
                                $input.focus();
                            }
                            $input.attr('value', '');
                            $input.css('color', '#000000');
                        }
                    });
                    ($original_input || $input).bind('blur', function () {
                        if ($input.attr('value') == $input.attr('placeholder') || $input.attr('value') == '') {
                            if ($original_input) {
                                $original_input.hide();
                                $proxy.show();
                                $input = $proxy;
                            }
                            $input.attr('value', $input.attr('placeholder'));
                            if ($hascolor || $hascolor != -1) {
                                $input.css('color', '#aeaeae');
                            }
                        }
                    });
                }
            });
        });
    };
})(jQuery);


/* INIT IMAGE CAROUSEL
----------------------------------------------------*/
(function ($) {
    $.fn.InitImageCarousel = function () {
        
        var thumbSize = 5;
        var carouselWidth = 400;

        if($(this).hasClass("small")){
            thumbSize = 2;
            carouselWidth = 200;
        }

        var fullSize = $(this).find('#fullsize');
        var thumbs = $(this).find('#thumbs');

        thumbs.find('li').bind('click',function(){
            var thumbIndex = $(this).attr('id');
            if(fullSize.find('li').eq(thumbIndex).size() > 0){
                fullSize.find('li').hide();
                fullSize.find('li img').removeAttr('id');
                fullSize.find('li').eq(thumbIndex).find('img').attr('id','current-photo');
                
                fullSize.find('li').eq(thumbIndex).fadeIn('fast');
                //$.fn.ImageResize();
            }
        });

        fullSize.find('li').not(':first').hide();
        thumbs.find('li:gt('+ parseInt(thumbSize-1) +')').hide();

        if(thumbs.find('li').size() > thumbSize){

            /*thumbs.css('width',carouselWidth);*/
        
            var prev = $('<li class="prev"><a href="#"><img src="/legacy/templates/images/ico-carousel-left.png" style="width:10px;height:19px" alt=""></a></li>');
            var next = $('<li class="next"><a href="#"><img src="/legacy/templates/images/ico-carousel-right.png" style="width:10px;height:19px" alt=""></a></li>');

            thumbs.prepend(prev);
            thumbs.append(next);

            prev.bind('click',function(){
                if(!thumbs.find('li:visible:not(":first"):first').prev().hasClass('prev')){
                    thumbs.find('li:visible:not(":last"):last').hide();
                    thumbs.find('li:visible:not(":first"):first').prev().fadeIn('fast');
                }
                return false;
            });
            next.bind('click',function(){
                if(!thumbs.find('li:visible:not(":last"):last').next().hasClass('next')){
                    thumbs.find('li:visible:not(":first"):first').hide();
                    thumbs.find('li:visible:not(":last"):last').next().fadeIn('fast');
                }
                return false;
            });

        } else{
            //Set width of thumbnail ul
           /* nrOfImages = thumbs.find('li').length;
            thumbWidth = thumbs.find('li').outerWidth(true);
            thumbs.css('width',nrOfImages * thumbWidth);*/
        }
        //$.fn.ImageResize();
    };
})(jQuery);

(function ($) {
    $.fn.ImageResize = function () {

        width = $('#current-photo').width();
        height = $('#current-photo').height();
        ratio = width/height;

        boxWidth = $('#photos #fullsize').width();
        boxHeight = $('#photos #fullsize').height();
        boxRatio= boxWidth/boxHeight;

        //Portrait, fix on height, no zoom
        if(ratio <= 1){
            fixedRatio = height/boxHeight;
            $('#current-photo').css('height', boxHeight);
            newWidth = width/fixedRatio;
            $('#current-photo').css('width', newWidth);
            $('#current-photo').css('margin-top',0);
            $('#current-photo').css('margin-left', (boxWidth-newWidth)/2);
        }

        //More "landscape" than box, fix on height, zoom
        else if(ratio > boxRatio){
            currRatio = height/boxHeight;
            newWidth = width/currRatio;
            margin = (boxWidth - newWidth)/2;
            $('#current-photo').css('height', boxHeight);
            $('#current-photo').css('width', newWidth);
            $('#current-photo').css('margin-top',0);
            $('#current-photo').css('margin-left', margin + "px");
        }

        //Landscape, fix on width, zoom
        else{
            $('#current-photo').css('width', boxWidth);
            currRatio = width/boxWidth;
            newHeight = height/currRatio;
            $('#current-photo').css('height', newHeight);
            margin = (boxHeight - newHeight)/2;
            $('#current-photo').css('margin-left', 0);  
            $('#current-photo').css('margin-top', margin + "px");  
        }
    };
})(jQuery);

/* Google Translate
----------------------------------------------------*/
(function ($) {
    $.fn.GoogleTranslate = function () {
        return this.each(function() { 
            textHoldingElement = this;
        });
    };
})(jQuery);

/* URL ENCODE
----------------------------------------------------*/
var Url = {
    encode: function (string) {
        return escape(this._utf8_encode(string));
    },
    decode: function (string) {
        return this._utf8_decode(unescape(string));
    },
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
};

/* Press release filtering
----------------------------------------------------*/
function setupPressReleaseFiltering() {
    var listbox = $('#press-release-filter');

    if (listbox) {

		listbox.bind('change', function () {
		
            var category = listbox.val();

            if (category == '') {
                $('table.press-releases tbody tr').show();
            }
            else {
                $('table.press-releases tbody tr').not('tr.' + listbox.val()).hide();
                $('table.press-releases tbody tr.' + listbox.val()).show();
            }

            // Set CSS class for even/odd rows
            var rowCount = 0;
            $('table.press-releases tbody tr').each(function (index) {
                if ($(this).is(":visible")) {
                    if (rowCount % 2 == 0) {
                        $(this).addClass('odd');
                    }
                    else {
                        $(this).removeClass('odd');
                    }

                    rowCount++;
                }
            });
        });
    }
}

(function ($) {
    $.rotate = function (s) {
        return $.rotate13($.rotate5(s));
    }

    $.rotate5 = function (s) {
        var b = [], c, i = s.length, a = '0'.charCodeAt(), z = a + 10;
        while (i--) {
            c = s.charCodeAt(i);
            if (c >= a && c < z) { b[i] = String.fromCharCode(((c - a + 5) % (10)) + a); }
            else { b[i] = s.charAt(i); }
        }
        return b.join('');
    };

    $.rotate13 = function (s) {
	    if(s === null) {return '';}

        var b = [], c, i = s.length, a = 'a'.charCodeAt(), z = a + 26, A = 'A'.charCodeAt(), Z = A + 26;
        while (i--) {
            c = s.charCodeAt(i);
            if (c >= a && c < z) { b[i] = String.fromCharCode(((c - a + 13) % (26)) + a); }
            else if (c >= A && c < Z) { b[i] = String.fromCharCode(((c - A + 13) % (26)) + A); }
            else { b[i] = s.charAt(i); }
        }
        return b.join('');
    };
})(jQuery)


FUNCTION.SearchPage = {
    Init: function() {
        $('#pagination').hide();

        // If refreshing browser and scroll is not at top of page, scroll to top
		if (SYS.scrollTop != 0) {
			$('html,body').animate({ scrollTop: 0 }, 500);
		}

        this.prScrollCount = 0;
		this.$prTbody = $('#serp-complete-list'); // Get list items parent
		this.$prItems = FUNCTION.SearchPage.$prTbody.find('li'); // Get list items
		this.$prInputData;
		this.prServerItems = [];
		this.prResult;
		this.prOffset = 0; // Get last list item coordinates
		this.prOffsetScrollCount = 0;
		this.prUpdate = true; // It's possible to update the page
		this.prFirstUpdate = true;
		this.$prLoadMore = $('<button id="load-more-btn" class="btn btn-medium">Ladda fler</button>');

        if (SYS.SearchNextPage > 1) {
			FUNCTION.SearchPage.$prTbody.parent().after(FUNCTION.SearchPage.$prLoadMore);
		}
		FUNCTION.SearchPage.$prLoadMore.bind('click', function (e) {
			e.preventDefault();
			$(window).trigger('scroll', true);
		});

        FUNCTION.SearchPage.prOffset = FUNCTION.SearchPage.$prItems.last().offset();
        
        $(window).scroll(function (e, click) {
			// If item list ends outside the viewport 
			if (FUNCTION.SearchPage.prOffset.top > SYS.winHeight || click === true) {
			
				//  If it's possible to update the page
				if (FUNCTION.SearchPage.prUpdate === true) {
					// ... update scroll top coordinates
					SYS.scrollTop = $(window).scrollTop();
					// If the item list section appears in the viewport when scrolling down or if first list update hasn't been made...
					if (FUNCTION.SearchPage.prOffset.top - SYS.scrollTop < SYS.winHeight || FUNCTION.SearchPage.prFirstUpdate === true) {
						// It's NOT possible to update the page anymore
						FUNCTION.SearchPage.prUpdate = false;
						// If first update has been made, fade in latest addition of items (only 1+2n:th element)
						if (FUNCTION.SearchPage.prFirstUpdate === false || click != true) {
							FUNCTION.SearchPage.$prItems.animate({ opacity: 1 }, 2000);
						}
						// If the last page is not fetched
						if (SYS.SearchNextPage != -1) {
							FUNCTION.SearchPage.Fetch('scroll');
						}
					}
				}
			} else {
				return false;
			}
		});
    },
    Fetch: function(action, click) {
        var q = getURLParameter('q');

        $.ajax({
            type: 'POST',
            cache: false,
            data: '{ "query":"' + q + '","nextPageStr":"'+SYS.SearchNextPage+'","postsPerPageStr":"'+SYS.SearchPostsPerPage+'","languageBranch":"sv" }',
            url: '/services/Search.asmx/Query',
            contentType: "application/json; charset=utf-8",
			dataType: "json",
            success: function(data) {
			    // If the returned data is a string, objectify it
				FUNCTION.SearchPage.prResult = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
                SYS.SearchNextPage = FUNCTION.SearchPage.prResult.NextPage;

                FUNCTION.SearchPage.prServerItems = $.map(FUNCTION.SearchPage.prResult.Items, function(item, i) {
                    return {
                        Url: item.Url,
                        Title: item.Title,
                        Footer: item.Footer,
                        Description: item.Description
                    };
                });

                // Compile markup and call it "serpListTemplate"
				$.template('serpListTemplate', TEMPLATES.serpListTemplate);
				// Render the template with the building data and insert it into the table tbody
				FUNCTION.SearchPage.$prItems = $.tmpl('serpListTemplate', FUNCTION.SearchPage.prServerItems).appendTo(FUNCTION.SearchPage.$prTbody).css({
					opacity: 0
				});
            },
            complete: function() {
                if(FUNCTION.SearchPage.prFirstUpdate === true || action === 'search' || click === true) {
                    FUNCTION.SearchPage.$prItems.animate({ opacity: 1 }, 2000);
                }
                if ( action === 'search') {
					FUNCTION.SearchPage.prOffset = FUNCTION.SearchPage.$prItems.eq(FUNCTION.SearchPage.$prItems.length - 2).offset();
						
				} else {
					FUNCTION.SearchPage.prOffset = FUNCTION.SearchPage.$prItems.first().offset();
				}
				//  If load more button is present
				if (FUNCTION.SearchPage.$prLoadMore) {
					var $btnOffset = FUNCTION.SearchPage.$prLoadMore.offset();
					// If load more button is not visible and page can scroll
					if ($btnOffset.top - SYS.scrollTop > SYS.winHeight) {
						$offset = $btnOffset;
						// Hide load more button
						FUNCTION.SearchPage.$prLoadMore.hide();
					}
				}
				// When data fetch is complete, make it possible to update the page
				FUNCTION.SearchPage.prUpdate = true;
				// If first update has been made
				if (FUNCTION.SearchPage.prFirstUpdate === true) {
					FUNCTION.SearchPage.prFirstUpdate = false;
				}
            }
        });
    }
};


/*
* 

* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
*/
(function (jQuery, undefined) {
    var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,
		newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];

    function newTmplItem(options, parentItem, fn, data) {
        // Returns a template item data structure for a new rendered instance of a template (a 'template item').
        // The content field is a hierarchical array of strings and nested items (t	o be
        // removed and replaced by nodes field of dom elements, once inserted in DOM).
        var newItem = {
            data: data || (parentItem ? parentItem.data : {}),
            _wrap: parentItem ? parentItem._wrap : null,
            tmpl: null,
            parent: parentItem || null,
            nodes: [],
            calls: tiCalls,
            nest: tiNest,
            wrap: tiWrap,
            html: tiHtml,
            update: tiUpdate
        };
        if (options) {
            jQuery.extend(newItem, options, { nodes: [], parent: parentItem });
        }
        if (fn) {
            // Build the hierarchical content to be used during insertion into DOM
            newItem.tmpl = fn;
            newItem._ctnt = newItem._ctnt || newItem.tmpl(jQuery, newItem);
            newItem.key = ++itemKey;
            // Keep track of new template item, until it is stored as jQuery Data on DOM element
            (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem;
        }
        return newItem;
    }

    // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core).
    jQuery.each({
        appendTo: "append",
        prependTo: "prepend",
        insertBefore: "before",
        insertAfter: "after",
        replaceAll: "replaceWith"
    }, function (name, original) {
        jQuery.fn[name] = function (selector) {
            var ret = [], insert = jQuery(selector), elems, i, l, tmplItems,
				parent = this.length === 1 && this[0].parentNode;

            appendToTmplItems = newTmplItems || {};
            if (parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1) {
                insert[original](this[0]);
                ret = this;
            } else {
                for (i = 0, l = insert.length; i < l; i++) {
                    cloneIndex = i;
                    elems = (i > 0 ? this.clone(true) : this).get();
                    jQuery.fn[original].apply(jQuery(insert[i]), elems);
                    ret = ret.concat(elems);
                }
                cloneIndex = 0;
                ret = this.pushStack(ret, name, insert.selector);
            }
            tmplItems = appendToTmplItems;
            appendToTmplItems = null;
            jQuery.tmpl.complete(tmplItems);
            return ret;
        };
    });

    jQuery.fn.extend({
        // Use first wrapped element as template markup.
        // Return wrapped set of template items, obtained by rendering template against data.
        tmpl: function (data, options, parentItem) {
            return jQuery.tmpl(this[0], data, options, parentItem);
        },

        // Find which rendered template item the first wrapped DOM element belongs to
        tmplItem: function () {
            return jQuery.tmplItem(this[0]);
        },

        // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template.
        template: function (name) {
            return jQuery.template(name, this[0]);
        },

        domManip: function (args, table, callback, options) {
            // This appears to be a bug in the appendTo, etc. implementation
            // it should be doing .call() instead of .apply(). See #6227
            if (args[0] && args[0].nodeType) {
                var dmArgs = jQuery.makeArray(arguments), argsLength = args.length, i = 0, tmplItem;
                while (i < argsLength && !(tmplItem = jQuery.data(args[i++], "tmplItem"))) { }
                if (argsLength > 1) {
                    dmArgs[0] = [jQuery.makeArray(args)];
                }
                if (tmplItem && cloneIndex) {
                    dmArgs[2] = function (fragClone) {
                        // Handler called by oldManip when rendered template has been inserted into DOM.
                        jQuery.tmpl.afterManip(this, fragClone, callback);
                    };
                }
                oldManip.apply(this, dmArgs);
            } else {
                oldManip.apply(this, arguments);
            }
            cloneIndex = 0;
            if (!appendToTmplItems) {
                jQuery.tmpl.complete(newTmplItems);
            }
            return this;
        }
    });

    jQuery.extend({
        // Return wrapped set of template items, obtained by rendering template against data.
        tmpl: function (tmpl, data, options, parentItem) {
            var ret, topLevel = !parentItem;
            if (topLevel) {
                // This is a top-level tmpl call (not from a nested template using {{tmpl}})
                parentItem = topTmplItem;
                tmpl = jQuery.template[tmpl] || jQuery.template(null, tmpl);
                wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
            } else if (!tmpl) {
                // The template item is already associated with DOM - this is a refresh.
                // Re-evaluate rendered template for the parentItem
                tmpl = parentItem.tmpl;
                newTmplItems[parentItem.key] = parentItem;
                parentItem.nodes = [];
                if (parentItem.wrapped) {
                    updateWrapped(parentItem, parentItem.wrapped);
                }
                // Rebuild, without creating a new template item
                return jQuery(build(parentItem, null, parentItem.tmpl(jQuery, parentItem)));
            }
            if (!tmpl) {
                return []; // Could throw...
            }
            if (typeof data === "function") {
                data = data.call(parentItem || {});
            }
            if (options && options.wrapped) {
                updateWrapped(options, options.wrapped);
            }
            ret = jQuery.isArray(data) ?
				jQuery.map(data, function (dataItem) {
				    return dataItem ? newTmplItem(options, parentItem, tmpl, dataItem) : null;
				}) :
				[newTmplItem(options, parentItem, tmpl, data)];
            return topLevel ? jQuery(build(parentItem, null, ret)) : ret;
        },

        // Return rendered template item for an element.
        tmplItem: function (elem) {
            var tmplItem;
            if (elem instanceof jQuery) {
                elem = elem[0];
            }
            while (elem && elem.nodeType === 1 && !(tmplItem = jQuery.data(elem, "tmplItem")) && (elem = elem.parentNode)) { }
            return tmplItem || topTmplItem;
        },

        // Set:
        // Use $.template( name, tmpl ) to cache a named template,
        // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc.
        // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration.

        // Get:
        // Use $.template( name ) to access a cached template.
        // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString )
        // will return the compiled template, without adding a name reference.
        // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent
        // to $.template( null, templateString )
        template: function (name, tmpl) {
            if (tmpl) {
                // Compile template and associate with name
                if (typeof tmpl === "string") {
                    // This is an HTML string being passed directly in.
                    tmpl = buildTmplFn(tmpl)
                } else if (tmpl instanceof jQuery) {
                    tmpl = tmpl[0] || {};
                }
                if (tmpl.nodeType) {
                    // If this is a template block, use cached copy, or generate tmpl function and cache.
                    tmpl = jQuery.data(tmpl, "tmpl") || jQuery.data(tmpl, "tmpl", buildTmplFn(tmpl.innerHTML));
                }
                return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl;
            }
            // Return named compiled template
            return name ? (typeof name !== "string" ? jQuery.template(null, name) :
				(jQuery.template[name] ||
            // If not in map, treat as a selector. (If integrated with core, use quickExpr.exec) 
					jQuery.template(null, htmlExpr.test(name) ? name : jQuery(name)))) : null;
        },

        encode: function (text) {
            // Do HTML encoding replacing < > & and ' and " by corresponding entities.
            //return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
            return text;
        }
    });

    jQuery.extend(jQuery.tmpl, {
        tag: {
            "tmpl": {
                _default: { $2: "null" },
                open: "if($notnull_1){_=_.concat($item.nest($1,$2));}"
                // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions)
                // This means that {{tmpl foo}} treats foo as a template (which IS a function). 
                // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}.
            },
            "wrap": {
                _default: { $2: "null" },
                open: "$item.calls(_,$1,$2);_=[];",
                close: "call=$item.calls();_=call._.concat($item.wrap(call,_));"
            },
            "each": {
                _default: { $2: "$index, $value" },
                open: "if($notnull_1){$.each($1a,function($2){with(this){",
                close: "}});}"
            },
            "if": {
                open: "if(($notnull_1) && $1a){",
                close: "}"
            },
            "else": {
                _default: { $1: "true" },
                open: "}else if(($notnull_1) && $1a){"
            },
            "html": {
                // Unecoded expression evaluation. 
                open: "if($notnull_1){_.push($1a);}"
            },
            "=": {
                // Encoded expression evaluation. Abbreviated form is ${}.
                _default: { $1: "$data" },
                open: "if($notnull_1){_.push($.encode($1a));}"
            },
            "!": {
                // Comment tag. Skipped by parser
                open: ""
            }
        },

        // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events
        complete: function (items) {
            newTmplItems = {};
        },

        // Call this from code which overrides domManip, or equivalent
        // Manage cloning/storing template items etc.
        afterManip: function afterManip(elem, fragClone, callback) {
            // Provides cloned fragment ready for fixup prior to and after insertion into DOM
            var content = fragClone.nodeType === 11 ?
				jQuery.makeArray(fragClone.childNodes) :
				fragClone.nodeType === 1 ? [fragClone] : [];

            // Return fragment to original caller (e.g. append) for DOM insertion
            callback.call(elem, fragClone);

            // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
            storeTmplItems(content);
            cloneIndex++;
        }
    });

    //========================== Private helper functions, used by code above ==========================

    function build(tmplItem, nested, content) {
        // Convert hierarchical content into flat string array 
        // and finally return array of fragments ready for DOM insertion
        var frag, ret = content ? jQuery.map(content, function (item) {
            return (typeof item === "string") ?
            // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM.
				(tmplItem.key ? item.replace(/(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2") : item) :
            // This is a child template item. Build nested template.
				build(item, tmplItem, item._ctnt);
        }) :
        // If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. 
		tmplItem;
        if (nested) {
            return ret;
        }

        // top-level template
        ret = ret.join("");

        // Support templates which have initial or final text nodes, or consist only of text
        // Also support HTML entities within the HTML markup.
        ret.replace(/^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function (all, before, middle, after) {
            frag = jQuery(middle).get();

            storeTmplItems(frag);
            if (before) {
                frag = unencode(before).concat(frag);
            }
            if (after) {
                frag = frag.concat(unencode(after));
            }
        });
        return frag ? frag : unencode(ret);
    }

    function unencode(text) {
        // Use createElement, since createTextNode will not render HTML entities correctly
        var el = document.createElement("div");
        el.innerHTML = text;
        return jQuery.makeArray(el.childNodes);
    }

    // Generate a reusable function that will serve to render a template against data
    function buildTmplFn(markup) {
        return new Function("jQuery", "$item",
			"var $=jQuery,call,_=[],$data=$item.data;" +

        // Introduce the data as local variables using with(){}
			"with($data){_.push('" +

        // Convert the template into pure JavaScript
			jQuery.trim(markup)
				.replace(/([\\'])/g, "\\$1")
				.replace(/[\r\t\n]/g, " ")
				.replace(/\$\{([^\}]*)\}/g, "{{= $1}}")
				.replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,
				function (all, slash, type, fnargs, target, parens, args) {
				    var tag = jQuery.tmpl.tag[type], def, expr, exprAutoFnDetect;
				    if (!tag) {
				        throw "Template command not found: " + type;
				    }
				    def = tag._default || [];
				    if (parens && !/\w$/.test(target)) {
				        target += parens;
				        parens = "";
				    }
				    if (target) {
				        target = unescape(target);
				        args = args ? ("," + unescape(args) + ")") : (parens ? ")" : "");
				        // Support for target being things like a.toLowerCase();
				        // In that case don't call with template item as 'this' pointer. Just evaluate...
				        expr = parens ? (target.indexOf(".") > -1 ? target + parens : ("(" + target + ").call($item" + args)) : target;
				        exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))";
				    } else {
				        exprAutoFnDetect = expr = def.$1 || "null";
				    }
				    fnargs = unescape(fnargs);
				    return "');" +
						tag[slash ? "close" : "open"]
							.split("$notnull_1").join(target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true")
							.split("$1a").join(exprAutoFnDetect)
							.split("$1").join(expr)
							.split("$2").join(fnargs ?
								fnargs.replace(/\s*([^\(]+)\s*(\((.*?)\))?/g, function (all, name, parens, params) {
								    params = params ? ("," + params + ")") : (parens ? ")" : "");
								    return params ? ("(" + name + ").call($item" + params) : all;
								})
								: (def.$2 || "")
							) +
						"_.push('";
				}) +
			"');}return _;"
		);
    }
    function updateWrapped(options, wrapped) {
        // Build the wrapped content. 
        options._wrap = build(options, true,
        // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string.
			jQuery.isArray(wrapped) ? wrapped : [htmlExpr.test(wrapped) ? wrapped : jQuery(wrapped).html()]
		).join("");
    }

    function unescape(args) {
        return args ? args.replace(/\\'/g, "'").replace(/\\\\/g, "\\") : null;
    }
    function outerHtml(elem) {
        var div = document.createElement("div");
        div.appendChild(elem.cloneNode(true));
        return div.innerHTML;
    }

    // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance.
    function storeTmplItems(content) {
        var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m;
        for (i = 0, l = content.length; i < l; i++) {
            if ((elem = content[i]).nodeType !== 1) {
                continue;
            }
            elems = elem.getElementsByTagName("*");
            for (m = elems.length - 1; m >= 0; m--) {
                processItemKey(elems[m]);
            }
            processItemKey(elem);
        }
        function processItemKey(el) {
            var pntKey, pntNode = el, pntItem, tmplItem, key;
            // Ensure that each rendered template inserted into the DOM has its own template item,
            if ((key = el.getAttribute(tmplItmAtt))) {
                while (pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute(tmplItmAtt))) { }
                if (pntKey !== key) {
                    // The next ancestor with a _tmplitem expando is on a different key than this one.
                    // So this is a top-level element within this template item
                    // Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment.
                    pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute(tmplItmAtt) || 0)) : 0;
                    if (!(tmplItem = newTmplItems[key])) {
                        // The item is for wrapped content, and was copied from the temporary parent wrappedItem.
                        tmplItem = wrappedItems[key];
                        tmplItem = newTmplItem(tmplItem, newTmplItems[pntNode] || wrappedItems[pntNode], null, true);
                        tmplItem.key = ++itemKey;
                        newTmplItems[itemKey] = tmplItem;
                    }
                    if (cloneIndex) {
                        cloneTmplItem(key);
                    }
                }
                el.removeAttribute(tmplItmAtt);
            } else if (cloneIndex && (tmplItem = jQuery.data(el, "tmplItem"))) {
                // This was a rendered element, cloned during append or appendTo etc.
                // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem.
                cloneTmplItem(tmplItem.key);
                newTmplItems[tmplItem.key] = tmplItem;
                pntNode = jQuery.data(el.parentNode, "tmplItem");
                pntNode = pntNode ? pntNode.key : 0;
            }
            if (tmplItem) {
                pntItem = tmplItem;
                // Find the template item of the parent element. 
                // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string)
                while (pntItem && pntItem.key != pntNode) {
                    // Add this element as a top-level node for this rendered template item, as well as for any
                    // ancestor items between this item and the item of its parent element
                    pntItem.nodes.push(el);
                    pntItem = pntItem.parent;
                }
                // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering...
                delete tmplItem._ctnt;
                delete tmplItem._wrap;
                // Store template item as jQuery data on the element
                jQuery.data(el, "tmplItem", tmplItem);
            }
            function cloneTmplItem(key) {
                key = key + keySuffix;
                tmplItem = newClonedItems[key] =
					(newClonedItems[key] || newTmplItem(tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent, null, true));
            }
        }
    }

    //---- Helper functions for template item ----

    function tiCalls(content, tmpl, data, options) {
        if (!content) {
            return stack.pop();
        }
        stack.push({ _: content, tmpl: tmpl, item: this, data: data, options: options });
    }

    function tiNest(tmpl, data, options) {
        // nested template, using {{tmpl}} tag
        return jQuery.tmpl(jQuery.template(tmpl), data, options, this);
    }

    function tiWrap(call, wrapped) {
        // nested template, using {{wrap}} tag
        var options = call.options || {};
        options.wrapped = wrapped;
        // Apply the template, which may incorporate wrapped content, 
        return jQuery.tmpl(jQuery.template(call.tmpl), call.data, options, call.item);
    }

    function tiHtml(filter, textOnly) {
        var wrapped = this._wrap;
        return jQuery.map(
			jQuery(jQuery.isArray(wrapped) ? wrapped.join("") : wrapped).filter(filter || "*"),
			function (e) {
			    return textOnly ?
					e.innerText || e.textContent :
					e.outerHTML || outerHtml(e);
			});
    }

    function tiUpdate() {
        var coll = this.nodes;
        jQuery.tmpl(null, null, null, this).insertBefore(coll[0]);
        jQuery(coll).remove();
    }
})(jQuery);

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}
