var glo_area;
 /* the value has to be changed when the application name is changed */
 var applicationName = '/portal' ;

 function FadeEffect(element){	
       new Effect.Fade(element, 
       { duration:1});
}
   function ShowEffect(element){
		
       new Effect.Appear( element, 
       {duration:1, from:1.0, to:1.0} );
}


String.prototype.reverse = function(){
	splitext = this.split("");
	revertext = splitext.reverse();
	reversed = revertext.join("");
	return reversed;
}
String.prototype.validateForEmail = function () {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;   
   	if(reg.test(email) == false) {     
      		return false;
   	}
	return true;	
}





// function test2(id1,h2,id2,id_h1,id_h2,id_h3,id_buyer,id_eg){
// 	var _h2 = document.getElementById(h2);
//  	var _id1 = document.getElementById(id_h1);
//  	var _id2 = document.getElementById(id_h2);
//  	var _id3 = document.getElementById(id_h3);
//  	var id_e = document.getElementById(id_eg);
//  	var id_buyer = document.getElementById(id_buyer);
// 
// 	FadeEffect(id1+'');
// 	FadeEffect('hide'+id1);
// 
// 	_h2.style.color="#233f8d"
//  	_id1.style.backgroundColor="white";
// 	_id2.style.color="black";
// 	id_e.style.color="black"
// 	id_buyer.style.color="black"
// 
//  	_id3.style.color="#233f8d";
// 
// 
// 	FadeEffect(id2+'');
// 	FadeEffect('hide'+id2);
// 
// 
// 
// 
// 	return false;
// 	
// }

function test2(id1,id2,trId){


	
	$(trId).setAttribute("class","");
	$( '_h2' + trId).style.color="#233F8D";
	
	FadeEffect(id1+'');
	FadeEffect('hide'+id1);

	FadeEffect(id2+'');
	FadeEffect('hide'+id2);




	return false;
	
}


function saveSystemUser(idadminlogin)
{
 

  var EmailAddress = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  
  url = location.href.substring(0,location.href.indexOf(applicationName));
   
   
   name = $('name').value;
   username = $('loginname').value;
   pass = $('password').value;

   if( name.length == 0){
      alert("Namn-fältet kan inte vara tom");
      return;
   }
   if( username.length == 0 | EmailAddress.test( username ) == false ){
      alert("Ange en giltig e-postadress");
      return;
   }
   if( pass.length == 0){
      alert("Lösenordet får inte vara tom");
      return;
   }
 

	new Ajax.Request(url + applicationName + "/admin/System_user/edit", {
					method: 'post',
					parameters :'name=' + name  + '&username='+username+'&pass='+pass+'&id='+idadminlogin,
					onSuccess: systemUserSave,
					onFailure:  failed
	});


}
function systemUserSave(response ) {
	
        clearSystemUserFields();
        //alert("systemets användare har skapats!");
       	url = location.href.substring(0,location.href.indexOf(applicationName));
        window.location = url + applicationName + "/admin/System_user";
}

function clearSystemUserFields()
{
   
    $('name').value = '';
    $('loginname').value = '';
    $('password').value = '';

}

function getRow(obj){
    var prnt = obj.parentElement;
    while(prnt.tagName != 'tr')
        prnt = prnt.parentElement;
    //alert( prnt.id);
}
// 

function hide( id ){

	//alert('hide'+id);	
	//document.getElementById(id).fade(0.5);
// 	console.log(id);
// 	console.log($(id));
// 	FadeEffect(id+'');
// 	FadeEffect('hide'+id+'');
}

function newWindow(){

      myWindow = window.open("http://www.kommuninfo.se/tender.php", "Readmore", 'directories=yes,toolbar,resizable=yes,menubar=yes,location=yes') 

}

function cpv_search(){
                   
		url = location.href.substring(0,location.href.indexOf(applicationName));
		cpv_text = document.getElementById("searchcpv").value;

		url = location.href.substring(0,location.href.indexOf(applicationName));

		window.location = url + applicationName + "/index.php/customers/Mywatchlist/show/"+cpv_text + "/";
	
// 		new Ajax.Request(url + applicationName + "/index.php/customers/Mywatchlist/searchCPVCodes/" + cvp_text, {
//   				method: 'get',
//   				onSuccess: searchList,
//   				onFailure: searchNotSucceed
//   		});
// 

}



function getUnderCodes(cpv){

	

		var url = location.href.substring(0,location.href.indexOf(applicationName));
		var cvp_text = cpv;


		new Ajax.Request(url + applicationName + "/customers/Mywatchlist/getUnderCPVCodes/" + cvp_text, {
  				method: 'get',
  				onSuccess: searchList,
  				onFailure:  searchNotSucceed
  		});

}

function getUnderCodesWithToggling( cpv,obj2 ){

		var url = location.href.substring(0,location.href.indexOf(applicationName));
		var cvp_text = cpv;
		$('pagination').innerHTML = "";

		if( $(obj2).style.display == 'none' ){
		    new Ajax.Request(url + applicationName + "/customers/Mywatchlist/getUnderCPVCodes/" + cvp_text, {
				    method: 'get',
				    onSuccess: searchList,
				    onFailure:  searchNotSucceed
		    });
		}
		else{
		    new Ajax.Request(url + applicationName + "/customers/Mywatchlist/getCpvCategory/" + cvp_text, {
				    method: 'get',
				    onSuccess: searchList,
				    onFailure:  searchNotSucceed
		    });

		}

}


function toggleobj(obj1,obj2) {

	var el1 = document.getElementById(obj1);

	var el2 = document.getElementById(obj2);

	if ( el2.style.display == 'none' ) {

		el2.style.display = 'block';
		el1.style.display = 'none';
	}
	else {

		el1.style.display = 'block';
		el2.style.display = 'none';
	}
}


function getUnderlyingCodes(cpv){

		var url = location.href.substring(0,location.href.indexOf(applicationName));
		var cvp_text = cpv;

		new Ajax.Request(url + applicationName + "/index.php/customers/Mywatchlist/getUnderlyingCPVList/" + cvp_text, {
  				method: 'get',
  				onSuccess: searchList,
  				onFailure:  searchNotSucceed
  		});


}


function searchList(response){

	
	//alert(response.responseText);
	document.getElementById("codelist").innerHTML=response.responseText;

}

function searchNotSucceed(response){
//alert("response");
}



function show( id ){
	//document.getElementById(id).appear(0.5); 
	ShowEffect(id);	
	ShowEffect('hide'+id);
	return false;
}

function addCpv2Favourite(id){	
	
	url = location.href.substring(0,location.href.indexOf(applicationName));

		new Ajax.Request(url + applicationName + "/index.php/customers/Mywatchlist/addCPVToWatchList/" + id, {
  				method: 'get',
  				onSuccess: cpvSaved,
  				onFailure:  cpvNotSaved
  		});

}

function cpvSaved(response ) {	
	document.getElementById('watchedCpv').innerHTML = response.responseText;
}

function cpvNotSaved( response ) {
	alert('Fel vid sparande CPV till favorit');
	
}



function test(id1,id2,trId) {

   if ( document.getElementById(trId).className == "active" )
	{
		test2(id1,id2,trId);
		return ;
	}

	

    $(trId).setAttribute("class","active");
    $( '_h2' + trId).style.color="#FFFFFF";

	$(id1 + '').show();
	$('hide' + id1).show();
	
	$(id2 + '').show();
	//$('hide' + id2).show();

	
    
}




function highlight(h2,id,id_p,id_b,id_eg){

      var _h2 = document.getElementById(h2);
      var id_buyer = document.getElementById(id_b);
      var id_pub = document.getElementById(id_p);
      var id_h = document.getElementById(id);
      var id_e = document.getElementById(id_eg);

      _h2.style.color="white";
      id_h.style.backgroundColor="#233F8D";
      id_pub.style.color="white";
      id_buyer.style.color="white";
      id_e.style.color="white";
}

function saveProposals( id ){
      var myProposal = document.getElementById(id);
     // myProposal.style.backgroundColor="#c1dae1";
	myProposal.style.backgroundColor="#dc5c7d";
//alert("Saved");
      myProposal.style.backgroundImage="url(icon-edit.gif)";
//alert(myProposal.style.backgroundImage);
//alert(i.style.backgroundImage);
 	url = location.href.substring(0,location.href.indexOf(applicationName));
 	var ajax = new Ajax.Updater(
 	{success: 'proposalSaved()'},
 	url = url + applicationName + "/index.php/customers/Proposals/MakeFavouriteProposal/"+id,
 	{method: 'get', onFailure: reportError}
 	);
// 	
	

}




function proposalSaved() {	
	alert ('proposalSaved');
}


	
function reportError(request) {
	alert(request.toString() );
	//alert('error saving proposal');
}

function addArea(  ){

var s = document.getElementById("areaselector");

for(var i=0; i<s.options.length; i++){
    if(s.options[i].selected){
		areaId = s.options[i].value;
		
    }
}


	url = location.href.substring(0,location.href.indexOf(applicationName));

		new Ajax.Request(url + applicationName+ "/index.php/customers/Mywatchlist/AddAreaToWatchList/" + areaId, {
  				method: 'get',
  				onSuccess: areaSaved,
  				onFailure:  areaNotSaved
  		});

}

function  areaSaved( response) {
	
	//alert(response.responseText);
	document.getElementById('watchedAreas').innerHTML = response.responseText;

}

function areaNotSaved( response ){

	alert("Inte emptySome fel Occoured vid Borttagning");
}

function removeArea( areaId ) {

	

	url = location.href.substring(0,location.href.indexOf(applicationName));

		new Ajax.Request(url + applicationName + "/index.php/customers/Mywatchlist/RemoveAreaFromWatchList/" + areaId, {
  				method: 'get',
  				onSuccess: areaRemoved,
  				onFailure:  areaNotRemoved
  		});

}

function areaRemoved ( response) {
	//alert(response.responseText + "removed" );
	document.getElementById('watchedAreas').innerHTML = response.responseText;

}

function areaNotRemoved ( response ) {

	alert("inte emptySome fel Occoured vid borttagning");
}

function removeCpv( cpvCode ) {

		url = location.href.substring(0,location.href.indexOf(applicationName));

		

		new Ajax.Request(url + applicationName + "/index.php/customers/Mywatchlist/removeCPVFromWatchList/" + cpvCode, {
  				method: 'get',
  				onSuccess: cpvRemoved,
  				onFailure:  cpvNotRemoved
  		});

}

function cpvRemoved( response ) {

	document.getElementById('watchedCpv').innerHTML = response.responseText;	

}

function cpvNotRemoved (response ) {

	alert('error removing cpv code ');
}

function getURL(){

	urlToget = $('url').value;
	if( urlToget.length == 0 )
	  alert('Vänligen eneter en giltig webbadress för att hämta');
	else{
	  if (urlToget.indexOf("http") == -1 ) {
		  urlToget = "http://".concat(urlToget); 
		 
	  }
	 // alert(urlToget);
	  //alert(urlToget.replace("+","_"));
	  while ( urlToget.indexOf(".") > -1 )
		  urlToget = urlToget.replace(".","DOT");
	  while ( urlToget.indexOf("/") > -1 )
	  urlToget = urlToget.replace("/","SLASH");
	  while ( urlToget.indexOf("?") > -1 )
	  urlToget = urlToget.replace("?","QUESTIONMARK");
	  while ( urlToget.indexOf("=") > -1 )
	  urlToget = urlToget.replace("=","EQUAL");
	  while ( urlToget.indexOf("&") > -1 )
	  urlToget = urlToget.replace("&","AMBER");
	  while ( urlToget.indexOf(";") > -1 )
	  urlToget = urlToget.replace(";","COMMA");
	  

	  
	

	  url = location.href.substring(0,location.href.indexOf(applicationName));
	  new Ajax.Request(url + applicationName + "/admin/Spider_web/accessUrl/" + urlToget, {
				  method: 'post',
				  parameters:'?url='+urlToget,
				  onSuccess: setURL,
				  onFailure:  failed
		  });
	}
	
	
	

}


function setURL(response){		

	

	if ( response.responseText.indexOf("PHP Error") > 0 ) {		
		alert('Mall format korrekt inte.');
		return ;
	
	}


	$('page_source').value = response.responseText;

}
function failed(response){
	
	alert(response.responseText);
}

function testTemplate(){

	 nastyChar=new Array("%","&","?","#");
	 safeChar = new Array("Percent","Ampercent","QuestionMark","Hash");
	
	template = $('content').value;

	
	idx=0;
	for( idx=-1; idx < nastyChar.length; idx ++ ) {

		//alert(nastyChar[idx]);
 		while ( template.indexOf( nastyChar[idx] ) > -1 ) {
			template = template.replace( nastyChar[idx] ,safeChar[idx] );
			
		}
	

			
	}
	
	//console.log(template);
	site = $('url').value;


	

	  while ( site.indexOf(".") > -1 )
		  site = site.replace(".","DOT");
	  while ( site.indexOf("/") > -1 )
	  site = site.replace("/","SLASH");
	  while ( site.indexOf("?") > -1 )
	  site = site.replace("?","QUESTIONMARK");
	  while ( site.indexOf("=") > -1 )
	  site = site.replace("=","EQUAL");
	  while ( site.indexOf("&") > -1 )
	  site = site.replace("&","AMBER");
	  while ( site.indexOf(";") > -1 )
	  site = site.replace(";","COMMA");

	if ( site.indexOf("http") == -1 ) {
		site = "http://".concat(site); 
	}
	
	url = location.href.substring(0,location.href.indexOf(applicationName));
	new Ajax.Request(url + applicationName + "/admin/Spider_web/testTemplate", {
  				method: 'post',
				parameters :'cons=' + template+'&url='+site,
  				onSuccess: templateMatch,
  				onFailure:  failed
  		});
	

}
function templateMatch(response){
	//alert(response.responseText);

	template = response.responseText;

	// here in template the character coding needed.
		
	
		
 	  while ( template.indexOf("&nbsp;") > -1 )
 		  template = template.replace("&nbsp;","");

 	  while ( template.indexOf("&amp;") > -1 )
 		  template = template.replace("&amp;","");

		while ( template.indexOf("\u00e5") > -1 )
 		  template = template.replace("\u00e5","å");
		while ( template.indexOf("\u00e4") > -1 )
 		  template = template.replace("\u00e4","ä");
		while ( template.indexOf("\u00f6") > -1 )
 		  template = template.replace("\u00f6","ö");
		while ( template.indexOf("\u00e9") > -1 )
 		  template = template.replace("\u00e9","é");





	

	if ( template.indexOf("PHP Error") > 0 ) {
		
		alert('Mall format korrekt inte.');
		return ;
	
	}

	//template = template.replace("\\","");
	template = template.replace("{","{\n" );
  	while ( template.indexOf("\",") > -1 )
 		template = template.replace("\",","\" ,\n" );
	template = template.replace("}","\n}" );


	$('spider_result').value = template;
	//alert(response.responseText);
}

function saveTemplate(){

	template = $('content').value;
	result = $('spider_result').value;
	site = $('url').value;

	if ( result.replace(/^\s*/, "").length == 0 ) {
		alert('Du måste skapa mallen första.');
		return ;
	}

	  while ( site.indexOf("\r") > -1 )
		result = result.replace("\r","");
		
      	 result = result.replace("&amp;", "");

	  while ( site.indexOf(".") > -1 )
		  site = site.replace(".","DOT");
	  while ( site.indexOf("/") > -1 )
	  site = site.replace("/","SLASH");
	  while ( site.indexOf("?") > -1 )
	  site = site.replace("?","QUESTIONMARK");
	  while ( site.indexOf("=") > -1 )
	  site = site.replace("=","EQUAL");
	  while ( site.indexOf("&") > -1 )
	  site = site.replace("&","AMBER");
	  while ( site.indexOf(";") > -1 )
	  site = site.replace(";","COMMA");

	 
	


	url = location.href.substring(0,location.href.indexOf(applicationName));
	new Ajax.Request(url + applicationName + "/admin/Spider_web/saveTemplate", {
  				method: 'post',
				parameters :'cons=' + result + '&site=' + site + '&template=' + template,
  				onSuccess: templateSaved,
  				onFailure:  templateFormatError
  		});




}

function templateSaved( response){

	
	alert(response.responseText);


	

	if ( response.responseText.indexOf("PHP Error") > 0 ) {
		
		alert('Ogiltigt resultat format.');
		return ;
	
	}

	
	$('spider_result').value = response.responseText;
	
	//alert(response.responseText);
}
function templateFormatError(response) {
	alert("Format Error");

}


function editURL(id){

		

		url = location.href.substring(0,location.href.indexOf(applicationName));

                location.href=url + applicationName + "/admin/Spider_web/edit/"+id;


}






function removeURL(id) {



	url = location.href.substring(0,location.href.indexOf(applicationName));

		new Ajax.Request(url + applicationName + "/admin/Spider_web/remove/" + id, {
  				method: 'get',
  				onSuccess: urlRemoved,
  				onFailure:  urlNotRemoved  		});

}

function urlRemoved(response){

                url = location.href.substring(0,location.href.indexOf(applicationName));

                location.href=url + applicationName + "/admin/Spider_web";

    
}
function urlNotRemoved(response){
    
    
    //alert(response.responseText);
    
}

function defaultAction(e,onClickComponent){	

	var KeyID = (window.event) ? event.keyCode : e.keyCode;
	if ( KeyID == 13 ) {
		func=$(onClickComponent).getAttributeNode('onclick').nodeValue;
		eval(func);
	}		
}
function forgotPassword( ){

	url = location.href.substring(0,location.href.indexOf(applicationName));
	email = document.getElementById('email').value;
	email = trim(email);

	if ( email.length == 0 ) {
		document.getElementById('forgotPassword').innerHTML="E-Postadress kan inte vara tom";
		return ;

	}
	if (email.validateForEmail() == false) {

		document.getElementById('forgotPassword').innerHTML = 'Felaktig email, skriv in din mailadress i fältet E-Mail och tryck sedan på "Glömt ditt lösenord?" Har ni ytterligare problem maila support@kommuninfo.se';
		return ;
	}
	new Ajax.Request(url + applicationName + "/login/passwordRetrived", {
  				method: 'post',
				parameters :'email=' + email,
  				onSuccess: passwordRetrived,
  				onFailure:  failed
  		});
	
	return false;
}

function passwordRetrived(response){
	document.getElementById('forgotPassword').innerHTML=response.responseText;

}



function forgotAdminPassword( ){

	url = location.href.substring(0,location.href.indexOf(applicationName));
	email = $('email').value;

	if ( email.length == 0 )  {
		alert('Ange din e-postadress');
		return ;
	}
	

	new Ajax.Request(url + applicationName + "/admin/Admin_Login/passwordRetrived", {
  				method: 'post',
				parameters :'email=' + email,
  				onSuccess: passwordRetrived,
  				onFailure:  failed
  		});
	
	return false;
}



function underLyingCPV( cpv ){


	url = location.href.substring(0,location.href.indexOf(applicationName));
	new Ajax.Request(url + applicationName + "/admin/Admin_Proposals_Add/underLyingCPV", {
  				method: 'post',
				parameters :'cpv=' + cpv,
  				onSuccess: putUnderlyingCodes,
  				onFailure:  failed
  		});
	
}

function underLyingCPVFromAdminCards( cpv ){


	url = location.href.substring(0,location.href.indexOf(applicationName));
	new Ajax.Request(url + applicationName + "/admin/Admin_Cards/underLyingCPV", {
  				method: 'post',
				parameters :'cpv=' + cpv,
  				onSuccess: putUnderlyingCodesForAdminCards,
  				onFailure:  failed
  		});

}

function putUnderlyingCodesForAdminCards(response){

	$('underLyingCPV1FromAdminCards').innerHTML=response.responseText;
}

function putUnderlyingCodes(response){

	$('underLyingCPV1').innerHTML=response.responseText;
}
function underLyingCPVSecondLevel2( cpv ){


	url = location.href.substring(0,location.href.indexOf(applicationName));
	
	
	

	new Ajax.Request(url + applicationName + "/admin/Admin_Proposals_Add/underLyingCPVLevel2", {
  				method: 'post',
				parameters :'cpv=' + cpv,
  				onSuccess: putUnderlyingCodes2,
  				onFailure:  failed
  		});
	
}

function underLyingCPVSecondLevel2FromAdminCards( cpv ){


	url = location.href.substring(0,location.href.indexOf(applicationName));




	new Ajax.Request(url + applicationName + "/admin/Admin_Cards/underLyingCPVLevel2", {
  				method: 'post',
				parameters :'cpv=' + cpv,
  				onSuccess: putUnderlyingCodes2ForAdminCards,
  				onFailure:  failed
  		});

}

function underLyingCPVSecondLevel3( cpv ){

	if($('selectedCPV').innerHTML.indexOf(cpv)==-1)
	      $('selectedCPV').innerHTML += "<option selected>"+cpv+"</option>";
	else alert("CPV-kod: "+cpv+" är redan i din Bevakning");
	
}
function underLyingCPVSecondLevel3FromAdminCards( cpv ){
  	if($('selectedCPVCodes').innerHTML.indexOf(cpv)==-1)
	      $('selectedCPVCodes').innerHTML += "<option selected>"+cpv+"</option>";
	else alert("CPV-kod: "+cpv+" är redan i din Bevakning");
	//$('selectedareas').innerHTML = "<option selected value = \"663\"> Sverige </option>";	
}

function putUnderlyingCodes2(response){
	
	$('underLyingCPV2').innerHTML=response.responseText;
}

function putUnderlyingCodes2ForAdminCards(response){

	$('underLyingCPV2FromAdminCards').innerHTML=response.responseText;
}
function removeSeletedCPVFromAdminCards(){

	idxToRemove = $("selectedCPVCodes").selectedIndex;

	$("selectedCPVCodes").options[idxToRemove] = null;

	return false;
	

}

function removeSeletedCPV(){

	idxToRemove = $("selectedCPV").selectedIndex;

	$("selectedCPV").options[idxToRemove] = null;

	return false;


}
function removeSeletedAreaFromAdminCards(){

	idxToRemove = $('selectedareas').selectedIndex;
	//alert(idxToRemove);
	$('selectedareas').options[idxToRemove] = null;

	return false;
	

}

function underLyingAreas( areaid ){
     // $('selectedAreas').innerHTML += "<option value="+areaid + ">"+ arealabel +"</option>";
     //$('buyerList').innerHTML += "<option value="+areaid + ">"+ areaid +"</option>";
     url = location.href.substring(0,location.href.indexOf(applicationName));

     new Ajax.Request(url + applicationName + "/admin/Admin_Cards/getAllBuyers", {
			method: 'post',
			parameters :'areaId=' + areaid ,onSuccess: showuderlyingBuyers,onFailure:failed
    });

}

function underLyingAreasForAdminCards( area,areaid ){
	
	url = location.href.substring(0,location.href.indexOf(applicationName));
    	var optionvalueList = $('selectedareas').options;
	
    	for( i=0;i < $('selectedareas').options.length;i++ ){		
		//alert(areaid + ":" + parseInt($('selectedareas').options[i].value) );
		if( parseInt($('selectedareas').options[i].value) == areaid ){
			alert( "området exists.please redan välja ny" );
			return;
		}
   	} 
	
    //checking is Sverige is selected
    if ( areaid == -100 ) { // this is a hard coded value don't change it.
	funtionname="getAllMunicipals";
	allArea = true;
	$('selectedareas').innerHTML = "";
	
    }
    else {
	
	funtionname = "getmunicipalFromAreaId";
	if ( typeof(allArea) != "undefined"  &&  allArea ==  true ) {
	    $('selectedareas').innerHTML = "";
	    allArea = false;
	}
	
	  
	
	
    }


	new Ajax.Request(url + applicationName + "/admin/Admin_Cards_Edit/" + funtionname, {
			method: 'post',
			parameters :'areaId=' + areaid, 
			onSuccess: setAreas,
			onFailure:  failed
	});

    //$('selectedareas').innerHTML += '<option value = '+ '" ' + areaid + ' "' + ' >' +  area + "</option>";

}


function setAreas(response){
	eval(response.responseText); //This eval creates a variable named js_array which comes from corresponding AJAX request.
	existingValues = $('selectedareas').options;
	existingHTML = $('selectedareas').innerHTML;
      	//alert(response.responseText);

	if(existingHTML.indexOf('Sverige') > 0){
		$('selectedareas').innerHTML = "";
	}
	
	for (var ar in js_array ) {
		if ( parseInt(ar) ) { // This is used to avoid unnecessary elements. index are given as number. So, parseInt comes in this case :) 
			// if Sverige is selected it will flash all previous areas from drop down (FS # 2415)
			if(js_array[ar] == 'Sverige'){
				$('selectedareas').innerHTML = '<option selected value = '+ '" ' + ar + ' "' + ' >' +  js_array[ar] + "</option>";
			}else{
				$('selectedareas').innerHTML += '<option selected value = '+ '" ' + ar + ' "' + ' >' +  js_array[ar] + "</option>";
			}
		}
	}
}


function showuderlyingBuyers(  ){

    $('buyerList').innerHTML = '';
    var buyersList= [];
    /*var mycars = new Array();
    mycars[0] = "Saab";
    mycars[1] = "Volvo";
    mycars[2] = "BMW";*/

    //eval(response.responseText);
    var str = '';

    for( i=0; i< mycars.length;i++){
	str += "<option value=" + mycars[i] + ">"+ mycars[i] +"</option>";
    }
    //alert(str);
    $('buyerList').innerHTML += str;
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


function manualProposal(){
	
	var url = location.href.substring(0,location.href.indexOf(applicationName));
	var areaList1 = document.getElementById("areaList");
	

	this.heading = $('heading').value;
	this.buyer = $('buyer').value;
	var published = $('published').value;
	var deadline = $('deadline').value;
	/*
		updated : task # 2475
		@brief  : document number should be trimmed with whitespace
	*/
	var document_no = trim($('document_no').value,' ');
	var area = areaList1.options[areaList1.selectedIndex].value;
	
        /*var nastychar = new Array("?","#","%");

        var safechar = new Array("QUESTIONMARK","HASH","PERCENTAGE");*/


	if(area== 0) {
	 area= $('location_city_input').value;
	}
	
	area = area.replace("--","");
	area = area.replace(/\d/g,"");
	
	var doc_type = $('type').value;
	
	//This block of code is commented due to some changes for FS#2426
	/*pro_description = $('description').value;
	infoFrom = $('infoFrom').value;
	detailedInfo = $('detailedInfo').value;*/

	//The following lines added for FS#2426( allowing special chars(?) to be saved into database )
	/*pro_description = $('description').value.replace(/\'/gi,"\\'").replace(/\?/gi,"QUESTIONMARK");
	infoFrom = $('infoFrom').value.replace(/\'/gi,"\\'").replace(/\?/gi,"QUESTIONMARK");
	detailedInfo = $('detailedInfo').value.replace(/\'/gi,"\\'").replace(/\?/gi,"QUESTIONMARK");


	pro_description = pro_description.replace(/\#/gi,"HASH");
	infoFrom = infoFrom.replace(/\#/gi,"HASH");
	detailedInfo = detailedInfo.replace(/\#/gi,"HASH");

	pro_description = pro_description.replace(/\%/gi,"PERCENTAGE");
	infoFrom = infoFrom.replace(/\%/gi,"PERCENTAGE");
	detailedInfo = detailedInfo.replace(/\%/gi,"PERCENTAGE");

	pro_description = pro_description.replace(/\&/gi,"AMPERSAND");
	infoFrom = infoFrom.replace(/\&/gi,"AMPERSAND");
	detailedInfo = detailedInfo.replace(/\&/gi,"AMPERSAND");



	pro_description = $('description').value.replace(/\'/gi,"\\'").replace(/\#/gi,"HashSign");
	infoFrom = $('infoFrom').value.replace(/\'/gi,"\\'").replace(/\#/gi,"HashSign");
	detailedInfo = $('detailedInfo').value.replace(/\'/gi,"\\'").replace(/\#/gi,"HashSign");*/

	this.pro_description = $('description').value;
	this.infoFrom = $('infoFrom').value;
	this.detailedInfo = $('detailedInfo').value;

	var varList = new Array( "pro_description","infoFrom","detailedInfo","heading","buyer" );//list of variables to be filtered(handling special characters)

	handleSpecialChar( this,varList );//This line handles the special character which creates prolem whhen exists in any parameter sent to the server

	alertStr = 'Ogiltigt format för dokument nummer. Dokumentnummer bör vara så: 123-456';


	//the following lines are commented according to task # 2416, no need to validate the documentation number.
	/*if ( document_no.indexOf("-") > 0 ) {
		
		parts = document_no.split('-');	
		//alert(parts);	
		
		//alert(parts[0] + 5 );

		if ( ! parseInt(parts[0] ) ) { 
			alert( alertStr );
			return ;
		}
		if ( ! parseInt(parts[1] ) ) { 
			alert( alertStr );
			return ;
		}

		
			
		
	}
	else {
		alert ( alertStr );
		return ;
	}*/


	 var combo1 = document.getElementById("selectedCPV");
	
	
	if ( combo1.options.length > 0 ) {

		var cpv = "";
		var op = "";

		for(i=0; i<combo1.options.length; i++) {
			parts = combo1.options[i].value.split('-');
			cpv += op + parts[0].replace(/^\s*/, "").replace(/\s*$/, "");
			op = ",";
			//alert(cpv);
			//cpv[i]= "" + combo1.options[i].value;
			
		}		
	}
	else {
		alert("Välj CPV första");
		return ;
	}
	//alert(cpv);
	

	if(document_no!=""){
		new Ajax.Request(url + applicationName + "/admin/Admin_Proposals_Add/saveProposal", {
				method: 'post',
				parameters :'heading=' + this.heading + '&buyer=' + this.buyer + '&published=' + published + '&deadline=' + deadline + '&document_no=' + document_no + '&area=' + area + '&doc_type=' + doc_type + '&pro_description=' + this.pro_description + '&infoFrom=' + this.infoFrom + '&detailedInfo=' + this.detailedInfo + '&cpv='+cpv,
				onSuccess: manualProposalsave,
				onFailure:  failed
		});
	}
	else{
	      alert("Ange dokumentnummer");
	}
	  
}

function manualProposalsave(response ) {
	
	
	if ( response.responseText.indexOf('Error') >= 0 ) {
		alert('fel occoured samtidigt som man sparar. Antingen: r är tom eller datumformat är inte lika "ÅÅÅÅ-MM-DD".');
	}
	else if ( response.responseText.indexOf('exists') >= 0 ) {

			alert('Förslag finns redan med viss handling nummer');		
	}
	else if ( response.responseText.indexOf('sparade') >= 0  ) {
			alert('förslag sparade');

	}
	else {
		alert('förslag inte sparas för internt fel');
	}

	//clearfield();

}


function editProposal(document_no){
	
	url = location.href.substring(0,location.href.indexOf(applicationName));
	var areaList1 = document.getElementById("areaList");
	

	this.heading = $('heading').value;
	this.buyer = $('buyer').value;
	var published = $('published').value;
	var deadline = $('deadline').value;
	var area = areaList1.options[areaList1.selectedIndex].value;
	var areaIndex = areaList1.options[areaList1.selectedIndex];

	var newarea = "";
	
	if(area==-1) { newarea= $('location_city_input').value; }
	
	var doc_type = $('type').value;

	//This block of code is commented due to some changes for FS#2426
	/*pro_description = $('description').value.replace(/\'/gi,"\\'");
	infoFrom = $('infoFrom').value.replace(/\'/gi,"\\'");
	detailedInfo = $('detailedInfo').value.replace(/\'/gi,"\\'");*/
	
	//The following lines added for FS#2426( allowing special chars(?) to be saved into database )
	/*pro_description = $('description').value.replace(/\'/gi,"\\'").replace(/\?/gi,"QUESTIONMARK");
	infoFrom = $('infoFrom').value.replace(/\'/gi,"\\'").replace(/\?/gi,"QUESTIONMARK");
	detailedInfo = $('detailedInfo').value.replace(/\'/gi,"\\'").replace(/\?/gi,"QUESTIONMARK");
	
	pro_description = pro_description.replace(/\#/gi,"HASH");
	infoFrom = infoFrom.replace(/\#/gi,"HASH");
	detailedInfo = detailedInfo.replace(/\#/gi,"HASH");

	pro_description = pro_description.replace(/\%/gi,"PERCENTAGE");
	infoFrom = infoFrom.replace(/\%/gi,"PERCENTAGE");
	detailedInfo = detailedInfo.replace(/\%/gi,"PERCENTAGE");

	pro_description = pro_description.replace(/\&/gi,"AMPERSAND");
	infoFrom = infoFrom.replace(/\&/gi,"AMPERSAND");
	detailedInfo = detailedInfo.replace(/\&/gi,"AMPERSAND");*/



	/*pro_description = $('description').value.replace(/\'/gi,"\\'").replace(/\%/gi,"percentageSign");
	infoFrom = $('infoFrom').value.replace(/\'/gi,"\\'").replace(/\%/gi,"percentageSign");
	detailedInfo = $('detailedInfo').value.replace(/\'/gi,"\\'").replace(/\%/gi,"percentageSign");

	pro_description = $('description').value.replace(/\'/gi,"\\'").replace(/\#/gi,"HashSign");
	infoFrom = $('infoFrom').value.replace(/\'/gi,"\\'").replace(/\#/gi,"HashSign");
	detailedInfo = $('detailedInfo').value.replace(/\'/gi,"\\'").replace(/\#/gi,"HashSign");*/

	/*pro_description = pro_description.replace(/\%/gi,"percentageSign");
	infoFrom = infoFrom.replace(/\%/gi,"percentageSign");
	detailedInfo = detailedInfo.replace(/\%/gi,"percentageSign");

	pro_description = pro_description.replace(/\#/gi,"HashSign");
	infoFrom = infoFrom.replace(/\'/gi,"\\'").replace(/\#/gi,"HashSign");
	detailedInfo = detailedInfo.replace(/\'/gi,"\\'").replace(/\#/gi,"HashSign");*/

	this.pro_description = $('description').value;
	this.infoFrom = $('infoFrom').value;
	this.detailedInfo = $('detailedInfo').value;

	var varList = new Array( "pro_description","infoFrom","detailedInfo","heading","buyer" );//list of variables to be filtered(handling special characters)
	
	handleSpecialChar( this,varList );//This line handles the special character which creates prolem whhen exists in any parameter sent to the server


	var alertStr = 'Ogiltigt format för dokument nummer. Dokumentnummer bör vara så: 123-456';

	


	//the following lines are commented according to task # 2416, no need to validate the documentation number.
	/*if ( document_no.indexOf("-") > 0 ) {
		
		parts = document_no.split('-');	
		if ( ! parseInt(parts[0] ) ) { 
			alert( alertStr );
			return ;
		}
		
		if ( ! parseInt(parts[1] ) ) {
			alert( alertStr ); 
			return ;
		}

	}
	else {
		alert( alertStr );
		return ;
	}*/


	 var combo1 = document.getElementById("selectedCPV");
	
	/*if ( combo1.options.length > 0 ) {

		var cpv = "";
		var op = "";

		for(i=0; i<combo1.options.length; i++) {
			cpv += op + combo1.options[i].value;
			op = ",";
		}		
	}
	else {
		alert("Välj CPV första");
		return ;
	}*/

	if ( combo1.options.length > 0 ) {

		var cpv = "";
		var op = "";

		for(i=0; i<combo1.options.length; i++) {
			parts = combo1.options[i].value.split('-');
			cpv += op + parts[0].replace(/^\s*/, "").replace(/\s*$/, "");
			op = ",";
			//alert(cpv);
			//cpv[i]= "" + combo1.options[i].value;
			
		}		
	}
	else {
		alert("Välj CPV första");
		return ;
	}

	new Ajax.Request(url + applicationName + "/admin/Admin_Proposals_Add/editProposal", {
			method: 'post',
			parameters :'heading=' + this.heading + '&buyer=' + this.buyer + '&published=' + published + '&deadline=' + deadline + '&document_no=' + document_no + '&area=' + area + '&doc_type=' + doc_type + '&pro_description=' + this.pro_description + '&infoFrom=' + this.infoFrom + '&detailedInfo=' + this.detailedInfo + '&cpv=' + cpv + '&newarea=' + newarea,
			onSuccess: editProposalsave,
			onFailure:  failed
	});
}

function editProposalsave(response ) {		
	
	
	if ( response.responseText.indexOf('Error') >= 0 ) {
		alert('fel occoured samtidigt som man sparar. Antingen: r är tom eller datumformat är inte lika "ÅÅÅÅ-MM-DD".');
	}
	else {
		alert('förslag sparade');
	}

	

}






function clearfield(){

	var els = Array("heading","buyer","published","deadline","document_no","type","description","infoFrom","detailedInfo","location_city_input");
	
	for(i=0; i<els.length; i++){
		$(els[i]).value='';
	
	}

	$('underLyingCPV1').innerHTML="";
    $('underLyingCPV2').innerHTML="";
	$('selectedCPV').innerHTML="";
	$('areaList').selectedIndex = 0;


}
function download(){

	startDate = $('time_from').value + "";
	endDate = $('time_to').value;

	

	if ( startDate.length == 0  ) {
		
		reverseurl = location.href;	
		reverseurl = reverseurl.reverse();


		splited = reverseurl.split("/");
		endDate = splited[1];
		startDate = splited[2];

		startDate = startDate.reverse();
		endDate = endDate.reverse();


	}



	url = location.href.substring(0,location.href.indexOf(applicationName));

	window.location = url + applicationName + "/admin/Admin_Export_Invoice/download/"+startDate+"/"+endDate;
	return false;


}

function showBuyers(  areaId ){

	url = location.href.substring(0,location.href.indexOf(applicationName));
	
	
	

	new Ajax.Request(url + applicationName + "/customers/Mywatchlist/getBuyers", {
  				method: 'post',
				parameters :'areaId=' + areaId,
  				onSuccess: showBuyersList,
  				onFailure:  failed
  		});
	

}

function showBuyersList(response){	

	$('buyersList').innerHTML = response.responseText;
	
}

function addBuyerToArea(buyername,areaId){

	url = location.href.substring(0,location.href.indexOf(applicationName));
	
	
	//buyername = buyername.replace("&amp;","Ampercent");
	

	new Ajax.Request(url + applicationName + "/customers/Mywatchlist/addBuyerToArea", {
  				method: 'post',
				parameters :'areaId=' + areaId + '&buyername=' + buyername,
  				onSuccess: showAreaBuyersList,
  				onFailure:  failed
  		});
	

}

function showAreaBuyersList(response){
	

	$('watchedAreas').innerHTML = response.responseText;

}

function RemoveBuyerFromArea(BuyerName,areaId){

	url = location.href.substring(0,location.href.indexOf(applicationName));	
	BuyerName = BuyerName.replace("&","Ampercent");

	new Ajax.Request(url + applicationName + "/customers/Mywatchlist/RemoveBuyerFromArea", {
  				method: 'post',
				parameters :'areaId=' + areaId + '&buyername=' + BuyerName,
  				onSuccess: showAreaBuyersList,
  				onFailure:  failed
  		});

}


function RemoveAreaFromWatchedArea(areaId){

	url = location.href.substring(0,location.href.indexOf(applicationName));	
	
	new Ajax.Request(url + applicationName + "/customers/Mywatchlist/RemoveAreaFromWatchedArea", {
  				method: 'post',
				parameters :'areaId=' + areaId ,
  				onSuccess: showAreaBuyersList,
  				onFailure:  failed
  		});

}




function addCardInfo(email){

	
 	url = location.href.substring(0,location.href.indexOf(applicationName));	
	
 	var email=(email.replace(/@/, "~~~"));
	window.location = url + applicationName + "/admin/Card_Info/index/"+email;
	return false;

}

function setCardInfo(response){

}

function SearchInvoice(){
	

	startDate = "";
	endDate = "";
	startDate = $('time_from').value;
	endDate = $('time_to').value;

	if ( startDate.length == 0 || endDate.length == 0 )
		return ;

	url = location.href.substring(0,location.href.indexOf(applicationName));	
	

	new Ajax.Request(url + applicationName + "/admin/Admin_Export_Invoice/search", {
  				method: 'post',
				parameters :'startDate=' + startDate + '&endDate=' + endDate,
  				onSuccess: searchInvoiceRes,
  				onFailure:  failed
  		});	

	new Ajax.Request(url + applicationName + "/admin/Admin_Export_Invoice/pagination", {
  				method: 'post',
				parameters :'startDate=' + startDate + '&endDate=' + endDate,
  				onSuccess: putpagenation,
  				onFailure:  failed
  		});	

}

function putpagenation(response){

    $('paging').innerHTML= response.responseText;


}

function  searchInvoiceRes(response ){	
	
	$('cardLists').innerHTML=response.responseText;

}

function resetInvoiceSearch(){	

	$('time_to').value = "";
	$('time_from').value = "";
}

function try_cust( ){
	extra="";
	params="";

	note = $('note').innerHTML;

	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	
	var els = ( $$('.box input[type="text"]') );
	
	for (i=0; els[i];i++ ) {

		if ( els[i].id == "email" ) {
			if(reg.test(els[i].value) == false) {
    		  	alert('Ogiltig e-postadress');
      			return ;
   			}
		}
		if ( els[i].value == "") {
			alert( els[i].id + ' kan inte vara tom');
			return ;
		}
		eval(els[i].id+"=els[i].value");		
		params += extra+els[i].id + "="+els[i].value;
		extra="&";
	}

	params += "&note="+note;
	
	url = location.href.substring(0,location.href.indexOf(applicationName));	
	

	new Ajax.Request(url + applicationName + "/customers/Prova/try_cust", {
  				method: 'post',
				parameters : params,
  				onSuccess: cust_reply,
  				onFailure:  failed
  		});	

	
	
}

function cust_reply(response ) {
	
// 	url = location.href.substring(0,location.href.indexOf(applicationName));
// 	window.location = url + applicationName +"/customers";


	$('mailconfirmation').innerHTML = response.responseText;
	clearForm();
}

function clearForm(){
	
	var els = ( $$('.box input[type="text"]') );
		for (i=0; els[i];i++ ) {
		els[i].value = "";
	}

}

function removeProposals( document_no ){
	

	url = location.href.substring(0,location.href.indexOf(applicationName));

	new Ajax.Request(url + applicationName + "/customers/Proposals/removeProposal", {
  				method: 'post',
				parameters : "documentno="+document_no,
  				onSuccess: propRemoved,
  				onFailure:  failed
  		});	

	return false;


}

function propRemoved(response){

	//alert(response.responseText);
	url = location.href.substring(0,location.href.indexOf(applicationName));
	window.location = url + applicationName + "/customers/Proposals/favourite";
}

function removeSystemUsers( systemuseremail ){


	url = location.href.substring(0,location.href.indexOf(applicationName));
 	choice = confirm("Är du säker på att du vill ta bort systemet användaren?");
	if (choice == true) {
	new Ajax.Request(url + applicationName + "/admin/System_user/removeSystemUsers", {
  				method: 'post',
				parameters : "systemuseremail="+systemuseremail,
  				onSuccess: systemUserRemoved,
  				onFailure:  failed
  		});
	}
	
	else
	return false;


}

function systemUserRemoved(response){
	$('systemusers').innerHTML = response.responseText;	
}


function showPreview()
{  
    url = location.href.substring(0,location.href.indexOf(applicationName));

    window.open (url + applicationName + "/admin/Card_Info","mywindow","menubar=1,resizable=1,width=350,height=200");


   
}

function showInstructions(){

   url = location.href.substring(0,location.href.indexOf(applicationName));
   myWindow = window.open(url + applicationName + "/admin/Spider_Instructions", "myyWindow", 'toolbar,width=950,height=800,scrollbars=yes') 

}

function moveToEditPropsal(document_no){

 url = location.href.substring(0,location.href.indexOf(applicationName));
 window.location = url + applicationName + "/admin/Admin_Proposals_Add/edit/"+document_no;

}

function testingForSorting(){

	
}

function toggleImage(did){
	$(did).setAttribute("class", "active");

}


function ShowPreview(email)
{
  
  email=(email.replace(/@/, "~~~"));
  url = location.href.substring(0,location.href.indexOf(applicationName));
  window.open(url + applicationName +"/admin/Card_Info_Preview/index/"+email,"Preview","width=1070,height=650,scrollbars=yes,resizable=yes, status=0");
}

function sendEmail(email) {
  answer = confirm("Vill du skicka e-post till"+email + "?");
  if (answer == true){
	email=(email.replace(/@/, "~~~"));
	url = location.href.substring(0,location.href.indexOf(applicationName));

	window.location=url + applicationName +"/admin/Card_Info/sendEmail/"+email;
  }
  else
	return false;  
}

function downloadDueCustomers(){

	url = location.href.substring(0,location.href.indexOf(applicationName));

	window.location = url + applicationName + "/admin/Admin_Export_Customers/download";

	return false;
	

}

//This function handles the special character which creates prolem whhen exists in any parameter sent to the server
function handleSpecialChar( currentObj,varList )
{
    var specialCharList = new Array( "?","#","%","&" );
    var safeCharLsit = new Array( "QUESTIONMARK","HASH","PERCENTAGE","AMPERSAND" );

    for( var i = 0; i < varList.length; i++ )
    {
	 for( var j = 0; j < specialCharList.length; j++ )
	 {
	   
	   var regexp = eval( '/\\' + specialCharList[j] + '/gi') ;

	   currentObj[varList[i]] = currentObj[varList[i]].replace(/\'/gi,"\\'").replace( regexp,safeCharLsit[j] );
	 }
    }
    
}



