// JavaScript Document
$(document).ready(function(){
  checkExtend();
  $('#hide_searchparameters').click(function(e){
    e.preventDefault();
    if($(this).html()=='Näytä lisähakuehdot'){
      $(this).css('background-position','left bottom');
      $(this).html('Piilota lisähakuehdot');
    }else{
      $(this).html('Näytä lisähakuehdot');
      $(this).css('background-position','left top');
    }
    $('#additionalSearchParameters').slideToggle(200);
  });
  
	if ( $('#areaRadios').children("input[checked]").attr('value') == 1 ){
		$('#selArea span').click(function(e){
			selectAreas(e, this);
		});
	} else {
	  $('div.announceType').each(function(){
  		$(this).removeClass('selected');
  		$(this).addClass('disabled');
  		$(this).unbind('click');
  	});
  	$('input.announceType').each(function(){
  	  $(this).attr('checked', false);
  	});
	
		$('#selArea span').click(function(e){
			selectTedAreas(e, this);
		});
	}
  
  //$('.openClose').click(openSubArea);
  //$('#areaList ul li .checkBoxRow .checkBoxDummy').click(selAll);
  $('#selTimespan span').click(selTimespan);
  $('#timespanList li').click(setTimespan);
  
  $('.infoLink, .datePicker').click(toolTip);
  $('#save_search_favorite_inactive, #save_search_listener_inactive, #save_search_favorite_disabled, #save_search_listener_disabled, .favorite_inactive a').click(favToolTip);
  
  $('#cpvCodeList p .right a.remove').click(function(e){
    e.preventDefault();
    var thisPlace = $(this).parent().parent();
    $(this).parent().parent().remove();
    $('#cpvCodeList').append(thisPlace);
    $('#cpvCodeList p:last').html('');
  });
  $('div.searchRadio').click(setRadio);
  //$('.checkBoxRow div.announceType, div.checkBoxDummy, span.checkBoxDummy').click(setBox);
  $('.checkBoxRow div.announceType').click(setBox);
  $('.sectHead').click(sectShow);
  $('.openCloseAll').click(openAllSects);
  $('.announceSectContent .bottomDotRow .favorite a').click(switchStar);
  /*if($('.thisPage').html()){
    $('.thisPage').html('');
    $('.thisPage').each(function(){
      var pageNums = $(this).parent().children('.pageNums').children('ul').children('li').length;
      var actPage = $(this).parent().children('.pageNums').children('ul').children('li.active').html();
      $('.thisPage').html('Sivu '+actPage+'('+pageNums+')');
    });
  }*/
  $('.categoryTabs a').click(changeCatActive);
  $('#save_search_listener').click(saveSearch);
  $('#save_search_favorite').click(saveSearchBookmark);
  $('.edit_search_listener').click(editWatch);
  $("input[type='text']").click(function(){
    //$(this).attr('value','');
    if($(this).attr('name')=='passW'){
      $(this).replaceWith('<input type="password" value="" id="passW" name="passW" />');
      $('#passW').focus();
    }
  });
  
//   $('#save_search_favorite').click(function() {
//     if($(this).html()=='Tallenna haku suosikiksi'){
//       $('[name=saveAsFavorite]').val("1");
//       $(this).html("Älä tallenna hakua");
//     }
//     else {
//       $('[name=saveAsFavorite]').val("0");
//       $(this).html("Tallenna haku suosikiksi");
//     }
//       return false;
//   });
  
  $('#areaListClose').click(function(e){
    e.preventDefault();
	$('#CPVcodesSubmit').unbind('click');
	$('#areaGreyArea').css('display','none');
  });
  $('#clearCPVs').click(clearCPVs);
  $('.freqSel').click(openList);
  $('.freqList ul li').click(selectFreq);
  if($('#allWatchList').html()){
    $('#allWatchList').children('.basicRow').each(function(){
      $(this).children('.frequency').children('.freqSel').each(function(){
        var thisSel = 0;
        $(this).parent().children('.freqRadios').children('.freqRadio').each(function(){
          if($(this).attr('checked')==true){
            thisSel = $(this).attr('class').split('_')[1];
          }
        });
        var thisText = 0;
        if(!$(this).parent().children('.freqList').children('ul').children('.'+thisSel).html()){
          thisText='Kerran viikossa';
        }else{
          thisText = $(this).parent().children('.freqList').children('ul').children('.'+thisSel).html();
        }
        $(this).html(thisText);
      });
    });
  }
  $('#listControl a').click(function(e){
  //e.preventDefault();
  });
  
  $('#loginUser').focus(function() {
    
    if ($(this).attr('value') == "Käyttäjätunnus") {
      $(this).attr('value','');
    }
    
  });
  
  $('#loginUser').blur(function() {
    
    if ($(this).attr('value') == "") {
      $(this).attr('value','Käyttäjätunnus');
    }
    
  });
  
  $('#loginPass').focus(function() {
    
    if ($(this).attr('value') == "Salasana") {
      $(this).attr('value','');
    }
  });
  
  $('#loginPass').blur(function() {
    
    if ($(this).attr('value') == "") {
      $(this).attr('value','Salasana');
    }
  });
  
  /*$('#loginArea input[name=Password]').focus(function(e) {
    
  });*/
  
});

function openList(){
  $(this).parent().children('.freqList').slideToggle(150);
}
function selectFreq(){
  var thisSel = $(this).attr('class');
  var thisVal = 0;
  $(this).parent().parent().parent().children('.freqRadios').children('.freqRadio').each(function(){
    thisVal = $(this).attr('class').split('_')[1];
    if(thisVal==thisSel){
      $(this).attr('checked', true);
    }
  });
  $(this).parent().parent().parent().children('.freqSel').html($(this).html());
  $(this).parent().parent('.freqList').slideUp(150);
}
function clearCPVs(e){
  e.preventDefault();
  $('#areaList div.checkBoxDummy').each(function(){
    if($(this).hasClass('selected')){
      $(this).removeClass(' selected');
      $(this).parent().children('input.checkBoxDummy').attr('checked', false);
      $('#areasList').html('');
    }
  });
  }
function addAreas(e){
  e.preventDefault();
  $('#CPVcodesSubmit').unbind('click');
  $('#areasList').html('');
  var html = '';
  $('#areaList div.checkBoxDummy').each(function(){
    if($(this).hasClass('selected')){
    	$('#areasList').append($(this).parent().children('input'));
		$('#areasList input').each(function(){
          $(this).attr('checked', true);
		})
		if ( html == '' ){
			html = $(this).parent().children('label').html();
		}else{
			html += ', '+ $(this).parent().children('label').html();
		}
    }
  });
  if ( html.length > 45 ){
	html = html.substring(0, 45) +' ...';
  } else if ( html == '' ){
	html = 'Valitse alue(et)';
  }
  $('#selArea span').html(html);
  $('#selArea input#areaString').attr('value', html);
  $('#areaGreyArea').css('display','none');
}

/*function editWatch(e) {
  var wid = $(this).attr("id").split('_')[1];
  
  $('#watchEditForm'+wid).slideToggle('fast');
  xajax_getWatchEditor(wid);  
  
}*/



function editWatch(e){
  e.preventDefault();
  var wid = $(this).attr("id").split('_')[1];
  
  var pos = $(this).offset();
  var conPos = $('#allContainer').offset();
  var watchContent = '<!--<form name="searchSave" id="searchSave" action="post">-->'+
    '<div id="searchSave">'+
    '<input type="text" name="searchName" id="watchName" value="'+$("#watchRow"+wid+" .name").html()+'" />'+
    '<div class="watchSpanContainer">'+
      '<div id="selWatchspan" class="formFull">'+
        '<span>'+$("#watchRow"+wid+" .frequency").html()+'</span>'+
        '<ul id="watchspanList">'+
          '<li value="1" id="sel_1">Joka päivä</li>'+
          '<li value="2" id="sel_2">2 kertaa viikossa</li>'+
          '<li value="3" id="sel_3">Kerran viikossa</li>'+
          '<li value="4" id="sel_4">Kerran kuukaudessa</li>'+
        '</ul>'+
      '</div>'+
      '<select name="selWatchspan" id="watchspanList_sel">'+
        '<option value="0">Valitse lähetystiheys</option>'+
        '<option value="1">Joka päivä</option>'+
        '<option value="2">2 kertaa viikossa</option>'+
        '<option value="3">Kerran viikossa</option>'+
        '<option value="4">Kerran kuukaudessa</option>'+
      '</select>'+
    '</div>'+
    '<div id="validUntil">'+
    '<!--<p>Voimassaoloaika (saakka)</p>'+
    '<input type="text" name="watchEnd_d" id="watchName_d" value="pp" /> . '+
    '<input type="text" name="watchEnd_m" id="watchName_m" value="kk" /> . '+
    '<input type="text" name="watchEnd_y" id="watchName_y" value="vvvv" />'+
    '<span class="datePicker" id="watchEnd"></span>'+
    '<div class="clear"></div>'+
    '<div class="watchType" id="watchType_1"></div>'+
    '<input type="checkbox" name="watchType" class="watchType" value="1" /><label>Toistaiseksi</label>-->'+
    '<a id="watchSubmit" href="#" onclick="processWatch('+wid+');return false;">Tallenna</a>'+
    '<!--<input type="submit" value="tallenna" name="submit" id="watchSubmit" />-->'+
    '<div id="saveWatchInfo"></div>'+
    '<div class="clear"></div>'+
    '</div>'+
    '</div>'+
    '<!--</form>-->'+
    '<div id="watchCalendar">'+
      '<a href="#" id="setWatchEnd">Seivaa päivä: 19.9. 2019</a>'+
    '</div>';
  $('.toolTip .toolContent .headBar h3').html('');
  $('.toolTip .toolContent .toolText').html('');
  $('.toolTip .toolContent .headBar h3').html($(this).html());
  $('.toolTip .toolContent .toolText').html(watchContent);
  
  $('#toolTip_down').css('top',(pos.top-$('#toolTip_down').height())+'px');
  $('#toolTip_down').css('left',(pos.left-23)+'px');
  $('#toolTip_down').css('display','block');
  $('.toolTip .headBar a.close').click(function(e){
    e.preventDefault();
    $(this).parent().parent().parent().css('display','none');
  });
  $('.watchType').click(setWatchBox);
  $('#selWatchspan span').click(selWatchspan);
  $('#watchspanList li').click(setWatchspan);
  $('#watchEnd').click(showWatchCalen);
  $("input[type='text']").click(function(){$(this).attr('value','');});
}


function saveSearchBookmark(e){
  e.preventDefault();
  var pos = $(this).offset();
  var conPos = $('#allContainer').offset();
  var watchContent = '<div id="searchSave">'+
    '<input type="text" name="searchName" id="bookmarkName" value="Nimeä haku" />'+
    '<div class="clear"></div>'+
    '<div id="validUntil">'+
    '<a id="watchSubmit" href="#" onclick="submitBookmark();return false;">Tallenna</a>'+
    '<div id="bookmarkSaveInfo">'+
    '<div class="clear"></div>'+
    '</div>'+
    '</div>'+
    '</div>';
  $('.toolTip .toolContent .headBar h3').html('');
  $('.toolTip .toolContent .toolText').html('');
  $('.toolTip .toolContent .headBar h3').html($(this).html());
  $('.toolTip .toolContent .toolText').html(watchContent);
  
  $('#toolTip_down').css('top',(pos.top-$('#toolTip_down').height())+'px');
  $('#toolTip_down').css('left',(pos.left-23)+'px');
  $('#toolTip_down').css('display','block');
  $('.toolTip .headBar a.close').click(function(e){
    e.preventDefault();
    $(this).parent().parent().parent().css('display','none');
  });
  $('.watchType').click(setWatchBox);
  $('#selWatchspan span').click(selWatchspan);
  $('#watchspanList li').click(setWatchspan);
  $('#watchEnd').click(showWatchCalen);
  $("input[type='text']").click(function(){$(this).attr('value','');});
}

function saveSearch(e){
  e.preventDefault();
  var pos = $(this).offset();
  var conPos = $('#allContainer').offset();
  var watchContent = '<!--<form name="searchSave" id="searchSave" action="post">-->'+
    '<div id="searchSave">'+
    '<input type="text" name="searchName" id="watchName" value="Nimeä vahti" />'+
    '<div class="watchSpanContainer">'+
      '<div id="selWatchspan" class="formFull">'+
        '<span>Valitse lähetystiheys</span>'+
        '<ul id="watchspanList">'+
          '<li value="1" id="sel_1">Joka päivä</li>'+
          '<li value="2" id="sel_2">2 kertaa viikossa</li>'+
          '<li value="3" id="sel_3">Kerran viikossa</li>'+
          '<li value="4" id="sel_4">Kerran kuukaudessa</li>'+
        '</ul>'+
      '</div>'+
      '<select name="selWatchspan" id="watchspanList_sel">'+
        '<option value="0">Valitse lähetystiheys</option>'+
        '<option value="1">Joka päivä</option>'+
        '<option value="2">2 kertaa viikossa</option>'+
        '<option value="3">Kerran viikossa</option>'+
        '<option value="4">Kerran kuukaudessa</option>'+
      '</select>'+
    '</div>'+
    '<div id="validUntil">'+
    '<!--<p>Voimassaoloaika (saakka)</p>'+
    '<input type="text" name="watchEnd_d" id="watchName_d" value="pp" /> . '+
    '<input type="text" name="watchEnd_m" id="watchName_m" value="kk" /> . '+
    '<input type="text" name="watchEnd_y" id="watchName_y" value="vvvv" />'+
    '<span class="datePicker" id="watchEnd"></span>'+
    '<div class="clear"></div>'+
    '<div class="watchType" id="watchType_1"></div>'+
    '<input type="checkbox" name="watchType" class="watchType" value="1" /><label>Toistaiseksi</label>-->'+
    '<a id="watchSubmit" href="#" onclick="submitWatch();return false;">Tallenna</a>'+
    '<!--<input type="submit" value="tallenna" name="submit" id="watchSubmit" />-->'+
    '<div id="saveWatchInfo"></div>'+
    '<div class="clear"></div>'+
    '</div>'+
    '</div>'+
    '<!--</form>-->'+
    '<div id="watchCalendar">'+
      '<a href="#" id="setWatchEnd">Seivaa päivä: 19.9. 2019</a>'+
    '</div>';
  $('.toolTip .toolContent .headBar h3').html('');
  $('.toolTip .toolContent .toolText').html('');
  $('.toolTip .toolContent .headBar h3').html($(this).html());
  $('.toolTip .toolContent .toolText').html(watchContent);
  
  $('#toolTip_down').css('top',(pos.top-$('#toolTip_down').height())+'px');
  $('#toolTip_down').css('left',(pos.left-23)+'px');
  $('#toolTip_down').css('display','block');
  $('.toolTip .headBar a.close').click(function(e){
    e.preventDefault();
    $(this).parent().parent().parent().css('display','none');
  });
  $('.watchType').click(setWatchBox);
  $('#selWatchspan span').click(selWatchspan);
  $('#watchspanList li').click(setWatchspan);
  $('#watchEnd').click(showWatchCalen);
  $("input[type='text']").click(function(){$(this).attr('value','');});
}
function showWatchCalen(){
  $('#searchSave').css('visibility','hidden');
  $('#watchCalendar').css('visibility','visible');
  $('#setWatchEnd').click(function(){
    $('#watchName_d').attr('value','19');
    $('#watchName_m').attr('value','09');
    $('#watchName_y').attr('value','2019');
    $('#searchSave').css('visibility','visible');
  $('#watchCalendar').css('visibility','hidden');
  });
}
function selWatchspan(){
  $('#watchspanList').slideDown(150);
  $('body').click(function(){$('#watchspanList').css('display','none');});
}
function setWatchspan(){
  $('#watchspanList_sel option').removeAttr('selected');
  var sel = $(this).attr('value');
  $('#watchspanList_sel option[value="'+sel+'"]').attr('selected','selected');
  $('#watchspanList').css('display','none');
  $('#selWatchspan span').html($(this).html());
  /*$('#selWatchspan span').click(function(){$(this).html('Joka päivä');});*/
}


function openAllSects(e){
  e.preventDefault();
  var k=0;
  var y=0;
  if($(this).parent().parent().children('.sectBlock').html()){
    $(this).parent().parent().children('.sectBlock').each(function(){
      y=y+1;
      if($(this).children('.sectContent').css('display')=='none'){k=k+1;}
      else{k=k-1;}
    });
  }else if($(this).parent().parent().parent().children('.sectBlock').html()){
    $(this).parent().parent().parent().children('.sectBlock').each(function(){
      y=y+1;
      if($(this).children('.sectContent').css('display')=='none'){k=k+1;}
      else{k=k-1;}
    });
  }
  if((y+k)>0){
    $('.sectContent').slideDown(150);
    $('.sectHead').children('.sectopenClose').css('background-position','left top');
  }else{
    $('.sectContent').slideUp(150);
    $('.sectHead').children('.sectopenClose').css('background-position','left bottom');
  }
}

function sectShow(){
  var target = $(this).parent().children('.sectContent');
  var direct = target.css('display');
  if(direct=='none'){
    $(this).children('.sectopenClose').css('background-position','left top');
    target.slideDown(150);
  }else{
    $(this).children('.sectopenClose').css('background-position','left bottom');
    target.slideUp(150);
    target.removeClass(' open');
  }
}
function changeCatActive(e){
  e.preventDefault();
  var thisId = $(this).attr('id');
  $(this).parent().children('a').each(function(){
    if($(this).attr('id')==thisId && $(this).attr('id').split('_')[1]!='active'){
      $(this).attr('id', $(this).attr('id')+'_active');
    }else if($(this).attr('id')==thisId){
      return;
    }else{
      $(this).attr('id', $(this).attr('id').split('_')[0]);
    }
  });
}

function switchStar(e){
  e.preventDefault();
  var starPos = $(this).attr('class');
  if(starPos=='no'){
    $(this).attr('class','yes');
  }else{
    $(this).attr('class','no');
  }
}
function setBox(){
  if(!$(this).hasClass('disabled')){
  var thisNum = $(this).attr('id').split('_')[1];
  if(!$(this).hasClass('selected')){
    $(this).attr('class',$(this).attr('class')+' selected');
    $('input.announceType').each(function(){
      if($(this).attr('value')==thisNum){
        $(this).attr('checked', true);
      }
    });
  }else{
    $(this).removeClass(' selected');
    $('input.announceType').each(function(){
      if($(this).attr('value')==thisNum){
        $(this).attr('checked', false);
      }
    });
  }
  }else{
	  //alert('nou kän too');
  }
}

function setWatchBox(){
  var thisNum = $(this).attr('id').split('_')[1];
  if(!$(this).hasClass('selected')){
    $(this).attr('class',$(this).attr('class')+' selected');
    $('input.watchType').each(function(){
      if($(this).attr('value')==thisNum){
        $(this).attr('checked', true);
      }
    });
  }else{
    $(this).removeClass(' selected');
    $('input.watchType').each(function(){
      if($(this).attr('value')==thisNum){
        $(this).attr('checked', false);
      }
    });
  }
}

function setRadio(){
  $('#areasList').html('');
  var thisNum = $(this).attr('id').split('_')[1];
  thisNum=thisNum.split('-')[0];
  var thisSel = $(this).attr('id').split('-')[1];
  $('div.searchRadio').css('background-position','left top');//visual help for IE6...
  $(this).css('background-position','left bottom');//..after this the actual code continues.
  if(thisSel!='radioSelected'){
    $('div.searchRadio').each(function(){
      $(this).attr('id',($(this).attr('id').split('-')[0]));
    });
    $(this).attr('id',('areaRadio_'+thisNum+'-radioSelected'));
    $('input.searchRadio').each(function(){
      if($(this).attr('value')==thisNum){
        $(this).attr('checked', true);

		switch ( thisNum ){
			case '1':
				$('#selArea span').unbind('click'); // ihan varmuuden vuoksi
	     		$('#selArea span').click(function(e){
					selectAreas(e, this);
			  	});
				$('#selArea span').html('Valitse alue(et)');
				$('#areaString').attr('value','Valitse alue(et)');
				$('div.announceType').each(function(){
					$(this).removeClass('disabled');
					$(this).click(setBox);
				});
			break;
			case '2':
				$('#selArea span').unbind('click');
				$('#selArea span').click(function(e){
				  selectTedAreas(e, this);
          		});
				$('#selArea span').html('Valitse maa(t)');
				$('#areaString').attr('value','Valitse maa(t)');
				$('div.announceType').each(function(){
					$(this).removeClass('selected');
					$(this).addClass('disabled');
					$(this).unbind('click');
				});
				$('input.announceType').each(function(){
				  $(this).attr('checked', false);
				});
			break;
		}

      }
    });
  }else{
    return;
  }
}

function favToolTip(e){
  e.preventDefault();
  var thisClass = $(this).attr('class').split(' ')[0];
  
  if ($(this).attr('id')!="") {
  
  var additionalClass = $(this).attr('id').split('_')[3];
  }
  
  var pos = $(this).offset();
  var conPos = $('#allContainer').offset();
  var tooltipId = '';
  
  //*** poista muut auki olevat tooltipit
  var tmp = [ 'toolTip_down', 'toolTip_right', 'toolTip_left' ];
  jQuery.each(tmp, function() {
    if ( $('#'+ this).css('display') == 'block' ){
	  if ( $('#'+ this +' .toolContent .toolText #calendarViewUi') ){
	    $('#'+ this +' .toolContent .toolText #calendarViewUi').datepicker('destroy');
		$('#'+ this +' .toolContent .toolText').removeClass('calContainer');
	  }
	  $('#'+ this +' .toolContent .toolText').html('');
	  $('#'+ this +' #calActive').removeAttr('id');
      $('#'+ this).css('display','none');
    }
  })
  
  if(pos.top-conPos.top<'200'){
    if(pos.left-conPos.left<'450'){/*toolTip_right*/
      $('#toolTip_right').css('top',(pos.top-38)+'px');
      $('#toolTip_right').css('left',(pos.left+20)+'px');
	  tooltipId = 'toolTip_right';
      //$('#toolTip_right').css('display','block');
    }else{/*toolTip_left*/
      $('#toolTip_left').css('top',(pos.top-38)+'px');
      $('#toolTip_left').css('left',(pos.left-222)+'px');
	  tooltipId = 'toolTip_left';
      //$('#toolTip_left').css('display','block');
    }
  }else if(pos.left-conPos.left>'790'){/*toolTip_left*/
    $('#toolTip_left').css('top',(pos.top-38)+'px');
    $('#toolTip_left').css('left',(pos.left-222)+'px');
	tooltipId = 'toolTip_left';
    //$('#toolTip_left').css('display','block');
  }else if(pos.left-conPos.left<'100'){/*toolTip_right*/
    $('#toolTip_right').css('top',(pos.top-38)+'px');
    $('#toolTip_right').css('left',(pos.left+20)+'px');
	tooltipId = 'toolTip_right';
    //$('#toolTip_right').css('display','block');
  }else{/*toolTip_down*/
    $('#toolTip_down').css('top',(pos.top-$('#toolTip_down').height())+'px');
    
    if (thisClass == "favorite_inactive") {
      $('#toolTip_down').css('left',(pos.left-93+65-22)+'px');
    }
    else {
      $('#toolTip_down').css('left',(pos.left-93+65)+'px');
    }
	tooltipId = 'toolTip_down';
    //$('#toolTip_down').css('display','block');
  }
  
  $('#'+ tooltipId +' .toolContent .headBar h3').html('');
  $('#'+ tooltipId +' .toolContent .toolText').html('');
  
  $('#'+ tooltipId +' .toolContent .headBar h3').html($(this).attr('title'));
  
  
  if (additionalClass == "disabled") {
  
  $('#'+ tooltipId +' .toolContent .toolText').html("Tämä toiminto on käytettävissä vain haun tekemisen yhteydessä.");
  }
  else {
  $('#'+ tooltipId +' .toolContent .toolText').html("Tämä toiminto on käytettävissä vain vahtipalvelun tilanneilla käyttäjillä. Lue lisää <a href='/index.php/hankintatieto/Vahtipalvelu/'>tästä!</a>");
  }
  
  $('#'+ tooltipId).css('display','block');

  $('#'+ tooltipId +' .headBar a.close').click(function(e){
    e.preventDefault();
	
	$('#'+ tooltipId +' .toolContent .toolText').html('');
	$('#'+ tooltipId +' .toolContent .toolText').removeClass('calContainer');
	
    $(this).parent().parent().parent().css('display','none');
	
  });
}

function toolTip(){

  $(this).attr('id','calActive');
  var thisClass = $(this).attr('class').split(' ')[0];
  var pos = $(this).offset();
  var conPos = $('#allContainer').offset();
  var tooltipId = '';
  
  //*** poista muut auki olevat tooltipit
  var tmp = [ 'toolTip_down', 'toolTip_right', 'toolTip_left' ];
  jQuery.each(tmp, function() {
    //if ( $('#'+ this).css('display') == 'block' ){
	  if ( $('#'+ this +' .toolContent .toolText #calendarViewUi') ){
	    $('#'+ this +' .toolContent .toolText #calendarViewUi').datepicker('destroy');
		$('#'+ this +' .toolContent .toolText').removeClass('calContainer');
	  }
	  $('#'+ this +' .toolContent .toolText').html('');
	  $('#'+ this +' #calActive').removeAttr('id');
      $('#'+ this).css('display','none');
    //}
  })
  
  if(pos.top-conPos.top<'200'){
    if(pos.left-conPos.left<'450'){/*toolTip_right*/
      $('#toolTip_right').css('top',(pos.top-38)+'px');
      $('#toolTip_right').css('left',(pos.left+20)+'px');
	  tooltipId = 'toolTip_right';
      //$('#toolTip_right').css('display','block');
    }else{/*toolTip_left*/
      $('#toolTip_left').css('top',(pos.top-38)+'px');
      $('#toolTip_left').css('left',(pos.left-222)+'px');
	  tooltipId = 'toolTip_left';
      //$('#toolTip_left').css('display','block');
    }
  }else if(pos.left-conPos.left>'790'){/*toolTip_left*/
    $('#toolTip_left').css('top',(pos.top-38)+'px');
    $('#toolTip_left').css('left',(pos.left-222)+'px');
	tooltipId = 'toolTip_left';
    //$('#toolTip_left').css('display','block');
  }else if(pos.left-conPos.left<'100'){/*toolTip_right*/
    $('#toolTip_right').css('top',(pos.top-38)+'px');
    $('#toolTip_right').css('left',(pos.left+20)+'px');
	tooltipId = 'toolTip_right';
    //$('#toolTip_right').css('display','block');
  }else{/*toolTip_down*/
    $('#toolTip_down').css('top',(pos.top-$('#toolTip_down').height())+'px');
    $('#toolTip_down').css('left',(pos.left-93)+'px');
	tooltipId = 'toolTip_down';
    //$('#toolTip_down').css('display','block');
  }
  calVar = '#'+ $(this).attr('class').split(' ')[1];
  $('#'+ tooltipId +' .toolContent .headBar h3').html('');
  $('#'+ tooltipId +' .toolContent .toolText').html('');
  if(thisClass=='datePicker'){
    $('#'+ tooltipId +' .toolContent .headBar h3').html('Valitse p&auml;iv&auml;');
    $('#'+ tooltipId +' .toolContent .toolText').attr('class',$('#'+ tooltipId +' .toolContent .toolText').attr('class')+' calContainer');
    $('#'+ tooltipId +' .toolContent .toolText').html('<div id="calendarViewUi"></div>');
	$('#'+ tooltipId +' .toolContent .toolText #calendarViewUi').datepicker({ 
	  duration: '', 
	  altField: '#'+ $(this).attr('class').split(' ')[1], 
	  altFormat: 'dd.mm.yy',
	  firstDay: 1,
	  monthNames: [
		'tammikuu','helmikuu','maaliskuu','huhtikuu','toukokuu','kesäkuu','heinäkuu','elokuu','syyskuu','lokakuu','marraskuu','joulukuu'],
	  dayNamesMin: ['Su', 'Ma', 'Ti', 'Ke', 'To', 'Pe', 'La'],
	  onSelect: function(dateText, inst, tooltipId) { 
	  	//alert($(inst).attr('id'));
	  	
		$('.toolTip').css('display','none');
		$('#'+ tooltipId +' .toolContent .toolText #calendarViewUi').datepicker('destroy');
		//$(calVar).attr('value',dateText);
	  }
	});
	if ( calVar == '#dateEnd' )
	{
		if ( $('#dateStart').attr('value') != '' )
		{
			var year = $('#dateStart').attr('value').split('.')[2];
			var month = $('#dateStart').attr('value').split('.')[1];
			var date = $('#dateStart').attr('value').split('.')[0];
			$('#'+ tooltipId +' .toolContent .toolText #calendarViewUi').datepicker('option', 'minDate', new Date(year, month - 1, date));
		}
	} else if ( calVar == '#dateStart' )
	{
		if ( $('#dateEnd').attr('value') != '' )
		{
			var year = $('#dateEnd').attr('value').split('.')[2];
			var month = $('#dateEnd').attr('value').split('.')[1];
			var date = $('#dateEnd').attr('value').split('.')[0];
			$('#'+ tooltipId +' .toolContent .toolText #calendarViewUi').datepicker('option', 'maxDate', '-0d');
		}
	}

  }else{
    $('#'+ tooltipId +' .toolContent .headBar h3').html($(this).attr('title'));
    $('#'+ tooltipId +' .toolContent .toolText').html($(this).html());
  }
  
  $('#'+ tooltipId).css('display','block');

  $('#'+ tooltipId +' .headBar a.close').click(function(e){
    e.preventDefault();
	$('#'+ tooltipId +' .toolContent .toolText #calendarViewUi').datepicker('destroy');
	$('#'+ tooltipId +' .toolContent .toolText').html('');
	$('#'+ tooltipId +' .toolContent .toolText').removeClass('calContainer');
	$('#'+ tooltipId +' #calActive').removeAttr('id');
    $(this).parent().parent().parent().css('display','none');
	
  });
  $('#calendarView .cancel').click(function(e){
    e.preventDefault();
    $('.toolTip').css('display','none');//Tämä vasta vahtipalvelu-sivulla, eri toiminto vahdin tallennukseen
  });
  $('#calendarView .save').click(function(e){
    e.preventDefault();
    var k=0;
    $(this).parent().children('table').children('tbody').children('tr').each(function(){
      $(this).children('td').each(function(){
        if($(this).attr('class')=='selected'){
          k=$(this).html(); 
        }
      });
    });
    $('#calActive').parent().children('.date').html('p&auml;&auml;ttyy '+k+'. p&auml;iv&auml');
    $('.toolTip').css('display','none');//Tämä vasta vahtipalvelu-sivulla, eri toiminto vahdin tallennukseen
    $('#calActive').parent().children('.datePicker').removeAttr('id');
  });
  /*
  $('#calendarView table td').click(function(){
    if($(this).html()){
      if($(this).parent().attr('class')!='head'){
        if($(this).attr('class')!='selected'){
          $('#calendarView table td').removeAttr('class');
          $(this).attr('class','selected');
        }
      }
    }
  });
  $('#calendarView table td').each(function(){
    if(!$(this).html()){
      $(this).css('visibility','hidden');
    }
  });
  */
}

function checkExtend(){
  $('#areaList ul li').each(function(){
    var thisBgHelp = $(this).css('background-image').split('/').length-1;
    var thisBg = $(this).css('background-image').split('/')[thisBgHelp].split('.gif')[0].split('-')[1];
    if(!$(this).children('ul').html()){
      switch(thisBg){
        case '1':
        $(this).children('.openClose').css('background-position','0 -42px');
        break;
        case '2':
        $(this).children('.openClose').css('background-position','-24px -42px');
        break;
        case '3':
        $(this).children('.openClose').css('background-position','-48px -42px');
        break;
        case '4':
        $(this).children('.openClose').css('background-position','-72px -42px');
        break;
      }
    }
  });
}

function openSubArea(e){
  e.preventDefault();
  var thisBgHelp = $(this).parent().css('background-image').split('/').length-1;
  var thisBg = $(this).parent().css('background-image').split('/')[thisBgHelp].split('.gif')[0].split('-')[1];
  var openState = $(this).parent().children('ul').css('display');
  var thisState = thisBg+' '+openState;
  
  /*IE 7:lla tilttaa leiska kun laatokon valitsee, muuten toimii*/
  switch(thisState){
    case '1 none':
      $(this).css('background-position','0 -21px');
    break;
    case '1 block':
      $(this).css('background-position','0 0');
    break;
    case '2 none':
      $(this).css('background-position','-24px -21px');
    break;
    case '2 block':
      $(this).css('background-position','-24px 0');
    break;
    case '3 none':
      $(this).css('background-position','-48px -21px');
    break;
    case '3 block':
      $(this).css('background-position','-48px 0');
    break;
    case '4 none':
      $(this).css('background-position','-72px -21px');
    break;
    case '4 block':
      $(this).css('background-position','-72px 0');
    break;
  }
  $(this).parent().children('ul').slideToggle(150);
}

function selAll(){
  var nextBoxes = $(this).parent().parent().children('ul').children('li').children('div').children('input');
  if($(this).parent().children('input').attr('checked')){
    nextBoxes.attr('checked', false);
    $(this).parent().parent().children('ul').children('li').children('.checkBoxRow').children('div.checkBoxDummy').removeClass(' selected');
  }else{
    nextBoxes.attr('checked', true);
    $(this).parent().parent().children('ul').children('li').children('.checkBoxRow').children('div.checkBoxDummy').attr('class',$(this).parent().parent().children('ul').children('li').children('.checkBoxRow').children('.checkBoxDummy').attr('class')+' selected');
  }
}

// JavaScript Document

$(document).ready(function(){
	$('a#clearFields').click( function(e) { clearSearchForm(e) });
	//$('a#addCPVcode').click( function(e) { addCpvCode(e, false, false) });
	$('a#addCPVcode').click( function(e) { CPVCodeFunctions.add(e, false, false) });
	$('input#searchByWordField').keyup( function(e) { searchCpvWheal.modified(this) });
	$('input#additionalCPVcode').keyup( function(e) { searchCpvWheal.modified(this) });
	//$('#openCpvTree').click( function(e) { cpvCodeTree(e, this) });
	$('#openCpvTree').click( function(e) { CPVCodeFunctions.openTree(e, this) });
})

function selTimespan(){
  $('#timespanList').slideDown(150);
  $('body').click(function(){$('#timespanList').css('display','none');});
}

function setTimespan(){
	$('#selTimespan span').html($(this).html());
	xajax_getEuribor($(this).attr('id'), $(this).html());
}

function selectAreas(e, obj){
	e.preventDefault();
	$('#areaListContent').html('Ladataan...');
    xajax_getAreas();
	var viewportHeight = parseInt((document.height !== undefined) ? document.height : document.body.offsetHeight);
	if ( $('html').height() > viewportHeight ){
		viewportHeight = $('html').height();
	}
	$('#areaGreyArea').css('height',viewportHeight+'px');
	$('#areaList h3').html('Alueluettelo');
    $('#areaGreyArea').fadeIn(150);
}

function selectTedAreas(e, obj){
	e.preventDefault();
	$('#areaListContent').html('Ladataan...');
    xajax_getTedAreas();
	var viewportHeight = parseInt((document.height !== undefined) ? document.height : document.body.offsetHeight);
	if ( $('html').height() > viewportHeight ){
		viewportHeight = $('html').height();
	}
	$('#areaGreyArea').css('height',viewportHeight+'px');
	$('#areaList h3').html('Maat');
    $('#areaGreyArea').fadeIn(150);
}

var CPVCodeFunctions = {
	objects: new Object(),
	openTree: function (e, obj){
		e.preventDefault();
		$('#areaListContent').html('Ladataan...');
		xajax_getCpvCodeTree('', 1, this.objects);
		var viewportHeight = parseInt((document.height !== undefined) ? document.height : document.body.offsetHeight);
		if ( $('html').height() > viewportHeight ){
			viewportHeight = $('html').height();
		}
		$('#areaGreyArea').css('height',viewportHeight+'px');
		$('#areaList h3').html('CPV-koodit');
		$('#areaGreyArea').fadeIn(150);
	},
	add : function(e, value, description){
		var doUpdate = false;
		if ( e != false ){
			e.preventDefault();
		}
		if ( value == false && description == false ){
			doUpdate = true;
		}
		if ( value == false ){
			if ( (value = $('#additionalCPVcode').attr('value')) == '') {
				return;
			}
		}
		if ( description == false ){
			var description = xajax.call("getCpvCodes",{parameters:[value, true],mode:'synchronous'});
		}
		this.objects[value] = new Object();
		this.objects[value] = description;
		if ( doUpdate == true ){
			this.update();
		}
	},
	addObjects : function(e){
		if ( e != false ){
			e.preventDefault();
		}
		var sendArray = new Array();
		$('#CPVcodesSubmit').unbind('click');
		$('#areaList div.checkBoxDummy').each(function(){
			if($(this).hasClass('selected') && !$(this).hasClass('disabled'))
			{
				CPVCodeFunctions.add(false, $(this).parent().children('input').attr('value'), $(this).parent().children('label').html().substr(9));
				// *** $subTree, $parentCpv, $parentDesc
				/*
				sendArray[sendArray.length] = $(this).parent().children('.checkBoxDummy').attr('id').split('_')[2] +'|'+ $(this).parent().children('input').attr('value') +'|'+ $(this).parent().children('label').html().substr(9);
				this.objectsCount++;
				*/
			}
		});
		CPVCodeFunctions.update();
		$('#areaGreyArea').css('display','none');
		//xajax_addCpvCodeTree(sendArray);
	},
	update: function(){
		$('#cpvCodeListContent').html('');
		$('#cpvCodeListInputs').html('');
		var counter = 1;
		jQuery.each(this.objects, function(cpv, desc) {
			$('#cpvCodeListContent').append('<p id="cpvCode_'+ counter +'"><span class="left">'+ desc +'</span><span class="center">'+ cpv +'</span><span class="right"><a href="#" class="remove" onclick="CPVCodeFunctions.remove(\'cpvCode_'+ counter +'\');return false;">Poista</a></span></p>');
			$('#cpvCodeListInputs').append('<input type="checkbox" name="cpvCode[]" class="checkBoxDummy" checked="checked" value="'+ cpv +'" />');
			counter++;
		});
	},
	remove: function(id){
		if ( $('#'+ id) ){
			delete this.objects[$('#'+ id).children('.center').html()];
			$('#cpvCodeListInputs [value=\''+ $('#'+ id).children('.center').html() +'\']').remove();
			$('#'+ id).remove();
		}
	},
	removeAll: function(){
		this.objects = new Object();
	},
	openSubArea: function (e, obj){
		e.preventDefault();
		content = $(obj).parent().children('ul');
		if ( content.html() == '' ){
			content.html('<li style="background-image:none;">Ladataan...</li>');
			tmp = $(obj).parent().children('.checkBoxRow').children('.checkBoxDummy').attr('id').split('_');
			xajax_getCpvCodeTree(tmp[1], tmp[2], this.objects);
			
		}
		var thisBgHelp = $(obj).parent().css('background-image').split('/').length-1;
		var thisBg = $(obj).parent().css('background-image').split('/')[thisBgHelp].split('.gif')[0].split('-')[1];
		var openState = $(obj).parent().children('ul').css('display');
		var thisState = thisBg+' '+openState;
		
		/*IE 7:lla tilttaa leiska kun laatokon valitsee, muuten toimii*/
		switch(thisState){
			case '1 none':
				$(obj).css('background-position','0 -21px');
			break;
			case '1 block':
				$(obj).css('background-position','0 0');
			break;
			case '2 none':
				$(obj).css('background-position','-24px -21px');
			break;
			case '2 block':
				$(obj).css('background-position','-24px 0');
			break;
			case '3 none':
				$(obj).css('background-position','-48px -21px');
			break;
			case '3 block':
				$(obj).css('background-position','-48px 0');
			break;
			case '4 none':
				$(obj).css('background-position','-72px -21px');
			break;
			case '4 block':
				$(obj).css('background-position','-72px 0');
			break;
		}
		$(obj).parent().children('ul').slideToggle(150);
	},
	setBox: function ()
	{
		if(!$(this).hasClass('disabled')){
			var thisNum = $(this).attr('id').split('_')[1];
			if(!$(this).hasClass('selected')){
				$(this).attr('class',$(this).attr('class')+' selected');
				$('input.announceType').each(function(){
					if($(this).attr('value')==thisNum){
						$(this).attr('checked', true);
					}
				});
				/*
				if ( $(this).parent().parent().children('ul').html() != '' ){
					var obj = $(this).parent().parent().children('ul');
					CPVCodeFunctions.setChildBox(obj, true);
				}
				*/
			}else{
				$(this).removeClass(' selected');
				$('input.announceType').each(function(){
					if($(this).attr('value')==thisNum){
						$(this).attr('checked', false);
					}
				});
				/*
				if ( $(this).parent().parent().children('ul').html() != '' ){
					var obj = $(this).parent().parent().children('ul');
					CPVCodeFunctions.setChildBox(obj, false);
				}
				*/
			}
		}
	},
	checkParentBoxStatus: function (id)	{
		if ( $('#'+ id).hasClass('selected') ){
			this.setChildBox($('#'+ id).parent().parent().children('ul'), true);
		}
	},
	setChildBox: function (obj, selected){
		$(obj).children('li').each(function(){
			if ( selected == true )	{
				$(this).children('div.checkBoxRow').children('div.checkBoxDummy').addClass('selected');
				$(this).children('div.checkBoxRow').children('div.checkBoxDummy').addClass('disabled');
				$(this).children('input.announceType').attr('checked', true);
				$(this).children('div.checkBoxRow').children('div.checkBoxDummy').unbind('click');
				if ( $(obj).children('li').children('ul').html() != '' ){
					CPVCodeFunctions.setChildBox($(obj).children('li').children('ul'), true);
				}
			}else{
				$(this).children('div.checkBoxRow').children('div.checkBoxDummy').removeClass('selected');
				$(this).children('div.checkBoxRow').children('div.checkBoxDummy').removeClass('disabled');
				$(this).children('input.announceType').attr('checked', false);
				$(this).children('div.checkBoxRow').children('div.checkBoxDummy').click(CPVCodeFunctions.setBox);
				if ( $(obj).children('li').children('ul').html() != '' ){
					CPVCodeFunctions.setChildBox($(obj).children('li').children('ul'), false);
				}
			}
		})
	}
}

var searchCpvWheal = {
	bufferText: false,
	bufferTime: 500,
	object: false,
	
	modified : function(obj){
		this.object = obj;
		/*
		if ( $(this.object).attr('id') == 'searchByWordField' ){
			if ( $(this.object).attr('value') != $("#searchByWordFieldHidden").attr('value') ){
				$("#searchByWordFieldHidden").attr('value', '');
			}
		}
		*/
		//console.debug('|'+$("#searchByWordField").attr('value')+'|');
		if ( $("#searchByWordField").attr('value') == '' || $("#searchByWordField").attr('value').length < 3 )
		{
			$('#searchByWordFieldHidden').attr('value', '');
		}
		setTimeout('searchCpvWheal.compareBuffer();', this.bufferTime);
	},
	
	compareBuffer : function(){
		strText = $(this.object).attr('value');
		if ( strText != this.bufferText && strText.length > 2){
			this.bufferText = strText;
			searchCpvWheal.makeRequest();
		}
	},
	
	makeRequest : function(){
		xajax_getCpvCodes($(this.object).attr('value'));
	},
	
	showResults : function(){
		if ( $(this.object).attr('id') == 'additionalCPVcode' ){
			var offset = $('#cpvCodeBox .additionalSearchBox').parent().position();
			var offset2 = $("#additionalCPVcode").position();
			var top = offset.top + offset2.top + $("#additionalCPVcode").height() + 2;
			var left = offset.left + offset2.left + 15;
			if ( $('#cpvSearchResults').hasClass('cpvSearchResultsBig') == true ){
				$('#cpvSearchResults').removeClass('cpvSearchResultsBig');
			}
		}else{
			var offset = $("#searchByWordField").position();
			var top = 155; //offset.top + $("#searchByWordField").height() + 2;
			var left = offset.left + 15;
			if ( $('#cpvSearchResults').hasClass('cpvSearchResultsBig') == false ){
				$('#cpvSearchResults').addClass('cpvSearchResultsBig');
			}
		}
		if ( $('#cpvSearchResults').css('display') == 'none' ){
			$('#cpvSearchResults').css('top', top);
			$('#cpvSearchResults').css('left', left);
			$('#cpvSearchResults').toggle();
			$('body').click(function(){searchCpvWheal.hideResults()});
		}
	},
	
	hideResults : function(){
		$('body').unbind('click', searchCpvWheal.hideResults)
		$('#cpvSearchResults').html('');
		//$('#cpvSearchResults').toggle();
		$('#cpvSearchResults').css('display','none');
	},
	
	select : function(e, obj){
		e.preventDefault();
		//alert($(this.object).attr('id'));
		if ( $(this.object).attr('id') == 'additionalCPVcode' ){
			CPVCodeFunctions.add(e, $(obj).html().substr(0, 8), $(obj).html().substr(9));
			CPVCodeFunctions.update();
			//addCpvCode(e, $(obj).html().substr(0, 8), $(obj).html().substr(9));
		}else{
			//$("#searchByWordField").attr('value', $(obj).html().substr(9));
			$("#searchByWordField").attr('value', $(obj).html());
			$("#searchByWordFieldHidden").attr('value', $(obj).html().substr(0, 8));
		}
		searchCpvWheal.hideResults();
	}
}

function checkAreaCodes(){
	selectedValues = new Array();
	i = 0;
	$('#areasList input.checkBoxDummy').each(function(){
		selectedValues[i] = $(this).attr('value');
		i++;
	})
  
	$('#areaList input.checkBoxDummy').each(function(){
		if (selectedValues.inArray($(this).attr('value'))){
			$('#cpvType_'+ $(this).attr('value')).addClass("selected");
			obj = $(this).parent('div').parent('li').parent('ul');
			treeLevel = obj.attr('class').split('_')[1];
			for ( i=0;i<treeLevel;i++){
				obj.css('display','block');
				obj = obj.parent('li').parent('ul');
			}
		}
	});
}

function clearSearchForm(e){
	e.preventDefault();
	CPVCodeFunctions.removeAll();
	$('#searchByWordField').attr('value', '');
	$('#searchByWordFieldHidden').attr('value', '');
	$('#areasList').html('');
	$('#areaString').attr('value', '');
	$('#additionalCPVcode').attr('value', '');
	$('#cpvCodeArray').attr('value', '');
	$('#cpvCodeListContent').html('');
	$('#cpvCodeListInputs').html('');
	$('#dateStart').attr('value', '');
	$('#dateEnd').attr('value', '');
	$('#hankitaYks').attr('value', '');
	$('div.announceType').each(function(){
		if ( $(this).hasClass('selected') ){
			$(this).removeClass('selected');
			$(this).removeClass('disabled');
		}
	});
	$('input.announceType').each(function(){
		$(this).attr('checked', false);
	});
	
	
	if ($('.searchRadio:checked').attr("value") == 1) {
	$('#selArea').children('span').html('Valitse alue(et)');
	$('#areaString').attr('value', 'Valitse alue(et)');
	}
	else {
  $('#selArea').children('span').html('Valitse maa(t)');
	$('#areaString').attr('value', 'Valitse maa(t)');
  }
	xajax_clearSearch();
}
/*
function checkAreaListDimensions(level){
	var maxWidth = 0;
	var test = '';
	$('span#areaListContent .checkBoxRow').each(function(){
		if ( $(this).width() > maxWidth ){
			maxWidth = $(this).outerWidth() + 40;
		}
	})
	$('span#areaListContent').width(maxWidth + (40 * (level)));
}
*/
function searchNavigator(offset){
	$('#searchArea form').attr('action', '/index.php/hankintatieto/content/search'+ offset);
	$('#searchArea form').submit();
}

// *** ***************************** helpers
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
// Returns true if the passed value is found in the
// array. Returns false if it is not.
Array.prototype.inArray = function (value){
	var i;
	for (i=0; i < this.length; i++) {
		// Matches identical (===), not just similar (==).
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};