// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}

//081222 dan - changes for the AT search
function quickSearch(query ,type ){
    var query = encodeURIComponent(query);

	var newAddress="";
    if(query != ''){
		if (type == ''){
			newAddress = '/ServiceTools/Search.aspx?q=' + query+ "&sortorder=asc";

		}
		else{
			var loc = location.href;
			var arrayloc = loc.split('/');
			
			/*var url = loc.substring(0,loc.length-5);*/
			var url = '';
			for(var i = 0; i < 4; i++){
				url = url + arrayloc[i] +'/';
			}

			if (arrayloc.length > 5)
				url = url + arrayloc[4];
			else
				url = url + arrayloc[4].substring(0, arrayloc[4].length - 5);

			newAddress = url + '/ServiceTools/Search.aspx?q=' + query+ "&sortorder=asc";
				
		}
		
	/*	if (trim(category!='') && (trim(category!='0')) )
			{
				newAddress +="&mc=scCategory=:"+category;
			}
			if (trim(subCategory!='') && (trim(subCategory!='0')) )
			{
				newAddress +="&mc=scSubCategory=:"+subCategory;
			} */
		location.href  = newAddress;
    }   
}

//081222 dan - added for the BM search
function changeSearchCateg()
{
	var query ='/ServiceTools/Search.aspx';

	var txtSearchValue="";
	var txtSearch = document.getElementById("txtPageSearch");
	if (txtSearch != null )
	{
		txtSearchValue = txtSearch.value;
	}

//090217 mrr - for now we don't have subcategories, onyl categories
    //txtSearchValue="";
	var searchCategoryValue="";
	var searchSubCategoryValue="";
	if (trim(txtSearchValue)!='')
	{
		 query+='?q='+encodeURIComponent(txtSearchValue);
		
		var searchCategory = document.getElementById("searchCategory");
		if (searchCategory != null )
		{
			searchCategoryValue = searchCategory.value;
			query+='&categ='+searchCategoryValue;
		}
		var searchSubCategory = document.getElementById("searchSubCategory");
		if ((searchSubCategory != null)  && (trim(searchCategoryValue) !='0'))
		{
			searchSubCategoryValue = searchSubCategory.value;
			query+='&subCateg='+searchSubCategoryValue;
		}
		
	location.href=query;
	}
}

//081222 dan - changed for the BM search
function doSearch()
{
	var query = location.href;
	var urlarray = query.split('?');
	var urlf = urlarray[0];
	
	var txtSearch = document.getElementById("txtPageSearch");
	if (txtSearch != null )
	{
		txtSearchValue = txtSearch.value;
	}
	

	var searchCategoryValue="";
	var searchSubCategoryValue="";
	if (trim(txtSearchValue)!='')
	{
		query = urlf + "?q=" +encodeURI(txtSearchValue)+'&l=1';
		 
		var searchCategory = document.getElementById("searchCategory");
		if (searchCategory != null ) 
		{
			searchCategoryValue = searchCategory.value;
			query+='&categ='+searchCategoryValue;
			
			/*if (trim(searchCategoryValue) !='0')
			{
				query+='&mc=scCategory=:'+searchCategoryValue;
			}	*/
		}
		var searchSubCategory = document.getElementById("searchSubCategory");
		if ((searchSubCategory != null)  && (trim(searchSubCategoryValue) !='0'))
		{
			searchSubCategoryValue = searchSubCategory.value;
			query+='&subCateg='+searchSubCategoryValue;
			
			/*if (trim(searchSubCategoryValue) !='0')
			{
				query+='&mc=scSubCategory=:'+searchSubCategoryValue;
			} */
			
		}
	}	
	
	location.href=query;
}

//110330 dan - AT
function doSearch2()
{
	var query = location.href;
	var urlarray = query.split('?');
	var urlf = urlarray[0];
	
	var txtSearch = document.getElementById("txtPageSearch");
	if (txtSearch != null )
	{
		txtSearchValue = txtSearch.value;
	}
	

	var searchCategoryValue="";
	if (trim(txtSearchValue)!='')
	{
		query = urlf + "?q=" +encodeURI(txtSearchValue)+'&l=1';
		 
		var searchCategory = document.getElementById("searchCategory");
		if (searchCategory != null ) 
		{
			searchCategoryValue = searchCategory.value;
			query+='&categ='+searchCategoryValue;
		}
	}	
	
	location.href=query;
}

//080105 dan - added some new functions

function checkEnter(e,caller) //e is event object passed from function invocation
{

	var characterCode //literal character code will be stored in this variable

	if(e && e.which ||e.which == 0)
	{ //if which property of event object is supported (NN4)
	
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	}
	else
	{
		e = event;
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}

	if(characterCode == 13)//if generated character code is equal to ascii 13 (if enter key)
	{ 
	    if(document.all){
		    e.returnValue=false;
            e.cancel = true;
        }
        else{
         e.preventDefault();
        }
        var obj = document.getElementById(caller);
        if(obj){        
            
            if(obj.click){
		        obj.click();
		    }
		}
		return false;
	}
	else
	{
		return true;
	}
		
}

function groupSearch(startPage, resultsPerGroup, resultPage){
   
	//searchStr = encodeURI(searchStr);
	var query = location.href;
	var urlarray = query.split('?');
	var urlf = urlarray[0];
	
	var txtSearch = document.getElementById("txtPageSearch");
	if (txtSearch != null )
	{
		txtSearchValue = txtSearch.value;
	}
	
	var searchCategoryValue="";
	var searchSubCategoryValue="";
	if (trim(txtSearchValue)!='')
	{
		query = urlf + "?q=" +encodeURI(txtSearchValue)+ '&l=' + startPage + '&results=' + resultsPerGroup;
		 
		var searchCategory = document.getElementById("searchCategory");
		if (searchCategory != null ) 
		{
			searchCategoryValue = searchCategory.value;
			query+='&categ='+searchCategoryValue;
			
			/*if (trim(searchCategoryValue) !='0')
			{
				query+='&mc=scCategory=:'+searchCategoryValue;
			}	 */
		}
		var searchSubCategory = document.getElementById("searchSubCategory");
		if ((searchSubCategory != null)  && (trim(searchSubCategoryValue) !='0'))
		{
			searchSubCategoryValue = searchSubCategory.value;
			query+='&subCateg='+searchSubCategoryValue;
			
			/*if (trim(searchSubCategoryValue) !='0')
			{
				query+='&mc=scSubCategory=:'+searchSubCategoryValue;
			} */
			
		}
	}	
	location.href=query;
	
}

function openPopUp(pUrl, title) {	
	window.open(pUrl,"","width=420,height=450,resizable,scrollbars=no,status=1");
}

function newsCategoryDropDown(){
	
	var newsCatElem = document.getElementById("newsCateg");
	if (newsCatElem.selectedIndex>0){
		location.href='?newsCategoryID='+ newsCatElem.options[newsCatElem.selectedIndex].value;
	}
	else
	{
		location.href = location.href.split('?')[0];
	}
	
	//location.href='?newsCategoryID='+ this.options[this.selectedIndex].value;
}

function catThemeOnClick(newurl){
	if (newurl != '')
		location.href = newurl;
}

function getKeyTF(evt, element) {
    /*
	if (evt && ns6)
		typedKey=evt.which;
	else
		typedKey=event.keyCode;    
    */
    
    var typedKey = null;
	if(evt && evt.which)
	{ //if which property of event object is supported (NN4)
		//e = e ?? 
		typedKey = evt.which //character code is contained in NN4's which property
	}
	else
	{		
		typedKey = event.keyCode; //character code is contained in IE's keyCode property
	}

	if (typedKey == 13) {	    
		if(document.all) {
			window.event.cancelBubble='true';
		    window.event.returnValue = false;
		} else {
			evt.stopPropagation();
		    evt.preventDefault();
		}
		
		if (element.id == "tbxFromMail"){
			document.getElementById("tbToMail").focus();
		}
		else{
			if (element.id == "tbToMail"){
				document.getElementById("tbBody").focus();
			}
			else{
				if (element.id == "tbBody"){
					//document.getElementById("btSend").focus();
				}
				else{
					if (element.id == "btSend"){	
						document.getElementById("btSend").click();
					}
				}
			}
		}
		
		
		//document.getElementById("btSend").click();
	 }
}

// 090302 dan- added for the search syle 
function seeWithStyle(newLocation) 
{
	var txtSearchValue="";
	var txtSearch = document.getElementById("txtPageSearch");
	if (txtSearch != null )
	{
		txtSearchValue = txtSearch.value;
	}
    if (txtSearchValue!='')
	{
	  
		//alert(printlink);
		var oldurl = newLocation + "?";
		var stringHref = oldurl.split("?");
		var url;
		if (stringHref[1] != "")
			url = newLocation + "&s="+encodeURIComponent(txtSearchValue);
		else
			url = newLocation+ "?s="+encodeURIComponent(txtSearchValue);
		
		//alert(url);
		location.href = url;
	}
}

function getURL()
{
    var objc;    
    if (location.href.indexOf('?')>0)
      {
        objc=location.href+'&p=1';
      }
      else
        objc=location.href+'?p=1';
    window.open(objc);
}
    
function getPopUp()
{
    var obj = '/TellAFriend.aspx?url='+location.href;
    obj = obj.replace("~", "%7E");
    obj = obj.replace("~", "%7E");
    openPopUp(obj, 'Send mail to a friend');
}  


//used for Search
function Search()
{
    curQuery = location.search.replace(/[?&]q=[^&]*/,"").replace(/[?&;]p=[^&]*/,"").replace(/^[?&]?(?!$)/,"&");
    location.href='/ServiceTools/Search.aspx?q=' + encodeURI(document.getElementById('searchTxt').value.replace(/\+/g,'%2b')+curQuery);
    return false;
}

 function CheckSearch(valueSearch)
{
    if (document.getElementById('searchTxt').value!=valueSearch) 
    {
      Search(); 
      return true;
    }
    return false;
}

//function getFormularPopUp(url)
//{
//    if(location.href.indexOf("errorMessage")>=0){    
//        var obj = location.href;
//        var objqs = obj.split('?')[1];
//        if(objqs && (location.href.indexOf("errorPop")<0)){         
//            objqs += "&errorPop=true";
//            openPopUp('/gicTest/gicErrorTest.aspx?' + objqs, 'Send mail to a friend');
//        }
//    }
//    else{
//        if(location.href.indexOf("formular")>=0){
//             
//            var obj = '/gicTest.aspx';
//            formularwindow = window.open (obj, "formularwindow","location=1,status=1,scrollbars=1,width=800,height=400");
//            formularwindow.moveTo(0,0);
//        }
//    }
//} 

function getFormularPopUp(url)
{
    if(location.href.indexOf("errorMessage")>=0){    
        var obj = location.href;
        var objqs = obj.split('?')[1];
        if(objqs && (location.href.indexOf("errorPop")<0)){         
            objqs += "&errorPop=true";
            openPopUp('/gicTestWithPagination/Error.aspx?' + objqs, 'Send mail to a friend');
        }
    }
    else{
        //if(location.href.indexOf("formular")>=0){
        if(url.indexOf("formular")>=0){
            var obj = url;
            formularwindow = window.open (obj, "formularwindow","width=600,height=950,status=yes,toolbar=no,menubar=no,location=no, scrollbars=1");
            //openPopUp(obj, "formularwindow","location=1,status=1,scrollbars=1,width=600,height=650");
            
            //formularwindow.moveTo(0,0);
        }
    }
}

//added by LDU

function EnableFormularRadioButtonSubfields(parentClass) {
    //alert("merge");
    
    //$(':input:visible').each(function(i,e){$(this).attr('tabindex', i);});

    $("." + parentClass + " input:checked").each(function(i, e) {
        onclickattr = $(this);
        splitedAttributes = onclickattr[0].getAttributeNode('onclick').value.split(',');
        if ($(this).val() == "Ja") {
            //alert("'" + splitedAttributes[0].split("'")[1] + "'" + "," + splitedAttributes[1] + "," + "'" + splitedAttributes[2].split("'")[1] + "'");
            //alert(onclickattr + "                " + $(this).val(), splitedAttributes[1], splitedAttributes[2]);
            getFormularRadioButton(splitedAttributes[0].split("'")[1], splitedAttributes[1].split("'")[1], splitedAttributes[2].split("'")[1]);
        }
    });
}

function EnableFormularDropDownListSubfields(parentClass) {
    //alert("merge");
    $("." + parentClass + " select").each(function(i, e) {
        ddlonclick = $(this);
        ddlonclickAttr = ddlonclick[0].getAttributeNode('onchange').value;
        //alert(ddlonclickAttr);
        //alert(ddlonclickAttr.split(',')[0].split("'")[1] + " / " + ddlonclickAttr.split(',')[1].split("'")[1] + " / " + ddlonclickAttr.split(',')[2].split("'")[1] );
        getFormularDropListCustomChange(ddlonclickAttr.split(',')[0].split("'")[1] , ddlonclickAttr.split(',')[1].split("'")[1] , ddlonclickAttr.split(',')[2].split("'")[1])        
    });
}

function getFormularRadioButton(radioValue, formID, visibleID) {    
    arrayloc = visibleID.split('|');
    var formloc = formID.split('_');
    var resultForInput ="";
    var resultForLabel ="";
    
    var i=0,j=0;
    for(i=0;i<4;i++){
        resultForInput += formloc[i]+"_";
    }
    
    for(i=2;i<4;i++){
        resultForLabel += formloc[i]+"_";
    }
       
    for(i=0;i<arrayloc.length;i++){
        var currID = arrayloc[i];
        currID = currID.replace("{", "").replace("}", "");

        // currID = currID.replace("-", ""); - another option
        var part_of_id = currID.split('-');
        var newCurrID = "";
        for(j=0;j<part_of_id.length;j++){
            newCurrID+=part_of_id[j];
        }
       
        var final_result_for_input = resultForInput + newCurrID;
        var final_result_for_label = resultForLabel + newCurrID + "_text";

        var input_element = document.getElementById(final_result_for_input);
        var label_element = document.getElementById(final_result_for_label);
        
        if(input_element && label_element){
            if (radioValue=="Ja"){
                input_element.style.display = "block";
                label_element.style.display = "block";
            }
            else{
				input_element.value = "";
                input_element.style.display = "none";
                label_element.style.display = "none";
            }
        }
    }
}

function redirectToFirstPage(formularHome, url){
    alert("/"+formularHome + "/" + url + ".aspx?formular=yes");
    location.href = "/"+formularHome + "/" + url + ".aspx?formular=yes";
}

function printFormular(){
    var newurl = location.href + "?p=1";
    openPopUp(location.href+"?p=1", 'formularwindow')
}

function pdfFormular(){
    var newurl = location.href + "?p=2";
    openPopUp(location.href.replace("p=1", "p=2"), 'formularpdfwindow');
}

function getFormularDropListCustomChange(valueForShow, formID, idsForToShow){     
    var drop_down_element = document.getElementById(formID.replace("scope", ""));
    if(drop_down_element){
        
            var inputid = "";
            var labelid = "";
            
            var arrayloc = formID.split('_');
            
            var i=0;
            for(i=0;i<4;i++){
                inputid += arrayloc[i]+"_";
            }
    
            for(i=2;i<4;i++){
                labelid += arrayloc[i]+"_";
            }
            
            var ids_for_to_show = idsForToShow.split('|');
            for(i=0;i<ids_for_to_show.length;i++){
            
                var currID = ids_for_to_show[i].replace("{", "").replace("}", "")
                var part_of_id = currID.split('-');
                var newCurrID = "";
                for(j=0;j<part_of_id.length;j++){
                    newCurrID+=part_of_id[j];
                }
                
                var input_for_to_show=inputid + newCurrID;
                var label_for_to_show=labelid + newCurrID +"_text";
				
				var valueSelected = drop_down_element.options[drop_down_element.selectedIndex].value;
					
				var input_element = document.getElementById(input_for_to_show);
                var label_element = document.getElementById(label_for_to_show);
				
                if(input_element && label_element){
					var showValues = valueForShow.split('|');				
					var showDD = false;
					for(j=0;j<showValues.length;j++){
						if (valueSelected == showValues[j]){
							showDD = true;
						}
					}
				
                    //if (drop_down_element.options[drop_down_element.selectedIndex].value == valueForShow){
					if (showDD == true){
                        input_element.style.display = "block";
                        label_element.style.display = "block";
                    }
                    else{
						input_element.selectedIndex = 0;
                        input_element.style.display = "none";
                        label_element.style.display = "none";
                    }
                }
            }
        
    }
}

function BackAction(url){
    window.location = url;
}

function CloseSession(url, sesp) 
{ 
    if (url){
        BackAction(url+sesp);
    }
}

function GoBack(url, fieldIDSOnPage){

    var fieldIDs = fieldIDSOnPage.split('|');
    var backValues = "";
    
    for(i=0;i<fieldIDs.length-1;i++){
       var fields = fieldIDs[i].split('_');
       if (document.getElementById(fieldIDs[i]) != null){
            var value = document.getElementById(fieldIDs[i]).value;
            if (value == undefined){
                var j=0;
                for(j=0;j<2;j++){
                    if(document.getElementById(fieldIDs[i]+"_"+j.toString()).checked == true){
                        value = document.getElementById(fieldIDs[i]+"_"+j.toString()).value;
                    }
                }
            }
            backValues += fields[fields.length-1] + "_" + encodeURIComponent(value) + "|";
        }
    }
    
    window.location = url+"?formular=yes&backValues="+backValues;
   
}

function CloseWindow(url, sesp) {   
   formularwindow = window.open (url +  "/ConfirmClose.aspx", "confirmationWindow","width=600,height=300,status=yes,toolbar=no,menubar=no,location=no, scrollbars=1");
}

function confirmYes(url, sesp){
    if(url){
        window.opener.location = url+sesp;
        self.close();
    }
}
/*
function createThrobber() {
    return $('<div class="throbber" style="height:50px;"><img class="throbber_img" src="img/throbber.gif" border="0" style="float:left;"><p class="throbber_text" style="">Genererer rapport...</p></div>');
}

function DisplayReportElement(reportPath, appendTo, alternative) {
    // Create and show process indicator
    var throbber = createThrobber();
    throbber.appendTo(appendTo);
    var altern = $(alternative);
    var appendDiv = $(appendTo);
    // Report url
    var reportURL = 'http://91.208.157.177/cognos8/cgi-bin/cognos.cgi/rds/reportData/path/' + reportPath
    altern.hide();
    // Fetch report
    $.ajax({
        type: "GET",
        url: reportURL,
        cache: false,
        success: function (response, textStatus, XMLHttpRequest) {
            if (XMLHttpRequest.readyState == 4 && XMLHttpRequest.status == 200) {
                throbber.remove();
                // IP configuration should be changed on the server, so no IP replacement is needed.
                $(response.replace('172.16.2.70', '91.208.157.177')).appendTo(appendTo);
            } else {
                throbber.remove();
                appendDiv.hide();
                altern.show();
                $('<p class="errorMsg">Der skete en fejl</p>').appendTo(appendTo);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            throbber.remove();
            appendDiv.hide();
            altern.show();
            $('<p class="errorMsg">Der skete en fejl</p>').appendTo(appendTo); asa
        }
    });

}
*/
