/** Put functions which needs to run on every page load between $(document).ready below...**/
$(document).ready(function(){

$('#userFeedbackMessage').hide();
$('#userFeedbackMessage').fadeIn(1200);

$("body span, option").each(function(i) {
var el = $(this);

if (el.html().indexOf("{txt:") == 0) { // Is a text resource replacement string
$.get("APP_UE.P.getTr?pi_str="+$(this).html()+"&pi_lang="+$('#P0_APP_LANGUAGE').val(),function(data) {


//el.html('<span style="color: black !important;">' + data + '</span>'); // Used for detecting text resources
el.html(data); // If not detecting text resources, use this


});
}

});

// added for the sum report issue
$("b").each(function(i) {
var el = $(this);

if (el.html().indexOf("{txt:") == 0) { // Is a text resource replacement string
$.get("APP_UE.P.getTr?pi_str="+$(this).html()+"&pi_lang="+$('#P0_APP_LANGUAGE').val(),function(data) {


el.html('<span style="color: black !important;">' + data + '</span>'); // Used for detecting text resources
//el.html(data); // If not detecting text resources, use this


});
}

});

$("title").each(function(i) {
var el = $(this);
if ($(this).html().indexOf("{txt:") > -1) {
$.get("APP_UE.P.getTr?pi_str="+$(this).html()+"&pi_lang="+$('#P0_APP_LANGUAGE').val(),function(data) {
document.title=jQuery.trim(data);
});}});

});

/** End page load functions **/

function getCityByZipcode(indiv,outdiv) {

$.get("/a/zipcode/"+$('#'+indiv).val(), {} , function(data){
    $('#'+outdiv).val(data);
    $('#'+outdiv).html(data);
  });

}


function changeLanguage(itemId,lang) {
$('#'+itemId+'_NN').hide();
$('label[for="'+itemId+'_NN"]').hide();
$('#button_NN').removeClass("current");

$('#'+itemId+'_EN').hide();
$('label[for="'+itemId+'_EN"]').hide();
$('#button_EN').removeClass("current");

$('#'+itemId+'_NO').hide();
$('label[for="'+itemId+'_NO"]').hide();
$('#button_NO').removeClass("current");

$('#'+itemId+'_'+lang).show();
$('label[for="'+itemId+'_'+lang+'"]').show();
$('#button_'+lang).addClass("current");

}

function toggle(item) {

$('#'+item).toggle();

}

function changeLanguageArticle(item1,item2,item3,language) {
/*
changeLanguage(item1,language);
changeLanguage(item2,language);
changeLanguage(item3,language);
*/
changeLanguage('article',language);

}

function showReportMenu(id) {
 if ($('#reportMenu' + id + ' ul').css("display") == "block") {
 $('#reportMenu' + id + ' ul').hide();
 } else {
 $('.reportMenu ul').hide();
 $('#reportMenu' + id + ' ul').show();
 }
}

// starts up the datepicker
$(document).ready(function(){
$(".dateSelector").datepicker();  
$.datepicker.setDefaults($.datepicker.regional['no']);
setFormLanguage('bokmaal');
});

/** Function used for language switching in forms in admin **/
function setFormLanguage(language) {
$('.switchlinks .currentFormLanguage').removeClass('currentFormLanguage');
$('.l_bokmaal,.l_nynorsk,.l_english').hide();
$('.l_'+language).show();
$('.switchlink_'+language).addClass('currentFormLanguage');
$('.switchlink_'+language).blur();
}

/** Function used for shoe hide divs**/
function showDiv(isVisible) {
$('.show').addClass('hidden');
$('.show').removeClass('show');
$('#'+isVisible).removeClass('hidden');
$('#'+isVisible+'_BTN').removeClass('hidden');
$('#'+isVisible).addClass('show');
$('#'+isVisible+'_BTN').addClass('show');
$('.hidden').hide();
$('.show').show();
$('.switchlinks .currentFormLanguage').removeClass('currentFormLanguage');
$('.switchlink_'+isVisible).addClass('currentFormLanguage');
$('.switchlink_'+isVisible).blur();
}

/** Function used to calc the vat and net from a gross price**/
function calcNet(price_item,net_item,vat) {
/** Change the desimal seperator from , to . **/
$('#'+price_item).val($('#'+price_item).val().replace(',','.'));
//$('#'+net_item).val(parseFloat($('#'+price_item).val()) - ((parseFloat($('#'+price_item).val()) * vat)/100));
$('#'+net_item).val(parseFloat($('#'+price_item).val()) / ((100 + vat)/100));

/** Change the desimal seperator from . to , **/
$('#'+net_item).val(roundNumber($('#'+net_item).val(),2));
$('#'+net_item).val($('#'+net_item).val().replace('.',','));
$('#'+price_item).val($('#'+price_item).val().replace('.',','));
}

/** Function used to calc the gross price from a net price**/
function calcGross(price_item,gross_item,vat) {
/** Change the desimal seperator from , to . **/
$('#'+price_item).val($('#'+price_item).val().replace(',','.'));
//$('#'+gross_item).val(parseFloat($('#'+price_item).val()) / ((100 - vat)/100));
$('#'+gross_item).val(parseFloat($('#'+price_item).val()) * (100 + vat)/100);

/** Change the desimal seperator from . to , **/
$('#'+gross_item).val(roundNumber($('#'+gross_item).val(),2));
$('#'+gross_item).val($('#'+gross_item).val().replace('.',','));
$('#'+price_item).val($('#'+price_item).val().replace('.',','));
}

function numberWith2decimal(item){
$('#'+item).val($('#'+item).val().replace(',','.'));
$('#'+item).val(roundNumber($('#'+item).val(),2));
$('#'+item).val($('#'+item).val().replace('.',','));
}


/** Standard popup **/
function uePopup(url,title) {
	window.open(url,title);
}

function closePopupAndSetValue(valueItemName,valueItemValue,displayItemName,displayItemValue) {
	window.opener.$('#'+valueItemName).val(valueItemValue);
	window.opener.$('#'+displayItemName).html(displayItemValue);
	window.close();
}

function showOrHideItem(itemName1,itemName2, itemName3, isVisible) {
	if (isVisible == 1){	
	$('#'+ itemName1).show();
	$('#'+ itemName2).hide();
	$('#'+ itemName3).show();
	}
	else{
	$('#'+ itemName2).show();
	$('#'+ itemName1).hide();
	$('#'+ itemName3).hide();
	}
}

/** This function hides or shows the two pair of items**/
function showOrHidePairOfItems(itemNamePair1_1,itemNamePair1_2, itemNamePair2_1, itemNamePair2_2, isVisible) {
	if (isVisible == 1){	
	$('#'+ itemNamePair1_1).show();
	$('#'+ itemNamePair1_2).show();
	$('#'+ itemNamePair2_1).hide();
	$('#'+ itemNamePair2_2).hide();
	}
	else{
	$('#'+ itemNamePair1_1).hide();
	$('#'+ itemNamePair1_2).hide();
	$('#'+ itemNamePair2_1).show();
	$('#'+ itemNamePair2_2).show();
	}
}

/** Send user to another URL **/
function gotoUrl(url) {
	location.href = url;
}


// Activate is true/false .. if true, files will be set active at once. If not, files
// will have to be activated after uploading
function updateAttachmentsAndActivateNotDeletable(pi_ownerType,pi_ownerId) {
	$.get("APP_UE.P.getAttachments?pi_ownerId="+pi_ownerId+"&pi_ownerType="+pi_ownerType+"&pi_activate=1&pi_deletable=0&pi_randomSeed="+Math.ceil(Math.random()*1000000),function(data) {
		$('#fileAttachments_'+pi_ownerType).html(data);		
	});	
}


function updateAttachmentsAndActivate(pi_ownerType,pi_ownerId) {
	$.get("APP_UE.P.getAttachments?pi_ownerId="+pi_ownerId+"&pi_ownerType="+pi_ownerType+"&pi_activate=1&pi_randomSeed="+Math.ceil(Math.random()*1000000),function(data) {
		$('#fileAttachments_'+pi_ownerType).html(data);		
	});	
}

function updateAttachments(pi_ownerType,pi_ownerId) {
	$.get("APP_UE.P.getAttachments?pi_ownerId="+pi_ownerId+"&pi_ownerType="+pi_ownerType+"&pi_activate=0&pi_randomSeed="+Math.ceil(Math.random()*1000000),function(data) {
		$('#fileAttachments_'+pi_ownerType).html(data);		
	});	
}


function renameAttachment(fileId,ownerType,ownerId) {
	var filename = prompt("Skriv inn nytt filnavn. Filetternavn blir lagt til automatisk.");
	if (filename==null || filename=="" || filename == " ") {
		
	} else {
	/*
		$.get("APP_UE.P.renameAttachment?pi_fileId="+fileId+"&pi_fileTitle="+filename,function(data) {
			updateAttachments(ownerType,ownerId);
		});
	*/
	}
}

function deleteAttachment(fileId,ownerType,ownerId,activate) {
	if (activate) {
		$.get("APP_UE.P.getTr?pi_str={txt:confirmDeleteAttachment}&pi_lang="+$.cookie("UE_USER_LANGUAGE"),function(data) {
			if (confirm(data)) {
				$.get("APP_UE.P.deleteAttachment?pi_fileId="+fileId+"&pi_permanent=1"),function(data) {}
				updateAttachments(ownerType,ownerId,activate);
				//doSubmit('P4552_HID_INSTITUTION_ID');
			}
		});
	} else {
		$.get("APP_UE.P.getTr?pi_str={txt:confirmDeleteAttachment}&pi_lang="+$.cookie("UE_USER_LANGUAGE"),function(data) {
			if (confirm(data)) {
				$('#P0_DELETED_ATTACHMENTS').val(
					$('#P0_DELETED_ATTACHMENTS').val() + fileId + ";");
				$('#fileAttachment_'+ownerType+'_' + fileId).addClass("deletedAttachment");
				//doSubmit('P4552_HID_INSTITUTION_ID');
			}
		});
	}
}

function getPopupTextForContinueButtonP3400() {
	$.get("APP_UE.P.getTr?pi_str={txt:P3400PopupTextForContinueButton}&pi_lang="+$.cookie("UE_USER_LANGUAGE"),function(data) {
		if (confirm(data)) {
			return true;
		}
	});
}

function updateIllustrationPreviewImage(ownerType,ownerId) {
	$.get("APP_UE.P.getFileNameByOwner?pi_ownerType="+ownerType+"&pi_ownerId="+ownerId,function(data) {
		$('#illustrationImagePreview').html("<img src='/f/"+data+"' />");
	});
}

function selectCounty() {
	$('#sidebarCountySelectorBox').css("display","block");
	$('#sidebarCountySelector').blur();
	$('#sidebarCountySelector a.selector').addClass("selectorActive");
	$('#sidebarCountySelector').bind("mouseleave",function() {
		$('#sidebarCountySelector a.selector').removeClass("selectorActive");
		$('#sidebarCountySelectorBox').css("display","none");
	});
}

function selectWebtvCategory() {
	$('#webtv_dropdownlist').css("display","block");
	$('#webtv_dropdown #selector').blur();
	$('#webtv_dropdownlist').bind("mouseleave",function() {
		$('#webtv_dropdownlist').css("display","none");
	});
}

function setWebTvCategory(cat) {
	$('#webtv_dropdownlist').css("display","none");
    if (cat.category_id == undefined) { // Special category
        if (cat.special_category=="most_viewed") {
            updateWebTvMovieListingMostViewed();
        } else if (cat.special_category=="published_date") {
            updateWebTvMovieListingLatest();
        }
    } else { // Category ID
        updateWebTvMovieListing(cat.category_id);
    }
    
    updateWebTvDropdown(cat);
}

function updateWebTvDropdown(cat) {
    $.get("APP_UE.P.getWebTvDropdownLinks?pi_category="+cat.category_id,function(data) {
        $('#webtv_dropdownlist').html(data);
    });
}

function updateWebTvMovieListing(id) {
    // Insert ajax function here to print movies for this category id
    $.get("APP_UE.P.getWebTvMoviesForCategory?pi_categoryId="+id,function(data) {
        $('#webtv_sidebarcontent').html(data);
    });
    
    $.get("APP_UE.P.getWebTvCategoryTitle?pi_categoryId="+id,function(data) {
        $('#webtv_dropdown #selector').html(data);
    });
}

function updateWebTvMovieListingMostViewed() {
    // Insert ajax function here to print most viewed list
    $('#webtv_sidebarcontent').html('most viewed');
    $('#webtv_dropdown #selector').html('Mest populære');
}

function updateWebTvMovieListingLatest() {
    $.get("APP_UE.P.getWebTvMoviesByDate",function(data) {
        $('#webtv_sidebarcontent').html(data);
    });
    
    $('#webtv_dropdown #selector').html("Sist publiserte");
}

function playWebTvMovie(id) {    
    $.get("APP_UE.P.getWebTvMoviePlayer?pi_movieId="+id,function(data) {
       $('#webtv_movie').html(data);  
       $('#webtv_sidebarcontent .current').removeClass("current");
       $('#movie_'+id).addClass("current");
    });
}

function webTvOnLoad() {
    var myFile = document.location.toString();
    var anchor = myFile.split('#')[1]
    
    if (anchor!=undefined) {
        if (anchor.match("movie_")) {
            $.get("APP_UE.P.getWebTvMovieCategoryId?pi_movieId="+anchor.split('movie_')[1],function(data) {
                updateWebTvMovieListing(data);
                playWebTvMovie(anchor.split('movie_')[1]);
            });
        }
    } else {
        updateWebTvMovieListingLatest();
    }
    
    updateWebTvDropdown({category_id:1});
}

function roundNumber(number,decimal_points) {
	if(!decimal_points) return Math.round(number);
	if(number == 0) {
		var decimals = "";
		for(var i=0;i<decimal_points;i++) decimals += "0";
		return "0."+decimals;
	}

	var exponent = Math.pow(10,decimal_points);
	var num = Math.round((number * exponent)).toString();
	return num.slice(0,-1*decimal_points) + "." + num.slice(-1*decimal_points)
}

function limitChars(textid, limit) {
	var text = $('#'+textid).val(); 
	var textlength = text.length;

	if(textlength > limit) {
		$('#'+textid).val(text.substr(0,limit));
		return false;
	} else {
		return true;
	}
}

$(function(){

$('.webshopAmount').keyup(function(){

    var text = $(this).val();
    var textlength = text.length;

    if (textlength > 2) {
	$(this).val(text.substr(0,2));
    }

})

});

function setEditArticlePublishFromDate() {
    if ($('#P4701_TXT_PUBLISH_FROM').val().length==0) {
        $('#P4701_TXT_PUBLISH_FROM').val($('#P4701_HID_TODAYS_DATE').val());
    }
}

function clearEditArticlePublishFromDate() {
    $('#P4701_TXT_PUBLISH_FROM').val('');
}

function autoCompleteFindValForPersonId(li) {
	if( li == null ) return alert("No match!");

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

        $('#P3103_TXT_STUDENT').removeClass("inputInvalid");
        $('#P3103_TXT_STUDENT').addClass("inputValid");
	$('#P3103_HID_PERSON_ID').val(sValue);
	//alert(sValue);
}

function autoCompleteSelectItemForPersonId(li) {
	autoCompleteFindValForPersonId(li);
}

function autoCompleteFindValForPersonId_2(li) {
	if( li == null ) return alert("No match!");

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

        $('#P4607_TXT_PERSON').removeClass("inputInvalid");
        $('#P4607_TXT_PERSON').addClass("inputValid");
	$('#P4607_HID_PERSON_ID').val(sValue);
	//alert(sValue);
}

function autoCompleteSelectItemForPersonId_2(li) {
	autoCompleteFindValForPersonId_2(li);
}

function autoCompleteFindValue(li) {	
	if( li == null ) return alert("No match!");

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

        $('#P1102_TXT_INSTITUTION_NAME').removeClass("inputInvalid");
        $('#P1102_TXT_INSTITUTION_NAME').addClass("inputValid");
	$('#P1102_HID_INSTITUTION_ID').val(sValue);
	//alert(sValue);
}

function autoCompleteSelectItem(li) {
	autoCompleteFindValue(li);
}

/*
For use in user edit in admin application
*/
function autoCompleteFindValue2(li) {
	if( li == null ) return alert("No match!");

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

        $('#P5901_TXT_INSTITUTION_NAME').removeClass("inputInvalid");
        $('#P5901_TXT_INSTITUTION_NAME').addClass("inputValid");
        $('#P5901_HID_INSTITUTION_ID').val(sValue);
	//alert(sValue);
}

/*
For use in user edit in admin application
*/
function autoCompleteSelectItem2(li) {
	autoCompleteFindValue2(li);
}

/*
For use in program activity in admin application
*/
function autoCompleteFindValue3(li) {
	if( li == null ) return alert("No match!");

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

        $('#P4552_TXT_INSTITUTION_NAME').removeClass("inputInvalid");
        $('#P4552_TXT_INSTITUTION_NAME').addClass("inputValid");
        $('#P4552_HID_INSTITUTION_ID').val(sValue);
        doSubmit('P4552_HID_INSTITUTION_ID');
	//alert(sValue);
}

/*
For use in program activity in admin application
*/
function autoCompleteSelectItem3(li) {
	autoCompleteFindValue3(li);
}

/*
For use in create company in admin application
*/
function autoCompleteFindValue4(li) {
	if( li == null ) return alert("No match!");

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

        $('#P5204_TXT_INSTITUTION_NAME').removeClass("inputInvalid");
        $('#P5204_TXT_INSTITUTION_NAME').addClass("inputValid");
        $('#P5204_HID_INSTITUTION_ID').val(sValue);        
	//alert(sValue);
}

/*
For use in create company in admin application
*/
function autoCompleteSelectItem4(li) {
	autoCompleteFindValue4(li);
}

/*
For use in create public event registration
*/
function autoCompleteFindValue5(li) {
	if( li == null ) return alert("No match!");

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

        $('#P1301_INSTITUTION').removeClass("inputInvalid");
        $('#P1301_INSTITUTION').addClass("inputValid");
        $('#P1301_HID_INSTITUTION_ID').val(sValue);        
	//alert(sValue);
}

/*
For use in create public event registration
*/
function autoCompleteSelectItem5(li) {
	autoCompleteFindValue5(li);
}

function hideSidebar() {
    $('#sidebar').hide();
    $('#mainContent.oneCol').css("width","880px");
    $('.contentBox').css("width","100%");
    $('#breadcrumbs').css("width","880px");
    $('.scrollable').css("width","870px");
    $('#showSidebarLink').show();
}

function showSidebar() {
    $('#sidebar').show();
    $('#mainContent.oneCol').css("width","643px");
    $('.contentBox').css("width","643px");
    $('#breadcrumbs').css("width","643px");
    $('.scrollable').css("width","640px");
    $('#showSidebarLink').hide();
}

function navigateToPage(appId, pageId) {  
  location.href="f?p=" + appId + ":" + pageId;
  doSubmit('Search');
}

function getAvailableOrgNo(item) {
$.get("APP_UE.P.getAvailableOrgNo",function(data) {
        $('#'+item).val(data);
    });

}

function maxCountValidation() {
//var maxCount;

$.get("APP_UE.P.getMaxRowCount",function(data) {
        //$('#maxCount').val(data);
        var maxCount = data;
        alert(maxCount);
        //alert(data);
    });
    //alert(maxCount);
}

/*
Functions for event connection items
*/
function setNoEventConnection() {
$('#noEventConnection').attr('checked','checked');
$('#eventProgramConnection').attr('checked','');
$('#eventActivityConnection').attr('checked','');
$('#eventProgram').hide();
$('#eventActivityType').hide();
$('#eventCountyProgram').hide();
$('#P4602_CMB_PROGRAM').val('');
$('#P4602_CMB_ACTIVITY_TYPE').val('');
$('#P4602_CMB_COUNTY_PROGRAM').val('');
}

function setProgramConnection() {
$('#eventProgramConnection').attr('checked','checked');
$('#noEventConnection').attr('checked','');
$('#eventActivityConnection').attr('checked','');
$('#eventProgram').show();
$('#eventActivityType').hide();
$('#eventCountyProgram').hide();
$('#P4602_CMB_ACTIVITY_TYPE').val('');
$('#P4602_CMB_COUNTY_PROGRAM').val('');
}

function setActivityTypeConnection() {
$('#eventActivityConnection').attr('checked','checked');
$('#eventProgramConnection').attr('checked','');
$('#noEventConnection').attr('checked','');
$('#eventProgram').hide();
$('#eventActivityType').show();
$('#P4602_CMB_PROGRAM').val('');
}

function setCountyProgramConnection() {

	// show the county program field if activity type is county program (4)
	if ($('#P4602_CMB_ACTIVITY_TYPE').val() == 4){
		$('#eventCountyProgram').show();
	}
	else{
		$('#eventCountyProgram').hide();
		$('#P4602_CMB_COUNTY_PROGRAM').val('');
	}
}
/*
End Functions for event connection items
*/

function setFileAsHasBeenOpened(pi_ownerType,pi_ownerId) {
$.get("APP_UE.P.setFileAsHasBeenOpened?pi_ownerType="+pi_ownerType+"&pi_ownerId="+pi_ownerId,function(data) {
    });
}

function reloadToDoList(pi_companyId) {
$.get("APP_UE.P.getToDoListHTML?pi_companyId="+pi_companyId,function(data) {
  jQuery("#RGN_TO_DO_LIST").html(data);
    });
}

function showImageCategoryInput() {
	$("#newCategoryContainer").show();
	$("#categoryLinks").hide();
}

function addImageCategory(parentId,institutionId,fileTypeId) {
	var title = $("#imageCategoryName").val();

	if (title==null) {
		return;
	}

	$.get("APP_UE.P.addImageCategory?pi_fileTypeId="+fileTypeId+"&pi_categoryTitle="+title+"&pi_parentId="+parentId+"&pi_institutionId="+institutionId,function(data) {
		window.location.reload();
	});
}