if(useAdminTools==true){

function winBRopen(theURL, theName, theWidth, theHeight) { 
  var theLeft = (screen.width - theWidth) / 2;
  var theTop = (screen.height - theHeight) / 2;
  var theProps = "width="+theWidth+",height="+theHeight+",left="+theLeft+",top="+theTop+",scrollbars=yes,resizable=no";
  theWindow= window.open(theURL, theName, theProps);
  theWindow.creator = self;
  theWindow.window.focus();
};
function goto_URL(object) {window.location.href = object.options[object.selectedIndex].value;};
function modalDialogShow_IE(url,width,height) //IE
{
return window.showModalDialog(url,window,
"dialogWidth:"+width+"px;dialogHeight:"+height+"px;edge:Raised;center:Yes;help:No;Resizable:Yes;Maximize:Yes");
};
function modalDialogShow_Moz(url,width,height) //Moz
{
var left = screen.availWidth/2 - width/2;
var top = screen.availHeight/2 - height/2;
activeModalWin = window.open(url, "", "width="+width+"px,height="+height+",left="+left+",top="+top);
window.onfocus = function(){if (activeModalWin.closed == false){activeModalWin.focus();};};
};
var sActiveAssetInput;
var refreshParent;
refreshParent = 0;
function setAssetValue(v){document.getElementById(sActiveAssetInput).value = v;};
function openAsset(s){
sActiveAssetInput = s;

if(navigator.appName.indexOf('Microsoft')!=-1)
document.getElementById(sActiveAssetInput).value=modalDialogShow_IE("/core/coreSrc/externalSrc/WYSIWYG/assetManager/assetmanager.asp",640,520); //IE
else
modalDialogShow_Moz("/core/coreSrc/externalSrc/WYSIWYG/assetManager/assetmanager.asp",640,520); //Moz
};




var xForm = -1;

function updatePageTitleFields(){
document.getElementById("page_title").value = document.getElementById("page_name").value;
document.getElementById("text_head").value = document.getElementById("page_name").value;
};
function updateFormBySelect(handle,URL){
// Determine prefix
if (URL.indexOf("?") != -1){
var prefix = "&";
}else{
var prefix = "?";
}
switch (handle)
  {
case "ADMIN_EDIT_ARTICLE": { 
if(URL.match(/aID/)){
document.location = URL.replace(/aID=\d/, "aID="+document.articleForm.article_id.value);
}else{
document.location = URL + prefix + "aID=" + document.articleForm.article_id.value;
}
break;
}
case "ADMIN_NEW_ARTICLE_EDITION": { 
if(URL.match(/edition/)){
document.location = URL.replace(/edition=\d/, "edition="+document.articleForm.editionId.value);
}else{
document.location = URL + prefix + "edition=" + document.articleForm.editionId.value;
}
break;
}
case "ADMIN_UPDATE_GROUP_CHOOSE_GROUP": { 
if(URL.match(/gID/)){
document.location = URL.replace(/gID=\d/, "gID="+document.chooseGroup.gID.value);
}else{
document.location = URL + prefix + "gID=" + document.chooseGroup.gID.value;
}
break;
}
case "ADMIN_NEW_PAGE_EDITION": { 
if(URL.match(/edition/)){
document.location = URL.replace(/edition=\d/, "edition="+document.newPage.editionId.value);
}else{
document.location = URL + prefix + "edition=" + document.newPage.editionId.value;
}
break;
}
case "ADMIN_UPDATE_PAGE_EDITION": { 
if(URL.match(/edition/)){
document.location = URL.replace(/edition=\d/, "edition="+document.updatePage.editionId.value);
}else{
document.location = URL + prefix + "edition=" + document.updatePage.editionId.value;
}
break;
}
case "ADMIN_UPDATE_CHOOSE_PAGE_EDITION": { 
if(URL.match(/edition/)){
document.location = URL.replace(/edition=\d/, "edition="+document.choosePage.editionId.value);
}else{
document.location = URL + prefix + "edition=" + document.choosePage.editionId.value;
}
break;
}
case "ADMIN_UPDATE_USER_CHOOSE_USER": { 
if(URL.match(/uID/)){
document.location = URL.replace(/uID=\d/, "uID="+document.chooseUser.userID.value);
}else{
document.location = URL + prefix + "uID=" + document.chooseUser.userID.value;
}
break;
}
case "ADMIN_UPDATE_DELETE_PAGE_EDITION": { 
if(URL.match(/edition/)){
document.location = URL.replace(/edition=\d/, "edition="+document.deletePage.editionId.value);
}else{
document.location = URL + prefix + "edition=" + document.deletePage.editionId.value;
}
break;
}
case "ADMIN_DELETE_USER": { 
if(URL.match(/uID/)){
document.location = URL.replace(/uID=\d/, "uID="+document.deleteUser.uID.value);
}else{
document.location = URL + prefix + "uID=" + document.deleteUser.uID.value;
}
break;
}
case "ADMIN_UPDATE_PAGE_CHOOSE_PAGE": { 
if(URL.match(/pageID/)){
document.location = URL.replace(/pageID=.+/, "pageID="+document.choosePage.pageID.value);
}else{
document.location = URL + prefix + "pageID=" + document.choosePage.pageID.value;
}
break;
}
case "ADMIN_DELETE_PAGE_CHOOSE_PAGE": { 
if(URL.match(/pageID/)){
document.location = URL.replace(/pageID=.+/, "pageID="+document.deletePage.pageID.value);
}else{
document.location = URL + prefix + "pageID=" + document.deletePage.pageID.value;
}
break;
}
default: {break}
  }
};



function genericAJAXRemove(tblName,postID,confirmText,key){
if(confirm(confirmText)){
var removeIcon = $("#"+tblName+"-"+postID);
removeIcon.addClass("loading");
$.ajax({
  type: "GET",
  url: "/core/coreSrc/ajax/generic-post-remove.asp",
  data: "postID="+postID+"&tblName="+tblName+"&key="+key+"&x="+Math.random(9999),
  contentType: "text/html; charset=iso-8859-1",
  error : function(data){alert(data);},
  success : function (data) {
if(Math.floor(data)==1){
removeIcon.parents("tr").fadeOut("slow");
}else{
alert("Systemfel!");
removeIcon.removeClass("loading");
}
  }
});


}
}

}
function getFormObject(objectName){return document.forms[objectName];};
function getHTMLObject(objectName){return document.getElementById(objectName);};
function hideItem(theItem){getHTMLObject(theItem).style.display= "none";};
function showItem(theItem){getHTMLObject(theItem).style.display= "block";};
function toggleShowItem(theItem){
if(getHTMLObject(theItem).style.display== "block"){
getHTMLObject(theItem).style.display= "none";
}else{
getHTMLObject(theItem).style.display= "block";
}
};
function validateComment(){
var errMess = "";
var fldName= $("#userName");
var fldEmail= $("#userEmail");

if(fldName.val().length<2){
fldName.addClass("formAttention");
if(editionLCID==1053){
  errMess += "- Ditt namn\n";
}else{
  errMess += "- Your name\n";
}
}else{fldName.removeClass("formAttention");}

if(fldEmail.val().length<2){
fldEmail.addClass("formAttention");
if(editionLCID==1053){
  errMess += "- Din e-postadress\n";
}else{
  errMess += "- Your e-mail\n";
}
}else{fldEmail.removeClass("formAttention");}

if(errMess.length>2){
if(editionLCID==1053){
  errMess = "Vänligen ange obligatoriska uppgifter:\n" + errMess;
}else{
  errMess = "Please enter:\n" + errMess;
}
alert(errMess);
return false;
}else{
return true;
}
}
function setBookmark(url,title){
if(document.all){
window.external.AddFavorite(url, title);
}
else if(window.sidebar){
window.sidebar.addPanel(title, url, "");
}
else if(window.print && window.opera){
var bmLink = document.createElement('a');
bmLink.setAttribute('href',url);
bmLink.setAttribute('title',title);
bmLink.setAttribute('rel','sidebar');
bmLink.click();
} 
else{
if(editionLCID==1053){
alert("Vi saknar tyvärr direktlänk för att lägga till bokmärket i den webbläsare du använder.");
}else{
alert("Unfortunatly we were not able to add the bookmark directly to the browser you are using.");
}
}
}
var captchaField = "";
var captchaForm= "";
var captchaFormTrigger = "";
var captchaFormMessage= "";
var captchaValidField= "";

function validateCaptchaInput(formTrigger){

var hiddenVal = captchaForm.find("#captchaRandom").val();
var inputVal = captchaField.val();
var indicator= captchaForm.find(".capthcaCheck");

indicator.css({"background-image" : "url(http://www.smode-resource.se/gfx/icons/ajax-loader.gif)"});

if(captchaValidField.val()==1){
return captchaOk();
}else{
if(inputVal.length==4){
$.ajax({
  type: "GET",
  url: "/core/coreSrc/modules/captcha/ajax-validate.asp",
  data: "inputVal="+inputVal+"&hiddenVal="+hiddenVal,
  contentType: "text/html; charset=iso-8859-1",
  error : function(data,string) {alert(string);},
  success : function (data) {
  var theResult = Math.floor(data);
  if(theResult==-1){
  indicator.css({"background-image" : "url(http://www.smode-resource.se/gfx/icons/check.gif)"});
  return captchaOk();
}else{
  indicator.css({"background-image" : "url(http://www.smode-resource.se/gfx/icons/action_refresh.gif)"});
 return captchaInvalid();
  }
}
});
}else{
  indicator.css({"background-image" : "url(http://www.smode-resource.se/gfx/icons/action_refresh.gif)"});
return captchaInvalid();
}
}
}
function captchaOk(){
 captchaField.removeClass("swlValidationError");
 captchaField.addClass("swlValidationOk");
 captchaValidField.val("1");
 captchaField.attr("disabled","disabled");
 captchaShowSubmit();
 return true;
}
function captchaInvalid(){
 captchaField.removeClass("swlValidationOk");
 captchaField.addClass("swlValidationError");
 captchaValidField.val("0");
 captchaHideSubmit();
return false;
}
function captchaHideSubmit(){
 captchaFormTrigger.after(captchaFormMessage);
 captchaFormTrigger.hide();
}
function captchaShowSubmit(){
 captchaFormMessage.remove();
 captchaFormTrigger.show();
}
function removeGenericConfirm(theURL,theMessage){
if(confirm(theMessage)){
document.location=theURL;
}
}
function googleTranslateElementInit() {
  var defaultLang =(editionLCID==1053) ? 'sv' : 'en' ;
  new google.translate.TranslateElement({pageLanguage: defaultLang}, 'google_translate_element');
}
function MultiUpload(el)
{
    var self = this;
    el = $(el);
    this.working = 0;
    this.uploaded = [];
    this.el = el;
    this.id_counter = 0;
    this.rowset = $('<div class="multiupload-rowset"></div>').appendTo(this.el);
    this.panel = $('<div class="multiupload-panel"></div>').appendTo(this.el);
    this.form = el.closest('form');
    this.name = el.attr('id');
    this.formid = this.form.attr("id");

    this.num_pending = 0;
    this.num_uploaded = 0;
    this.num_failed = 0;
    this.num_working = 0;
    this.__error_fallback = [];
    this.__prevent_fallback = [];

    this.properties = {
        'url': '/core/coreSrc/ajax/public-file-upload.asp'
    };

    this.load_config();
    this.init_tpl();

    this.lang = {
        'laddaupp': "Ladda upp",
        "laggtill": "L&auml;gg till fil",
        "felantal": "Du m&aring;ste ladda upp minst "+this.properties['min-files']+' filer.',
        "arbetar": "Var god v&auml;nta tills alla filer &auml;r uppladdade innan du skickar formul&auml;ret."
    };

    this.ready_to_submit=function (e) {
        if (self.working > 0) {
            alert(self.lang.arbetar);
            return false;
        } else if (typeof self.properties['min-files'] != 'undefined'
                   && self.uploaded.length < parseInt(self.properties['min-files'], 10)) {
            alert(self.lang.felantal);
            return false;
        }

        //alert("NU funkar det:"+self.uploaded.join(','));
if(self.uploaded.length>0){
        self.form.append('<input type="hidden" name="'+self.name+'-files" value="'+self.uploaded.join(',')+'" />');
}
        self.form.children(".multiupload").remove();
return true;
    };

    this.btn_add = $('<input type="button" value="'+this.lang.laggtill+'" class="multiupload-append-file" />').appendTo(this.panel)
        .click(function () { $(self.el).find(".multiupload-rowset>.multiupload-placeholder").remove(); self.add_row(); });

    if (typeof this.properties['min-files'] != "undefined"
            && (n = parseInt(this.properties['min-files'], 10)) > 0) {
        for (var x=0; x<n; x++)
            this.add_row();
    }

    if (typeof this.properties['min-files'] != 'undefined'
        && typeof this.properties['max-files'] != 'undefined'
        && parseInt(this.properties['min-files'], 10) == parseInt(this.properties['max-files'], 10)) {
        this.btn_add.hide();
    }

    if (this.num_pending == 0)
        this.rowset.html(this.tpl.placeholder);

    MultiUpload.all.push(this);
}

MultiUpload.all = [];

MultiUpload.__tpl = {
    'success': '<div class="multiupload-success multiupload-status">{msg-success}</div>',
    'failure': '<div class="multiupload-failure multiupload-status">{msg-error}</div>',
    'loading': '<div class="multiupload-loading multiupload-status">{msg-loading}</div>',
    'placeholder': '<div class="multiupload-placeholder">{msg-placeholder}</div>'
};
MultiUpload.__tpl_def = {
        "msg-error": "Uppladdningen misslyckades.",
        "msg-success": "Fil uppladdad.",
        "msg-placeholder": "Tryck p&aring; L&auml;gg till fill f&ouml;r att b&ouml;rja",
        "msg-loading": "Laddar upp..."
};

MultiUpload.prototype.init_tpl = function () {
    var self = this;
    this.tpl = {};
    for (x in MultiUpload.__tpl) {
        this.tpl[x] = MultiUpload.__tpl[x].replace(/\{(.*)\}/g, function (str, p1) {
           return self.properties[p1] || MultiUpload.__tpl_def[p1];
        });
    }
}

MultiUpload.prototype.add_row = function () {
    var self = this;
    this.num_pending ++;
    this.id_counter ++;

    var cfg_extra = "";
    for (c in this.properties)
        cfg_extra += '<input type="hidden" name="'+c+'" value="'+this.properties[c]+'" />';

    var row = $('<div class="multiupload-row" id="'+this.name+"-"+this.id_counter+'"></div>');
    var form = $('<form class="multiupload-subform" action="'+this.properties.url+'" target="multiupload-iframe-'+this.id_counter+'" method="post" enctype="multipart/form-data">'+
                 '<input name="form-name" type="hidden" value="'+this.name+'" />'+
                 '<input name="file-id" type="hidden" value="'+this.id_counter+'" />'+
                 '<input name="file" type="file" class="upload-file-path" />'+
                 cfg_extra+

                 (this.properties['enable-comments'] == "true"
                  ?'<input class="multiupload-comment upload-file-comment" value="Ange en kommentar h&auml;r" type="text" name="comment" />'
                  :'')+

                 '</form>').appendTo(row);
    var iframe = $('<iframe style="display:none;" src="#" name="multiupload-iframe-'+this.id_counter+'"></iframe>')
        .appendTo($(document.body));

    var i = this.id_counter;
    var submit = $('<input type="submit" value="'+this.lang.laddaupp+'" class="upload-file-btn" />').appendTo(form);
    submit.click(function () {
        if ($(this).attr("disabled") == true)
            return;
        $(this).parent().parent().find(".multiupload-status").remove();
        $(this).parent().hide();
        $(this).parent().parent().append(self.tpl.loading);
        self.working ++;
        self.num_pending --;
        var _btn = this;

        self.__prevent_fallback[i] = false;
        iframe.load(function () {
            if (!self.__prevent_fallback[i]) {
                self.__error_fallback[i] = setTimeout(function () {
                    MultiUpload.report_status(0, self.name, i, 0, "Ett internt fel uppstod");
                }, 400);
            }
        });
        setTimeout(function(){$(_btn).attr("disabled", true);}, 100);
        return true;
    });

    row.appendTo(this.rowset);

    if (typeof this.properties['max-files'] != 'undefined'
        && ((this.num_pending + this.uploaded.length + this.working)
           >= parseInt(this.properties['max-files'], 10)))
        $(this.btn_add).attr("disabled", true);
}

MultiUpload.submit_form = function(id)
{
    for (var x=0; x<MultiUpload.all.length; x++) {
if(MultiUpload.all[x].formid==id){
return MultiUpload.all[x].ready_to_submit();
}
}
return false;
}

MultiUpload.report_status = function(success, form_name, file_id, server_id, msg)
{
    var m;
    for (var x=0; x<MultiUpload.all.length; x++) {
        if ((m = MultiUpload.all[x]).name == form_name) {
            m.__prevent_fallback[file_id] = true;
            if (m.__error_fallback[file_id] != null && m.__error_fallback[file_id] != undefined) {
                clearTimeout(m.__error_fallback[file_id]);
                m.__error_fallback[file_id] = null;
            }

            var tpl = success == "1"
                    ? m.tpl.success
                    : m.tpl.failure;
            var el = $(m.rowset).children('#'+form_name+"-"+file_id);

            el.find(".multiupload-status").remove();

            if (msg != "")
                $(tpl).text(msg);

            el.prepend($(tpl));
            m.working --;
            if (success == "1")
                m.uploaded.push(server_id);
            else {
                m.num_failed ++;
                if (typeof m.properties['max-files'] == 'undefined'
                    || ((m.num_pending + m.uploaded.length + m.working) < parseInt(m.properties['max-files'], 10))) {
                    el.find("form").show();
                    el.find("form>input[type=submit]").removeAttr("disabled").show();
                }
            }
        }
    }
}

MultiUpload.prototype.load_config = function () {
    var self = this;
    this.el.children("input.multiupload-config").each(function () {
        self.properties[this.title] = this.value;
    });
};

function ajaxRenewSession(){
var renewer = $(".ajaxRenewLoginSession:first");
if(renewer.is('*')){
var theKey= escape(renewer.find(".key").text());
var theRandom= escape(renewer.find(".rnd").text());
var theSalt= escape(renewer.find(".salt").text());
var theDate= renewer.find(".dte").text();
if(theKey.length>0 && theRandom.length>0 && theSalt.length>0 && theDate.length>0){
   renewer.load("/core/coreSrc/ajax/renew-session.asp",{randomInt : theRandom, keyStr : theKey, saltInt : theSalt, timeDate: theDate}, function(){});
   setTimeout('ajaxRenewSession()',60000);
}
}
}
$(document).ready(function(){
var uploadGadget = $(".swl-file-picker");
var trigger= uploadGadget.find(".trigger");
var content= uploadGadget.find(".content");
trigger.click(function(){
  content.fadeIn(600);
});
});
function swlFileAttachmentFinish(){
$(".swl-file-picker .content.hidden").fadeOut(300);
}
function swlFileAttachmentCallback(uploadStatus,uploadMessage,uploadedFiles){

var uploadGadget = $(".swl-file-picker");
var messageBox= uploadGadget.find(".info-header");
var filesBox= uploadGadget.find(".files-box");
var fieldName= uploadGadget.find(".form-field-name").text();
var frameTarget= uploadGadget.find("iframe").attr("name");

uploadGadget.removeClass("success").removeClass("error");
messageBox.html(uploadMessage);
switch(uploadStatus){
case 1: case 2:
 uploadGadget.addClass("success");

filesBox.html("");

var files =uploadedFiles.split(", ");
var currFile;
var currFileName;

for(var i = 0; i < files.length; i++){
currFile = files[i];
if(currFile.length>0){
currFileName = currFile.split("/");
currFileName = currFileName[currFileName.length-1];
filesBox.append("<p class='uploaded-file'><a href='/core/coreSrc/ajax/swl-file-attachment.asp?at=2&fi="+(i+1)+"&sn=swlaf-"+frameTarget.replace(/iframe-/,'')+"' target='"+frameTarget+"' class='remove-file'>&nbsp;</a>"+currFileName+"</p>");
filesBox.append("<input type='hidden' id='"+fieldName+"' name='"+fieldName+"' value='" +currFile+ "'>");
}
}
 break;

case 11:
 uploadGadget.addClass("error");
 alert(uploadMessage);
 break;
 
case 12:
 uploadGadget.addClass("error");
 alert(uploadMessage);
 break;

case 10:
 uploadGadget.addClass("error");
 alert(uploadMessage);
 break;
}
}
function swlGenericFormVal(formID,eMess,wMess,cMess){

var theForm= $("#"+formID);
var hardFields= theForm.find(".validate-hard > :input");
var softFields= theForm.find(".validate-soft > :input");
var valWarning= validateSoftFields(softFields);
var valError= validateHardFields(hardFields);

if(valError==true){
if(eMess.length>0){alert(eMess);}
return false;
}else if(valWarning==true && wMess.length>0){
if(confirm(wMess)){
return true;
}else{
return false;
}
} else {
if(cMess.length>0){
if(confirm(cMess)){return true;}
}else{
return true;
}
}
}

function validateSoftFields(fieldSet){
var foundError = false;
fieldSet.each(function(i){
var tmpFld = $(fieldSet[i]);
var tmpVal = "";
if(tmpFld.is("select")){
tmpVal = tmpFld.find("option:selected").val();
}else{
tmpVal = tmpFld.val();
}
if(tmpVal.length<1){
foundError = true;
tmpFld.addClass("swlValidationWarning");
tmpFld.removeClass("swlValidationOk");
}else{
  tmpFld.removeClass("swlValidationWarning");
tmpFld.addClass("swlValidationOk");
}
});
return foundError;
}
function validateHardFields(fieldSet){
var foundError = false;
fieldSet.each(function(i){
var tmpFld = $(fieldSet[i]);
var tmpVal = "";
if(tmpFld.is("select")){
tmpVal = tmpFld.find("option:selected").val();
}else{
tmpVal = tmpFld.val();
}
if(tmpVal.length<1){

foundError = true;
tmpFld.addClass("swlValidationError");
tmpFld.removeClass("swlValidationOk");
}else{
tmpFld.removeClass("swlValidationError");
tmpFld.addClass("swlValidationOk");
}
});
return foundError;
}
function hideSystemMessage(){
if($("div.systemMessageBox").is('*')){
   $("div.systemMessageBox").fadeOut('slow');
}
}
function clockSystemMessage2010(){
var delayBox = $(".system-message-container").find(".delay");
var newDelay = Math.floor(delayBox.html())-1;

var doCount = !$(".pause-delay").is("*");
if(newDelay > 0 && doCount){
delayBox.html(newDelay);
setTimeout('clockSystemMessage2010()',1000);
}else{
if(doCount){
$(".system-message-container").fadeOut("slow");
}else{

}
}
}
function userAutoCompleteFill(tempName,tempId,destinationField,valueField){
$("input#"+destinationField).val(tempId);
$("input#"+valueField).val(tempName);
$("div#autoComplete"+destinationField).slideUp("slow");
}

$(document).ready(function(){

$("#adminToolBoxToggler").toggle(function () {
$("#adminToolBox").slideDown("slow");
},function () {
$("#adminToolBox").slideUp("slow");
}); 

$("#article_teaser").add("#activity_teaser").change(function(){
var teaserField = $(this);
teaserField.parents("form").find("#sharing_message").val(teaserField.val());
});
$("img.resizeAjax").each(function(){
var theImage= $(this);
var originalSrc = theImage.attr("src");
theImage.attr({"src" : "http://www.smode-resource.se/gfx/icons/ajax-loader.gif"});
var newWidth = theImage.attr("width");
var theHeight = theImage.height();
$.ajax({
  type: "GET",
  url: "/core/coreSrc/ajax/resize-image.asp",
  data: "width="+newWidth+"&path="+originalSrc+"&height="+theHeight,
  contentType: "text/html; charset=iso-8859-1",
  success : function (data) {
theImage.attr({"src" : data});
  }
})
});
$(".colBoxContainer.clickAble > .top").click(function () {
var theContentBox = $(this).parent().find(".content");
var theIcon = $(this).find(".icon");

if(theContentBox.is(":visible")){
theContentBox.slideUp("fast");
if(theIcon.is(".visible")){
theIcon.removeClass("visible");
}else{
theIcon.addClass("visible");
}
}else{
theContentBox.slideDown("fast");
if(theIcon.is(".visible")){
theIcon.removeClass("visible");
}else{
theIcon.addClass("visible");
}
}
});
$(".moduleBoxContainer.clickAble > .top").toggle(function () {
$(this).parent().find(".content").slideUp("slow");
},function () {
$(this).parent().find(".content").slideDown("slow");
}); 
$(".horizontal-colboxes").each(function(){
var maxColBoxHeight= 0;
var currColBoxRow = $(this);
var currBoxes= currColBoxRow.find(".colBoxContainer,.unformated-messageBox-container");
var boxCount= currBoxes.length;
var i= 0;
currBoxes.find(".content,.art-blockcontent,.art-Blockcontent,.art-BlockContent,.unformated-messageBox").each(function(){
var currBox = $(this);
var currHeight = currBox.height();
if(currHeight>maxColBoxHeight){maxColBoxHeight=currHeight}
});   
currBoxes.find(".content,.art-blockcontent,.art-Blockcontent,.art-BlockContent,.unformated-messageBox").each(function(){
var currBox= $(this);
var currParent= currBox.parents(".colBoxContainer");
currBox.height(maxColBoxHeight);
currBox.addClass("colbox-"+(i+1));
i++; if(i==boxCount){
if(currParent.is("*")){
currParent.addClass("last-colbox")
}else{
currBox.addClass("last-colbox")
}

};
});   
});

var currentURL = document.location;
currentURL = currentURL.toString();
var showBrowserWarning = currentURL.indexOf('show-warning',0);
if($.browser.msie == true || showBrowserWarning>0){
  if($.browser.version<7 || showBrowserWarning>0){

var contentStr= "";
$.ajax({
  type: "GET",
  url: "/core/coreSrc/ajax/old-browser.asp",
  data: "show-browser-warning="+showBrowserWarning+"&x="+Math.random(9999),
  contentType: "text/html; charset=iso-8859-1",
  error : function(data){},
  success : function (data) {
  
contentStr = data;
if(contentStr.length>0){

var content= $("<div class='lightbox-content'>"+contentStr+"</div>");
var contentSize= new Array(650,330,650,330);
var overlay= $("<div class='lightbox-overlay'></div>");
var pageBody= $("body");
var pageWindow= $(window);
var windowSize= new Array();
windowSize[0] = (pageWindow.width() > pageBody.outerWidth()) ? pageWindow.width() : pageBody.outerWidth();
windowSize[1] = (pageWindow.height() > pageBody.outerHeight()) ? pageWindow.height() : pageBody.outerHeight();
overlay.css({"width" : windowSize[0]+"px", "height" : windowSize[1]+"px"});

overlay.appendTo(pageBody).fadeTo(300,0.5,function(){
content.appendTo(pageBody).css({
   "top" : (pageWindow.height()/2)+"px", 
   "left" : (windowSize[0]/2)+"px", 
   "width" : "10px", 
   "height" : "10px"}).show().animate({
"top" : "100px", 
"left" : (windowSize[0]/2)-(contentSize[0]/2)+"px", 
"width" : contentSize[2]+"px", 
"height" : contentSize[3]+"px"}
,"fast","",function(){
overlay.click(function(){
content.fadeOut("slow",function(){
overlay.fadeOut("fast",function(){
overlay.remove();
});
});
});

});
});

}

  }
});
  }
}
var stlFld = $(".stlth-field");

if(stlFld.is("*")){
stlFld.remove();
}
captchaField = $("#captchaValue");

if(captchaField.is("*")){
captchaForm= captchaField.parents("form");
captchaFormTrigger = captchaForm.find(".formSubmitTrigger");
captchaValidField = captchaForm.find("#captcha-is-validated");
captchaValidField.val(0);

if(editionLCID==1053){
  captchaFormMessage= $("<div id='captchaMessage'>Vänligen ange korrekt skräppostkod ovan innan du fortsätter.<br>Klicka på de gröna pilarna för att verifiera koden.</b>");
}else{
  captchaFormMessage= $("<div id='captchaMessage'>Please enter the captcha-code above to continue.<br>To verify your code, press the green arrows.</b>");
}

captchaForm.submit(function(){return false;});
captchaField.change(function(){validateCaptchaInput();});
captchaHideSubmit();
}
$("input#userNewPassword").add("input#new_psw").val("")
$(".autoEmpty").find("input").focus(function () {
var field = $(this);
var currentValue = field.val().toLowerCase();
var defaultValue = field.attr("defaultValue").toLowerCase();
if(currentValue == defaultValue){field.val("");}
});
$(".password-change-field > input").change(function(){
var message = "";
editionLCID==1053 ? message="Detta kommer att skriva över ditt befintliga lösenord, vill du fortsätta?" : message="This will replace your current password, would you like to continue?";
if(confirm(message)){}else{$(this).val("");}
});
$(".colBoxContainer,.unformated-messageBox").find("a img").each(function(){

var currImgLink = $(this);
currImgLink.hover(function(){
currImgLink.addClass("colbox-image-hover");
currImgLink.css({"opacity" : "0.7"});
},function(){
currImgLink.removeClass("colbox-image-hover");
currImgLink.css({"opacity" : "1"});
});

});
// QOUTE
$(".commentPost .qoute").click(function(){
var trigger = $(this);
var comPost= trigger.parents(".commentPost");
var comID= parseInt(comPost.find(".commentID").text());
var qouteHeader= comPost.find("h3").text();
var comForm= $(".admin.comment > form");
var parField= comForm.find("#parentID");
var formNotice= comForm.find(".qoute-info");
formNotice.html('<span>Du svarar på ett tidigare inlägg: </span><br>"'+qouteHeader+'"').addClass("active");
parField.val(comID);
$.scrollTo(comForm, 1600, {offset:-100} );
});

$(document).ready(function(){

$(".jquery-slider-container").each(function(sliderIndex){

var container = $(this);
var slider= container.parent();
var viewport = container.find(".jquery-slider-viewport");
var wrapper = container.find(".jquery-slider-wrapper");
var sequences= container.find(".jquery-slider-sequence");
var labels= sequences.find(".label");
var lodingInfo = $("<div class='jquery-slider-loading-overlay'></div>");
var navigationbar= $("<div class='jquery-slider-navigation-bar'></div>");
var containerWidth = container.outerWidth();
var containerHeight = 0;
var totalOffset= 0;
var currSequenceNr= 1;
var defaultExposure = 4000;
var isAnimating= false;
var currTimer;
var currCounter;

container.find(".jquery-slider-sequence > br").add("noscript").remove();

// REMOVE if no sequences was found, otherwise show
if(!sequences.is("*")){slider.remove(); return;}

container.addClass("loading");

// Start slideshow, with some delay
setTimeout(function(){
cacheSlides();
container.height(containerHeight);
navigationbar.appendTo(container);
container.removeClass("loading");
},1500+ (sequences.length*150));
// ---------------


// BUILD Slideshow
/*
Cache content and elements
Calculate sizes
Set CSS dynamicly
Add navigational items
*/
function cacheSlides(){
  sequences.each(function(i){

   var currSeq = $(sequences[i]);
   var currImage= currSeq.find("img:first");
   var currThumb= currImage.attr("thumbSrc");
   var currURL= currSeq.find("a:first");
   var currLabel= currSeq.find(".label");
   var currMeta= currSeq.find(".meta-data");
   var imageSize= (currImage.width()>containerWidth) ? containerWidth : currImage.width();
   var labelSize= new Array(0,0);
   var currExposure= defaultExposure;
   var metaExposure = false;
   var metaRibbon;
   var metaDate;
   var metaComment;

 // Handle label
 if(currLabel.is("*")){
   labelSize= new Array(
containerWidth-(
parseInt(currLabel.css("paddingLeft").replace(/px/,"")) + 
parseInt(currLabel.css("paddingRight").replace(/px/,"")))
,
containerHeight-(
parseInt(currLabel.css("paddingTop").replace(/px/,"")) + 
parseInt(currLabel.css("paddingLeft").replace(/px/,"")))
);
currLabel.css({"width":labelSize[0]+"px","top":containerHeight+"px"});
}

 // Get meta, if it exists
if(currMeta.is("*")){
   metaExposure= currMeta.find(".exposure");
   metaRibbon= currMeta.find(".ribbon-label");
   metaDate= currMeta.find(".moduleDate");
   metaComment= currMeta.find(".moduleComment");
      currExposure= (metaExposure.text()=="") ? defaultExposure : parseInt(metaExposure.text());
  
   if(metaRibbon.is("*")){metaRibbon.css({"left":"5px","top":(labelSize[1]-35)+"px"});}
   if(metaExposure.is("*")){metaExposure.css({"left":(labelSize[0]-50)+"px","top":"-6px"});}else{metaExposure = false;}
   if(metaDate.is("*")){metaDate.css({"left":"0px","top":"24px"});}
   if(metaComment.is("*")){metaComment.css({"left":"0px","top":"-7px"});;}
}
   
currImage.css({"width": imageSize+"px"});
    currSeq.data("width",currSeq.width());
    currSeq.data("height",currSeq.height());
    currSeq.data("offset",totalOffset);
    currSeq.data("index",i);
    currSeq.data("url",currURL.attr("href"));
    currSeq.data("thumb",currThumb);
    currSeq.data("exposure",currExposure);
    currSeq.data("counter",metaExposure);
    currSeq.data("label",currLabel);
       currSeq.css({"left" : totalOffset+"px"});
       totalOffset+= currSeq.outerWidth();
containerHeight = (currSeq.data("height") > containerHeight) ? currSeq.data("height") : containerHeight;

// Navigation
       $("<div class='nav-btn' id='slider-"+sliderIndex+"-nav-btn-"+(i+1)+"'>"+(i+1)+"</div>").appendTo(navigationbar).click(function(){
  if(!isAnimating){clearTimeout(currTimer);seqSlideTo(i+1);}
});
  currSeq.click(function(){document.location = currSeq.data("url");});
  currSeq.hover(function(e){
  if(!isAnimating){
  clearTimeout(currTimer);
  clearTimeout(currCounter);
  currSeq.addClass("paused");
  }
 },function(e){
  var hoverTarget = $(e.relatedTarget).attr("class");
  if(hoverTarget != "jquery-slider-navigation-bar" && hoverTarget != "nav-btn" ){
   if(!isAnimating){
  currSequenceNr = (currSequenceNr==sequences.length) ? 1 : currSequenceNr+1;
  currSeq.removeClass("paused");
  seqSlideTo(currSequenceNr);
   }
  }
 });
    currURL.remove();
  });
  
  slider.animate({"height" : containerHeight+"px"},"fast");
  lodingInfo.appendTo(viewport).css({"width" : containerWidth+"px", "height" : containerHeight+"px"});
  seqSlideTo(1);
}


// SET NAV BAR MARKER
function seqNavBarMarker(activeSequence){
navigationbar.find(".nav-btn.active").removeClass("active");
navigationbar.find("#slider-"+sliderIndex+"-nav-btn-"+activeSequence).addClass("active");
}

// SLIDE-TO-SEQUENCE
function seqSlideTo(slideTo){

var currentSlide= slideTo;
var nextSlide = (currentSlide==sequences.length) ? 1 : currentSlide+1;
currentSlide= $(sequences[currentSlide-1]);
nextSlide = $(sequences[nextSlide-1]);
  currSequenceNr = (currentSlide.data("index")+1);
var targetWidth = currentSlide.data("width");
var targetHeight = currentSlide.data("height");
isAnimating= true;

navigationbar.addClass("passive");
lodingInfo.fadeTo(400,0.5,function(){
currentSlide.find("img").css({"visibility" : "visible"});
labels.css({"top":containerHeight+"px"});
wrapper.animate({"left" : -currentSlide.data("offset")+"px"},"slow","",function(){
  container.css({"width" : targetWidth+"px","height" : targetHeight+"px"});
viewport.animate({
   "width" : targetWidth+"px", 
   "height" : targetHeight+"px",
   "marginTop" : "0px", 
   "marginLeft" : Math.floor((containerWidth-targetWidth)/2)+"px",
   "marginBottom" : Math.floor((containerHeight-targetHeight)/2)+"px", 
   "marginRight" : Math.floor((containerWidth-targetWidth)/2)+"px"
 }, 
 "fast",
 "",
 function(){
  seqNavBarMarker(currSequenceNr); 
  lodingInfo.fadeOut("slow",function(){
currentSlide.data("label").css({"left":currentSlide.data("offset")+"px","display":"block"}).animate({"top":(targetHeight-currentSlide.data("label").outerHeight())+"px"},"fast","",function(){});

if(sequences.length>1){
  seqQueueSlide((nextSlide.data("index")+1), currentSlide.data("exposure"));
  isAnimating= false;
  navigationbar.removeClass("passive");
  if(currentSlide.data("counter") != false){
countDown(currentSlide.data("counter"), currentSlide.data("exposure")+1000);
  }
}else{
  if(currentSlide.data("counter") != false){
  currentSlide.data("counter").hide();
  }
}
});
});
});
});
}

// QUE NEXT SLIDE
function seqQueueSlide(nextSlideIndex, nextSlideExposure){
currTimer = setTimeout(function(){seqSlideTo(nextSlideIndex);},nextSlideExposure)
}

// COUNTER
function countDown(element, value){
  if(element.is("*")){
value = parseInt(value)-1000;
element.html(parseInt(value/1000));
if(value>1){currCounter = setTimeout(function(){countDown(element, value);},1000);}
  }
}
// -----------------------------------------------------------------------------------------------------------
});
})
if(useJqueryUI==true){
$("input.datePickerjQuery").datepicker({
monthNames: ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
dayNames: ['Söndag', 'Måndag', 'Tisdag','Onsdag', 'Torsdag', 'Fredag', 'Lördag'],
dayNamesShort: ['Sön', 'Mån', 'Tis', 'Ons', 'Tors', 'Fre', 'Lör'],
dayNamesMin: ['Sö', 'Må', 'Ti', 'On', 'To', 'Fr', 'Lö'],
firstDay: 1,
dateFormat: $.datepicker.ATOM, 
showOn: "both",
buttonImage: "http://www.smode-resource.se/gfx/icons/24/calendar_24.gif", 
buttonImageOnly: true
});
$("#altInline").hide();
}
var editorInstances = $(".InnovaEditorInstance");

editorInstances.each(function(i){
var editorTable= $(editorInstances[i]);
var editorContainer = editorTable.parent();
var editorContHeader= editorContainer.parent().find("#"+editorContainer.attr("id")+"_header");
var pageWidth = editorTable.parent().parent().width();
var editorWidth= pageWidth.toString()+"px";
var headerWidth= pageWidth-24;
headerWidth= headerWidth.toString()+"px";
editorContainer.css({"width": editorWidth, "padding" : "0px", "border" : "0"});
editorContHeader.css({"width": headerWidth});
})

// SWL FORM GEO LOC LOOKUP

$(".swl-geo-loc-wrapper .close-geo-loc").click(function(){
$(this).parent().fadeOut(300);
});
$(".swl-geo-loc-wrapper").each(function(){

var trigger= $(this);
var picker= trigger.find(".get-position");
var geoLat= trigger.find(".default-lat").text();
var geoLng= trigger.find(".default-lng").text();
var posFields= trigger.find(".search-gadget");
var isVisible= picker.is("*");

if(!isVisible){
posFields.show();
$("#geoLat").val(geoLat);
$("#geoLng").val(geoLng);
resetSwlGeoFormMap(geoLat,geoLng,12);
}else{
picker.click(function(){
$("#geoLat").val(geoLat);
$("#geoLng").val(geoLng);
posFields.fadeIn(1000);
resetSwlGeoFormMap(geoLat,geoLng,12);
});
}

});
function resetSwlGeoFormMap(geoLat,geoLng,zoomLevel){

if(geoLat=="0" || geoLat==""){geoLat="59.631831150402725"}
if(geoLng=="0" || geoLng==""){geoLng="17.073440551757812"}


var geoMapBox = document.getElementById("swl-geo-loc-map");
var geoMapPos= new google.maps.LatLng(geoLat,geoLng);
var geoMapOpt= {
  zoom: zoomLevel,
  center: geoMapPos,
  disableDoubleClickZoom: true,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
var geoMap= new google.maps.Map(geoMapBox,geoMapOpt);
var geoMarker = new google.maps.Marker({
  position: geoMapPos,
  map: geoMap,
  animation: google.maps.Animation.BOUNCE,
  icon: "http://smode-resource.se/gfx/icons/google-maps/blue/downloadicon.png",
  title: "Aktuell position"
  });
google.maps.event.addListener(geoMap, 'dblclick', function(e){
geoFormResponse(e);
});
}
$(".swl-geo-loc-wrapper .search-user-position").click(function(){
if(confirm("Låt oss beräkna din nuvarande position!\n\nAv integritetsskäl måste du tillåta din webbläsare att beräkna din aktuella position.\nEn ruta kommer att visas strax efter att du klickat OK nedan - var noga med att Bekräfta valet din webbläsare ger dig.\n\nOBS! Detta bygger på ny teknik som endast är tillgänglig i vissa webbläsare.")){
var geoLocBox= $(".swl-geo-loc-wrapper").addClass("loading");
var infoHeader= geoLocBox.find(".info-header").html("Söker position..");
swlGetLoc('geoFormResponse');
}
});
function geoFormResponse(response){

var geoLocBox= $(".swl-geo-loc-wrapper").removeClass("success").removeClass("error");
var posFields= geoLocBox.find(".search-gadget");
var infoHeader= posFields.find(".info-header");
var infoMessage= "";

// Error handeling
switch(response){
case 1:// No native support
  infoMessage = "Din webbläsare saknar stöd för Geolocation.<br>Vi kunde inte beräkna din position.";
  geoLocBox.addClass("error");
break;
case 2:// HTML5 not activated in SWL
  infoMessage = "Okänt fel. Vi kunde inte beräkna din position.";
  geoLocBox.addClass("error");
break;
case 3:// Position not found
  infoMessage = "Vi kunde inte beräkna din position.";
  geoLocBox.addClass("error");
break;
case 4:// Time out
  infoMessage = "Timeout.\nVi kunde inte beräkna din position.";
  geoLocBox.addClass("error");
break;
default:
  infoMessage = "Koordinater funna!";
  geoLocBox.addClass("success");
useResponse(response);
break;
}
infoHeader.html(infoMessage);
geoLocBox.removeClass("loading");

  // Use found position!
  // ---------------------------------
function useResponse(p){
 var latField= $("#geoLat");
 var longField= $("#geoLng");
 var lat;
 var lng;

  if(p.latLng){
 lat = p.latLng.lat();
 lng = p.latLng.lng();
  }else{
 lat = p.coords.latitude;
 lng = p.coords.longitude;
  }
  
   latField.val(lat);
   longField.val(lng);
   
   resetSwlGeoFormMap(lat,lng,13);
  
}
  // ---------------------------------
}
$(".ajaxFormLoader").removeClass("ajaxFormLoader");
$(".date1 > input").change(function(){
var date1 = $(this);
var date2 = date1.parents(".formGroup").find(".date2 > input");

$.ajax({
  type: "GET",
  url: "/core/coreSrc/ajax/next-day-date.asp",
  data: "sDate="+date1.val()+"&x="+Math.random(99999),
  contentType: "text/html; charset=iso-8859-1",
  error : function(data,string) {date2.val(date1.val());},
  success : function (data) {
date2.val(data);
  }
});
});
function swlGetLoc(callback){

var timeOut = setTimeout(function(){
  response = 4;
eval(callback)(response);
},30000);

if(useHTML5){
  if (Modernizr.geolocation) {
if (geo_position_js.init()) {
  geo_position_js.getCurrentPosition(geo_success, geo_error);
}else{
  navigator.geolocation.getCurrentPosition(eval(native_geo_success),eval(native_geo_error));
}
  } else {
// No native support
clearTimeout(timeOut);
eval(callback)(1);
  }
}else{
// HTML5 not active
clearTimeout(timeOut);
eval(callback)(2);
}

function geo_success(p) {
clearTimeout(timeOut);
response = p;
eval(callback)(response);
}

function geo_error() {
clearTimeout(timeOut);
  response = 3;
eval(callback)(response);
}

function native_geo_success(p) {
clearTimeout(timeOut);
response = p;
eval(callback)(response);
}

function native_geo_error(e) {
clearTimeout(timeOut);
  response = 3;
eval(callback)(response);
}
}
if(useGoogleMaps==true){

var swlMainMap;
$(".google-map-container").each(function(){
var mapContainer = $(this);
var mapID = mapContainer.attr("id");
var loader = mapContainer.find(".loader");
var lodingTime = parseInt(mapContainer.find(".load-time").text());
var mapW = parseInt(mapContainer.find(".width").text());
var mapH = parseInt(mapContainer.find(".height").text());
var lat = parseFloat(mapContainer.find(".lat").text().replace(/,/,"."));
var long = parseFloat(mapContainer.find(".long").text().replace(/,/,"."));
var zoom = Math.floor(mapContainer.find(".zoom").text());
var icon = mapContainer.find(".icon");

if(icon.is("*")){
icon = icon.text();
}else{
icon = "http://smode-resource.se/gfx/icons/google-maps/blue/information.png";
}

var label = mapContainer.find(".label").text();
if(typeof google == "undefined"){
mapContainer.fadeOut("slow");
}else{
if(isNaN(lodingTime)){lodingTime = 1800;}
mapContainer.find(".AJAXhiddenElement").remove();
mapW = (mapW<1) ? 300 : mapW;
mapH = (mapH<1) ? 300 : mapH;
mapContainer.animate({"width" : mapW+"px", "height" : mapH+"px"},lodingTime,"",function(){
loader.fadeOut(lodingTime*0.8,function(){
var coords = new google.maps.LatLng(lat,long);
var mapOpt = {zoom: zoom, center: coords, mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById(mapID), mapOpt);
var marker = new google.maps.Marker({position: coords, map: map, icon: icon, animation: google.maps.Animation.DROP,title: label});
});
});
};
});

  // GENERIC OVERVIEW MAP
  $(".swl-overview-map").each(function(j){

var mapJQ= $(this);
var mapOptionsBox= mapJQ.find(".map-options");
var mapZoom= parseInt(mapOptionsBox.find(".zoom").text());

var mapType;
switch(mapOptionsBox.find(".type").text().toLowerCase()){
case "roadmap":
   mapType = google.maps.MapTypeId.ROADMAP;
  break;
  
case "satellite":
   mapType = google.maps.MapTypeId.SATELLITE;
  break;
  
case "terrain":
   mapType = google.maps.MapTypeId.TERRAIN;
  break;
  
case "hybrid":
   mapType = google.maps.MapTypeId.HYBRID;
  break;

default:
   mapType = google.maps.MapTypeId.ROADMAP;
  break;  
}

var mapContainer = document.getElementById(mapJQ.find(".map-wrapper").attr("id"));
var mapOptions = {
  zoom: mapZoom,
  disableDefaultUI: mapOptionsBox.find(".disableUI").is("*"),
  mapTypeControl: mapOptionsBox.find(".mapTypeControl").is("*"),
  mapTypeId: mapType
};
var mapBounds= new google.maps.LatLngBounds();
swlMainMap = new google.maps.Map(mapContainer,mapOptions);


// Append markers
var markers= mapJQ.find(".marker");
markers.each(function(i){
var currContent = $(markers[i]);
var currPosition= new google.maps.LatLng(currContent.find(".lat").text(),currContent.find(".lng").text());
var currMarker = new google.maps.Marker({
  position: currPosition,
  map: swlMainMap,
  icon: currContent.find(".icon").text(),
  title:currContent.find(".label").text()
  });
var currPopup = new google.maps.InfoWindow({
  content: "<div class='swl-info-window'>" + currContent.find(".content").html() + "</div>",
  maxWidth: 200,
  position: currPosition
});

mapBounds.extend(currPosition);

  google.maps.event.addListener(currMarker, 'click', function() {
  currPopup.open(swlMainMap);
  });

});

google.maps.event.addListener(swlMainMap, 'dblclick', function(e){
alert(e.latLng.lat()+', '+e.latLng.lng());
});

  // ZOOMING / POSITION
  
var initialZoomSet= false;
var forceZoom= mapOptionsBox.find(".force-zoom").is("*");

// Fit bounds
swlMainMap.fitBounds(mapBounds);
google.maps.event.addListener(swlMainMap,'bounds_changed',function(){
if((swlMainMap.getZoom() != mapZoom && forceZoom) && !initialZoomSet){
swlMainMap.setZoom(mapZoom);
initialZoomSet = true;
}
});


// Position me on the map : Callback function listed below, outside this func
   mapJQ.find(".position-me").click(function(){swlGetLoc('swlOverviewMapMyPos');});
   
  });
function swlOverviewMapMyPos(response){

// Error handeling
switch(response){
case 1:// No native support
  alert("Vi kunde inte beräkna din position.");
break;
case 2:// HTML5 not activated in SWL
  alert("Vi kunde inte beräkna din position.");
break;
case 3:// Position not found
  alert("Vi kunde inte beräkna din position.");
break;
default:
useResponse(response);
break;
}

  // Use found position!
  // ---------------------------------
function useResponse(p){
  if(confirm('Vi hittade din position!\n\nVill du att vi lägger till din position på kartan?\nKartan kommer samtidigt att zoomas för att inkludera din position.')){
var position= new google.maps.LatLng(p.coords.latitude ,p.coords.longitude);
var bounds= swlMainMap.getBounds();
bounds.extend(position);
var marker = new google.maps.Marker({
  position: position,
  map: swlMainMap,
  animation: google.maps.Animation.BOUNCE,
  icon: "http://smode-resource.se/gfx/icons/google-maps/brown/direction_down.png",
  title: "Du är här!: "+p.coords.latitude+', '+p.coords.longitude
  });
swlMainMap.fitBounds(bounds);
  }
}
  // ---------------------------------  
}
}
if($("div.imageSwitcher").is("*")){
var switchImages = $("div.imageSwitcher img");   
switchImages.each(function(index){
var currentImage = $(switchImages[index]);
currentImage.hide();
currentImage.click(function(){
switchImages.hide();
if(index==(switchImages.size()-1)){
$(switchImages[0]).show();
}else{
$(switchImages[index+1]).show();
}
});
});
$(switchImages[0]).show();
}
$(".lightbox").each(function(){
var lightbox= $(this);
var autoTrigger= lightbox.is(".auto-trigger");
var trigger= lightbox.find("a:first");
var content= lightbox.find(".lightbox-content");
var contentSize= new Array(content.outerWidth(),content.outerHeight(),content.width(),content.height());
var overlay= $("<div class='lightbox-overlay'></div>");
var closeBtn= $("<div class='lightbox-close-wrapper'><div class='lightbox-close-btn'>&nbsp;</div></div>");
var pageBody= $("body");
var pageWindow= $(window);
var windowSize= new Array();
windowSize[0] = (pageWindow.width() > pageBody.outerWidth()) ? pageWindow.width() : pageBody.outerWidth();
windowSize[1] = (pageWindow.height() > pageBody.outerHeight()) ? pageWindow.height() : pageBody.outerHeight();
overlay.css({"width" : windowSize[0]+"px", "height" : "1000%"});

if(autoTrigger==true){
 showLightbox();
}else{
 trigger.click(function(){showLightbox()});
}

function showLightbox(){
overlay.appendTo(pageBody).fadeTo(300,0.5,function(){
content.appendTo(pageBody).css({
   "top" : (pageWindow.height()/2)+"px", 
   "left" : (windowSize[0]/2)+"px", 
   "width" : "10px", 
   "height" : "10px"}).show().animate({
"top" : "100px", 
"left" : (windowSize[0]/2)-(contentSize[0]/2)+"px", 
"width" : contentSize[2]+"px", 
"height" : contentSize[3]+"px"}
,"fast","",function(){

$.scrollTo(0,700);

closeBtn.prependTo(content);
overlay.add(closeBtn).click(function(){
content.fadeOut("slow",function(){
overlay.fadeOut("fast",function(){
content.appendTo(lightbox);
overlay.remove();
});
});
});

});
});
}
});
if($(".lightboxGallery").is("*")){
var thumbs = $(".lightboxGallery > img").add(".lightboxGallery div > img");
var overlay = $("<div class='lightboxOverlay'></div>");
var container = $("<div class='lightboxContainer'></div>");
var viewPort= $("<div class='lightboxViewport'></div>");
var captionBox= $("<div class='lightboxCaption'></div>");
var navRow= $("<div class='lightboxNavigation'></div>");
var closeBtn= $("<span class='closeBtn btn'></span>");
var prevBtn= $("<span class='prevBtn btn'></span>");
var nextBtn= $("<span class='nextBtn btn'></span>");
var winH= $(window).height();
var winW= $(window).width();
var currentImage= 0;
var currentScroll= 0;

$("body").append(overlay).append(container);
container.append(navRow).append(viewPort).append(closeBtn).append(captionBox);
navRow.append(prevBtn).append(nextBtn);
container.show().css({"top": Math.round((winH-container.outerHeight())/2) + "px","left": Math.round((winW-container.outerWidth())/2) + "px"}).hide();

thumbs.each(function(index){
 var theImg = $(this);
 theImg.click(function(){currentScroll = $("html").scrollTop(); overlay.add(container).fadeIn("slow"); loadImage(index);});
 theImg.hover(function(){theImg.fadeTo(500,0.6);},function(){theImg.fadeTo(400,1);});
 theImg.attr({"image-index": index});
});

function loadImage(imageIndex) {
  container.addClass("loadingImage");
var newImage = thumbs.eq(imageIndex);
var img = new Image();
img.onload = function() {
img.style.display = "none";

var maxWidth = winW-20-100;
var maxHeight = winH-20-200; 
if(img.width > maxWidth || img.height > maxHeight){
var ratio = img.width / img.height;
if(img.height >= maxHeight) {
img.height = maxHeight;
img.width = maxHeight*ratio;
}else{
img.width = maxWidth;
img.height = maxWidth*ratio;
}
}
container.animate({"width": img.width,"height": img.height,"top": Math.round((winH - img.height - 20)/2) + "px","left": Math.round((winW - img.width - 20)/2) + "px"},
600, function(){
viewPort.append(img);
$(img).fadeIn(500,function(){
captionBox.html((currentImage+1)+" / "+thumbs.size()+"<br/>"+newImage.attr("alt"));
container.removeClass("loadingImage");
container.animate({"height": (container.height() + captionBox.height() + 30) + "px"},"fast", function(){
captionBox.fadeIn(300,function(){closeBtn.fadeIn(200,function(){navRow.fadeIn(200);});});
});
});
});


} 
img.src = newImage.attr("src");
thumbs.filter(".selected").removeClass("selected");
newImage.addClass("selected");
currentImage = parseInt(thumbs.filter(".selected").attr("image-index"));
$.scrollTo("0px",800);
}

closeBtn.add(overlay).click(function(){
viewPort.children().fadeOut("normal",function(){viewPort.children().remove();});
overlay.add(container).add(closeBtn).add(captionBox).fadeOut("normal");
$.scrollTo(currentScroll+"px",500);
});

nextBtn.add(prevBtn).click(function(){
navRow.hide();
closeBtn.fadeOut("fast",function(){captionBox.fadeOut("fast");});
viewPort.children().fadeOut("normal",function(){viewPort.children().remove();});
if($(this).is(".prevBtn")){
loadImage(currentImage == 0 ? thumbs.size()-1 : currentImage-1);
}else{
loadImage(currentImage == (thumbs.size()-1) ? 0 : currentImage+1);
}
});

var lbImgs = $(".lightboxGallery.labels img");
lbImgs.each(function(i){
var image = $(lbImgs[i]);
var title = image.attr("alt");
var lightbox= image.parents(".lightboxGallery");
var wrapper= $("<div class='image-wrapper'></div>");
var label = $("<div class='text-label'>"+title+"</div>");
image.appendTo(wrapper);
if(title.length > 2){label.appendTo(wrapper);}
wrapper.appendTo(lightbox);
});

}
$("form#loginForm").keydown(function (event) {
if(event.keyCode == 13){
$(this).parent().find("form")[0].submit();
$(this).parent().html("Loading...").css({height : "60px", padding : "30px"}).addClass("AJAXloading").css("background-color","#fff");
}
});
   
$("#swlLoginA").click(function () {
$(this).parent().parent().parent().find("form")[0].submit();
$(this).parent().parent().parent().html("Loading...").css({height : "60px", padding : "30px"}).addClass("AJAXloading").css("background-color","#fff");
});

$("input#remind").click(function(){
var pswBox = $(this).parent().parent().find("div.loginPassword");

if(editionLCID==1053){
var remindBtnTxt = "Begär lösenord";
var loginBtnTxt= "Logga in";
}else{
var remindBtnTxt = "Request password";
var loginBtnTxt= "Login";
}

if($(this).is(":checked")){
pswBox.slideUp("fast")
$("#swlLoginA").html(remindBtnTxt);
}else{
pswBox.slideDown("fast")
$("#swlLoginA").html(loginBtnTxt);
}
});
ajaxRenewSession();
if($("#mainHoverMenu").is('*')){
$(".menu.level1").superfish({
hoverClass:    "hover-menu",
delay:         500,
animation:     {height:"show"},
speed:         "fast",
autoArrows:    true,
dropShadows:   true,
disableHI:     false
});
}
$(".multiupload").each(function () {
new MultiUpload(this);
});
var showHideBox = $(".show-hide-container");
if(showHideBox.is("*")){
showHideBox.find(".trigger-link").css({"cursor" : "pointer"});
showHideBox.find(".trigger-link").toggle(function(){
$(this).parents(".show-hide-container").find(".hidden-content").slideDown("normal");
  },function(){
$(this).parents(".show-hide-container").find(".hidden-content").slideUp("slow");
});
}
$(".slideShowGallery").each(function(slideIndex){
var currentSlide= $(this);
var currentImages= currentSlide.find("img");
if(currentImages.length>1){
var currentIndex = 0;
var currentImage = $(currentImages[currentIndex]);
var currentSpeed = currentSlide.find(".slide-show-config-speed > .config-val");
currentSpeed = (currentSpeed.is("*") ? parseInt(currentSpeed.text()) : 1200);
currentSpeed = (currentSpeed < 700 ? 700 : currentSpeed);
currentImages.each(function(index){$(this).data("image-index", index);});
  loadImage();
}
function loadImage(){
currentImages.hide();
currentSlide.animate({"height" : currentImage.height()+"px"},"slow","",function(){
currentImage.fadeIn(currentSpeed*1.2,function(){
setTimeout(function(){
currentImage.fadeOut(currentSpeed/2.3,function(){
currentIndex = (currentImage.data("image-index") == (currentImages.length-1) ? 0 : currentImage.data("image-index")+1);
currentImage = $(currentImages[currentIndex]);
loadImage();
});
},currentSpeed*4);
});
});
}
});
var systemMessage = $(".system-message-container");
if(systemMessage.is('*')){
varmessageDelay = Math.floor(systemMessage.find(".delay").text())*1000;
    systemMessage.fadeIn("slow");
setTimeout('clockSystemMessage2010()',1000);
}
$(".system-message-box").click(function(){systemMessage.fadeOut("slow");});
$(".system-message-box > .pause").click(function(){systemMessage.append("<span class='pause-delay'></span>");});
if($("div.systemMessageBox").is('*')){
   $("div.systemMessageBox").fadeIn("slow");
   $("div.systemMessageBox").animate({opacity: 0.7}, 2500);
}
setTimeout('hideSystemMessage()', 3000);
if(useTableSorter==true){
if($("table#mainDataTable").is('*')){
  if($("table#mainDataTable").tablesorter!=undefined){
$("table#mainDataTable").tablesorter({
 widgets: ['zebra']
});
   }
}
}
$("a.toolActivator").toggle(function () {
$("div.toolTip",this).show("slow");
},function () {
$("div.toolTip",this).hide("slow");
}); 
$(".helpIcon").toggle(function(){
$(this).parent().find(".helpBox").slideDown("fast");
},function(){
$(this).parent().find(".helpBox").slideUp("slow");
});
var isAutoCompleting;
$(".swlUserPicker > .search-field").focus(function () {
var searchField = $(this);
var idField= searchField.parent().find(".id-field");
if (searchField.val()=="Sök användare här" || searchField.val()=="Ingen användare vald"){
searchField.val("");
idField.val("0");
}
});
$(".swlUserPicker > .search-field").keyup(function () {

inputField = $(this);
inputStr= inputField.val()
formElement= inputField.parents("div:first");
resultWrapper = formElement.find(".auto-complete-results");
valueField= formElement.find(".id-field");
  
if( inputStr.length>2 && !isAutoCompleting ){
  isAutoCompleting = true;
  valueField.val(0);
  resultWrapper.addClass("loading");
  $.ajax({
url : "/core/coreSrc/ajax/user-picker.asp",
data : "userSearch="+inputStr+"&x="+Math.random(9999),
error : function(data,string) {alert(string);},
success : function (data) {
resultWrapper.css({opacity: "0.8"}).html(data).slideDown("slow",function(){
isAutoCompleting = false;
resultWrapper.removeClass("loading");
});
var results = resultWrapper.find(".user-result");
    results.each(function(i){
  $(this).bind("click",function(){
 var choosenUser = $(this);
 var choosenName= choosenUser.find(".the-name").text();
 var choosenID= choosenUser.find(".the-id").text();
valueField.val(choosenID);
inputField.val(choosenName);
resultWrapper.slideUp("slow");
  });
    });
}
  });
}

});
$(".swlUserPicker > .search-field").change(function () {
var searchField = $(this);
var idField= searchField.parent().find(".id-field");
setTimeout(function(){
$(".auto-complete-results").addClass("loading");
if (idField.val()==0 || idField.val()=="" || searchField.val().length<2){
searchField.val("Ingen användare vald");
idField.val("0");
}
$(".auto-complete-results").slideUp("fast");
},1000);
});

$(".swlTextValLen > input").keyup(function () {swlTextValLen(this);}); 
$(".swlTextValLen > textarea").keyup(function () {swlTextValLen(this);}); 
function swlTextValLen(theField){
if(theField.value.length < $(theField).attr("swlValLen")){
$(theField).removeClass("swlValidationOk");
$(theField).addClass("swlValidationWarning");
$(theField).parent().find("img.valOkIcon").css('display', 'none');
$(theField).parent().find("img.valWarningIcon").css('display', 'inline');
}else{
$(theField).removeClass("swlValidationWarning");
$(theField).addClass("swlValidationOk");
$(theField).parent().find("img.valWarningIcon").css('display', 'none');
$(theField).parent().find("img.valOkIcon").css('display', 'inline');
}
}

$(".swlTextValMaxLen > input").change(function () {swlTextValMaxLen(this);}); 
$(".swlTextValMaxLen > textarea").change(function () {swlTextValMaxLen(this);}); 
function swlTextValMaxLen(theField){
  inp = theField.value;
  inpField = theField;
$.ajax({
url : "/core/coreSrc/ajax/validateMaxLength.asp?input="+inp+"&len="+$(theField).attr("swlValMaxLen"),
success : function (data) {
inpField.value = data;
}
});
}

$(".swlEmailVal > input").keyup(function () {
  emailAddress = this.value;
  emailField = $(this);
$.ajax({
url : "/core/coreSrc/ajax/validateEmail.asp",
data : "email="+emailAddress,
error : function(data,string) {alert(string);},
success : function (data) {
  if(data=="validationError"){
emailField.removeClass("swlValidationOk");
emailField.addClass("swlValidationWarning");
emailField.parent().find("img.valOkIcon").css('display', 'none');
emailField.parent().find("img.valWarningIcon").css('display', 'inline');
  }else{
emailField.removeClass("swlValidationWarning");
emailField.addClass("swlValidationOk");
emailField.parent().find("img.valWarningIcon").css('display', 'none');
emailField.parent().find("img.valOkIcon").css('display', 'inline');
  }
}
});
}); 

$(".swlPhoneVal > input").change(function () {
  var inp  = this.value;
  var inpField  = this;
  var clsssField = $(this);
$.ajax({
url : "/core/coreSrc/ajax/validateTelephone.asp?input="+inp,
success : function (data) {
inpField.value = data;
clsssField.addClass("swlValidationOk");
clsssField.parent().find("img.valOkIcon").css('display', 'inline');
}
});
}); 

$(".swlTimeVal > input").change(function () {
  var inp  = this.value;
  var inpField  = this;
  var clsssField = $(this);
$.ajax({
url : "/core/coreSrc/ajax/validateTime.asp?input="+inp,
success : function (data) {
inpField.value = data;
clsssField.addClass("swlValidationOk");
clsssField.parent().find("img.valOkIcon").css('display', 'inline');
}
});
}); 

$(".swlURLVal > input").change(function () {
  url = this.value;
  urlField = $(this);
  urlField.parent().find("img.valWarningIcon").attr('src', 'http://www.smode-resource.se/gfx/icons/ajax-loader.gif').css({'display': 'inline','width' :'20px'});
$.ajax({
url : "/core/coreSrc/ajax/validateURL.asp?url="+url,
success : function (data) {
  if(data=="validationError"){
urlField.parent().find("img.valWarningIcon").attr('src', 'http://www.smode-resource.se/gfx/icons/icon_varning.gif');
urlField.removeClass("swlValidationOk");
urlField.addClass("swlValidationWarning");
urlField.parent().find("img.valOkIcon").css('display', 'none');
urlField.parent().find("img.valWarningIcon").css('display', 'inline');
  }else{
urlField.removeClass("swlValidationWarning");
urlField.addClass("swlValidationOk");
urlField.parent().find("img.valWarningIcon").css('display', 'none');
urlField.parent().find("img.valOkIcon").css('display', 'inline');
  }
}
});
}); 

$(".swlPasswordVal > input").keyup(function () {
  passw = this.value;
  passwField = $(this);
$.ajax({
url : "/core/coreSrc/ajax/validatePassword.asp?password="+passw,
success : function (data) {
  if(data=="validationError"){
passwField.removeClass("swlValidationOk");
passwField.addClass("swlValidationWarning");
passwField.parent().find("img.valOkIcon").css('display', 'none');
passwField.parent().find("img.valWarningIcon").css('display', 'inline');
  }else{
passwField.removeClass("swlValidationWarning");
passwField.addClass("swlValidationOk");
passwField.parent().find("img.valWarningIcon").css('display', 'none');
passwField.parent().find("img.valOkIcon").css('display', 'inline');
  }
}
});
}); 

$(".swlOnlyDigits > input").change(function () {
  var inp  = this.value;
  var inpField  = this;
  var clsssField = $(this);
$.ajax({
url : "/core/coreSrc/ajax/validateOnlyDigit.asp?input="+inp,
success : function (data) {
inpField.value = data;
clsssField.addClass("swlValidationOk");
clsssField.parent().find("img.valOkIcon").css('display', 'inline');
}
});
}); 


});
