// JavaScript Document
$(document).ready(function(){
  $('div.searchRadio').click(setRadio);

  $('.checkBoxRow div.announceType, div.checkBoxDummy, span.checkBoxDummy').click(setBox);
  
  $('div.radioBoxDummy').click(setRadio);

  $('.selectOptionsSemi').parent().each(function(){
    $(this).css('width','99px');
  });

  $('.selectOptionsSmall').parent().each(function(){
    $(this).css('width','79px');
    
  });
  $('.selectOptions span').click(function(){
    dropDown(this);
  });
  $('.selectOptionsSemi span').click(function(){
    dropDown(this);
    
  });
    $('.selectOptionsSemiKoulutus span').click(function(){
    dropDown(this);
    
  });
  $('.selectOptionsSmall span').click(function(){
    dropDown(this);
//  $(this).css('background-image','none');
  }); 
  
  
    $('.selectVal li').click(function(){
        var value = $(this).attr('rel');
        $(this).parent().next('input').val(value);
    }); 
});


function bindSubSelectDrop(){
    $('#subCategories span').click(function(){
        dropDown(this);
    });
    $('#subCategories .selectVal li').click(function(){
        
        var value = $(this).attr('rel');
        $(this).parent().next('input').val(value);
    }); 
}

function bindThirdSelectDrop(){
    $('#thirdLevelCategories span').click(function(){
        dropDown(this);
    });
    $('#thirdLevelCategories .selectVal li').click(function(){
        var value = $(this).attr('rel');
        $(this).parent().next('input').val(value);
    }); 
}

function dropDown(val){
  var theList = $(val).parent().children('.optionList');
  var thisSel='';
  if($(theList).css('display')=='none'){
    $(theList).slideDown(150);
    $(theList).children('li').click(function(){
      thisSel=$(this).attr('class').split('_')[1];
      $(val).parent().parent().children('.optionList_sel').children('option').each(function(){
        if($(this).attr('value')==thisSel){
          $(this).attr('selected','selected');
        }else{
          $(this).removeAttr('selectd');
        }
      });
      $(val).html($(this).html());
      $(theList).slideUp(150);
    });
  }else{
    $(theList).slideUp(150);
  }

}
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 addCPVs(e){
  e.preventDefault();
  $('#areasList').html('');
  $('#areaList div.checkBoxDummy').each(function(){
    if($(this).hasClass('selected')){
    $('#areasList').append($(this).parent().children('input'));
    }
  });
  $('#areaGreyArea').css('display','none');
}

function saveSearch(e){
  e.preventDefault();
  var pos = $(this).offset();
  var conPos = $('#allContainer').offset();
  var watchContent = '<form name="searchSave" id="searchSave" action="post">'+
    '<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">6kk</li>'+
          '<li value="2" id="sel_2">12kk</li>'+
          '<li value="3" id="sel_3">24kk</li>'+
        '</ul>'+
      '</div>'+
      '<select name="selWatchspan" id="watchspanList_sel">'+
        '<option value="0">Valitse lÃ¤hetystiheys</option>'+
        '<option value="1">6kk</option>'+
        '<option value="2">12kk</option>'+
        '<option value="3">24kk</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>'+
    '<input type="submit" value="tallenna" name="submit" id="watchSubmit" />'+
    '<div class="clear"></div>'+
    '</div>'+
    '</form>'+
    '<div id="calendarView">'+
    '<div id="watchCalendar">'+
      '<a href="#" class="prev"></a><h4>Kuukausi, vvvv</h4><a href="#" class="next"></a>'+
      '<table cellpadding="0" cellspacing="0">'+
        '<tr class="head">'+
          '<td>MA</td><td>TI</td><td>KE</td><td>TO</td><td>PE</td><td>LA</td><td>SU</td>'+
        '</tr>'+
        '<tr>'+
          '<td>01</td><td>02</td><td>03</td><td>04</td><td>05</td><td>06</td><td>07</td>'+
        '</tr>'+
        '<tr>'+
          '<td>08</td><td>09</td><td>10</td><td>11</td><td>12</td><td>13</td><td>14</td>'+
        '</tr>'+
        '<tr>'+
          '<td>15</td><td>16</td><td>17</td><td>18</td><td>19</td><td>20</td><td>21</td>'+
        '</tr>'+
        '<tr>'+
          '<td>22</td><td>23</td><td>24</td><td>25</td><td>26</td><td>27</td><td>28</td>'+
        '</tr>'+
        '<tr>'+
          '<td>29</td><td>30</td><td>31</td><td></td><td></td><td></td><td></td>'+
        '</tr>'+
      '</table>'+
      '<a href="#" class="cancel">Peruuta</a>'+
      '<a href="#" class="save">Tallenna</a>'+
      '<div class="clear"></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');
  });
  $('#calendarView .cancel').click(function(e){
    e.preventDefault();
    $('#watchCalendar').css('visibility','hidden');
    $('#searchSave').css('visibility','visible');
  });
  $('#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');
    $('#watchName_d').attr('value',k);
    $('#watchCalendar').css('visibility','hidden');
    $('#searchSave').css('visibility','visible');
    //$('.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');
    }
  });
  $('.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('3kk');});
}


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(){
  var thisNum = $(this).attr('id').split('_')[1];
  if(!$(this).hasClass('selected')){
    $(this).attr('class',$(this).attr('class')+' selected');
    $('input.checkBoxDummy').each(function(){
      if($(this).attr('value')==thisNum){
        $(this).attr('checked', true);
      }
    });
  }else{
    $(this).removeClass(' selected');
    $('input.checkBoxDummy').each(function(){
      if($(this).attr('value')==thisNum){
        $(this).attr('checked', false);
      }
    });
  }
}

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(){
  var thisNum = $(this).attr('id').split('_')[1];
  thisNum=thisNum.split('-')[0];
  var thisSel = $(this).attr('id').split('-')[1];
  $('div.radioBoxDummy').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.radioBoxDummy').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);
      }
    });
  }else{
    return;
  }
}

function toolTip(){
  $(this).attr('id','calActive');
  var thisClass = $(this).attr('class');
  var pos = $(this).offset();
  var conPos = $('#allContainer').offset();
  $('.toolTip .toolContent .headBar h3').html('');
  $('.toolTip .toolContent .toolText').html('');
  if(thisClass=='datePicker'){
    $('.toolTip .toolContent .headBar h3').html('Valitse p&auml;iv&auml;');
    if(!$('.toolTip .toolContent .toolText').hasClass('calContainer')){
      $('.toolTip .toolContent .toolText').attr('class',$('.toolTip .toolContent .toolText').attr('class')+' calContainer');
    }
    $('.toolTip .toolContent .toolText').html('<div id="calendarView">'+$('#calContent').html()+'</div>');
  }else{
    $('.toolTip .toolContent .headBar h3').html($(this).attr('title'));
    $('.toolTip .toolContent .toolText').html($(this).html());
  }
  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');
      $('#toolTip_right').css('display','block');
    }else{/*toolTip_left*/
      $('#toolTip_left').css('top',(pos.top-38)+'px');
      $('#toolTip_left').css('left',(pos.left-222)+'px');
      $('#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');
    $('#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');
    $('#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');
    $('#toolTip_down').css('display','block');
  }
  $('.toolTip .headBar a.close').click(function(e){
    e.preventDefault();
    $(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');
  }
}
function selTimespan(){
  $('#timespanList').slideDown(150);
  $('body').click(function(){$('#timespanList').css('display','none');});
}
function setTimespan(){
  $('#timespanList_sel option').removeAttr('selected');
  var sel = $(this).attr('value');
  $('#timespanList_sel option[value="'+sel+'"]').attr('selected','selected');
  $('#timespanList').css('display','none');
  $('#selTimespan span').html($(this).html());
  $('#selTimespan span').click(function(){$(this).html('3kk');});
}
/*
 *
 * jqTransform
 * by mathieu vilaplana mvilaplana@dfc-e.com
 * Designer ghyslain armand garmand@dfc-e.com
 *
 *
 * Version 1.0 25.09.08
 * Version 1.1 06.08.09
 * Add event click on Checkbox and Radio
 * Auto calculate the size of a select element
 * Can now, disabled the elements
 * Correct bug in ff if click on select (overflow=hidden)
 * No need any more preloading !!
 * 
 ******************************************** */
 
(function($){
	var defaultOptions = {preloadImg:true};
	var jqTransformImgPreloaded = false;

	var jqTransformPreloadHoverFocusImg = function(strImgUrl) {
		//guillemets to remove for ie
		strImgUrl = strImgUrl.replace(/^url\((.*)\)/,'$1').replace(/^\"(.*)\"$/,'$1');
		var imgHover = new Image();
		imgHover.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-hover.$1');
		var imgFocus = new Image();
		imgFocus.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-focus.$1');				
	};

	
	/***************************
	  Labels
	***************************/
	var jqTransformGetLabel = function(objfield){
		var selfForm = $(objfield.get(0).form);
		var oLabel = objfield.next();
		if(!oLabel.is('label')) {
			oLabel = objfield.prev();
			if(oLabel.is('label')){
				var inputname = objfield.attr('id');
				if(inputname){
					oLabel = selfForm.find('label[for="'+inputname+'"]');
				} 
			}
		}
		if(oLabel.is('label')){return oLabel.css('cursor','pointer');}
		return false;
	};
	
	/* Hide all open selects */
	var jqTransformHideSelect = function(oTarget){
		var ulVisible = $('.jqTransformSelectWrapper ul:visible');
		ulVisible.each(function(){
			var oSelect = $(this).parents(".jqTransformSelectWrapper:first").find("select").get(0);
			//do not hide if click on the label object associated to the select
			if( !(oTarget && oSelect.oLabel && oSelect.oLabel.get(0) == oTarget.get(0)) ){$(this).hide();}
		});
	};
	/* Check for an external click */
	var jqTransformCheckExternalClick = function(event) {
		if ($(event.target).parents('.jqTransformSelectWrapper').length === 0) { jqTransformHideSelect($(event.target)); }
	};

	/* Apply document listener */
	var jqTransformAddDocumentListener = function (){
		$(document).mousedown(jqTransformCheckExternalClick);
	};	
			
	/* Add a new handler for the reset action */
	var jqTransformReset = function(f){
		var sel;
		$('.jqTransformSelectWrapper select', f).each(function(){sel = (this.selectedIndex<0) ? 0 : this.selectedIndex; $('ul', $(this).parent()).each(function(){$('a:eq('+ sel +')', this).click();});});
		$('a.jqTransformCheckbox, a.jqTransformRadio', f).removeClass('jqTransformChecked');
		$('input:checkbox, input:radio', f).each(function(){if(this.checked){$('a', $(this).parent()).addClass('jqTransformChecked');}});
	};

	/***************************
	  Buttons
	 ***************************/
	$.fn.jqTransInputButton = function(){
		return this.each(function(){
			var newBtn = $('<button id="'+ this.id +'" name="'+ this.name +'" type="'+ this.type +'" class="'+ this.className +' jqTransformButton"><span><span>'+ $(this).attr('value') +'</span></span>')
				.hover(function(){newBtn.addClass('jqTransformButton_hover');},function(){newBtn.removeClass('jqTransformButton_hover')})
				.mousedown(function(){newBtn.addClass('jqTransformButton_click')})
				.mouseup(function(){newBtn.removeClass('jqTransformButton_click')})
			;
			$(this).replaceWith(newBtn);
		});
	};
	
	/***************************
	  Text Fields 
	 ***************************/
	$.fn.jqTransInputText = function(){
		return this.each(function(){
			var $input = $(this);
	
			if($input.hasClass('jqtranformdone') || !$input.is('input')) {return;}
			$input.addClass('jqtranformdone');
	
			var oLabel = jqTransformGetLabel($(this));
			oLabel && oLabel.bind('click',function(){$input.focus();});
	
			var inputSize=$input.width();
			if($input.attr('size')){
				inputSize = $input.attr('size')*10;
				$input.css('width',inputSize);
			}
			
			$input.addClass("jqTransformInput").wrap('<div class="jqTransformInputWrapper"><div class="jqTransformInputInner"><div></div></div></div>');
			var $wrapper = $input.parent().parent().parent();
			$wrapper.css("width", inputSize+10);
			$input
				.focus(function(){$wrapper.addClass("jqTransformInputWrapper_focus");})
				.blur(function(){$wrapper.removeClass("jqTransformInputWrapper_focus");})
				.hover(function(){$wrapper.addClass("jqTransformInputWrapper_hover");},function(){$wrapper.removeClass("jqTransformInputWrapper_hover");})
			;
	
			/* If this is safari we need to add an extra class */
			$.browser.safari && $wrapper.addClass('jqTransformSafari');
			$.browser.safari && $input.css('width',$wrapper.width()+16);
			this.wrapper = $wrapper;
			
		});
	};
	
	/***************************
	  Check Boxes 
	 ***************************/	
	$.fn.jqTransCheckBox = function(){
		return this.each(function(){
			if($(this).hasClass('jqTransformHidden')) {return;}

			var $input = $(this);
			var inputSelf = this;

			//set the click on the label
			var oLabel=jqTransformGetLabel($input);
			oLabel && oLabel.click(function(){aLink.trigger('click');});
			
			var aLink = $('<a href="#" class="jqTransformCheckbox"></a>');
			//wrap and add the link
			$input.addClass('jqTransformHidden').wrap('<span class="jqTransformCheckboxWrapper"></span>').parent().prepend(aLink);
			//on change, change the class of the link
			$input.change(function(){
				this.checked && aLink.addClass('jqTransformChecked') || aLink.removeClass('jqTransformChecked');
				return true;
			});
			// Click Handler, trigger the click and change event on the input
			aLink.click(function(){
				//do nothing if the original input is disabled
				if($input.attr('disabled')){return false;}
				//trigger the envents on the input object
				$input.trigger('click').trigger("change");	
				return false;
			});

			// set the default state
			this.checked && aLink.addClass('jqTransformChecked');		
		});
	};
	/***************************
	  Radio Buttons 
	 ***************************/	
	$.fn.jqTransRadio = function(){
		return this.each(function(){
			if($(this).hasClass('jqTransformHidden')) {return;}

			var $input = $(this);
			var inputSelf = this;
				
			oLabel = jqTransformGetLabel($input);
			oLabel && oLabel.click(function(){aLink.trigger('click');});
	
			var aLink = $('<a href="#" class="jqTransformRadio" rel="'+ this.name +'"></a>');
			$input.addClass('jqTransformHidden').wrap('<span class="jqTransformRadioWrapper"></span>').parent().prepend(aLink);
			
			$input.change(function(){
				inputSelf.checked && aLink.addClass('jqTransformChecked') || aLink.removeClass('jqTransformChecked');
				return true;
			});
			// Click Handler
			aLink.click(function(){
				if($input.attr('disabled')){return false;}
				$input.trigger('click').trigger('change');
	
				// uncheck all others of same name input radio elements
				$('input[name="'+$input.attr('name')+'"]',inputSelf.form).not($input).each(function(){
					$(this).attr('type')=='radio' && $(this).trigger('change');
				});
	
				return false;					
			});
			// set the default state
			inputSelf.checked && aLink.addClass('jqTransformChecked');
		});
	};
	
	/***************************
	  TextArea 
	 ***************************/	
	$.fn.jqTransTextarea = function(){
		return this.each(function(){
			var textarea = $(this);
	
			if(textarea.hasClass('jqtransformdone')) {return;}
			textarea.addClass('jqtransformdone');
	
			oLabel = jqTransformGetLabel(textarea);
			oLabel && oLabel.click(function(){textarea.focus();});
			
			var strTable = '<table cellspacing="0" cellpadding="0" border="0" class="jqTransformTextarea">';
			strTable +='<tr><td id="jqTransformTextarea-tl"></td><td id="jqTransformTextarea-tm"></td><td id="jqTransformTextarea-tr"></td></tr>';
			strTable +='<tr><td id="jqTransformTextarea-ml">&nbsp;</td><td id="jqTransformTextarea-mm"><div></div></td><td id="jqTransformTextarea-mr">&nbsp;</td></tr>';	
			strTable +='<tr><td id="jqTransformTextarea-bl"></td><td id="jqTransformTextarea-bm"></td><td id="jqTransformTextarea-br"></td></tr>';
			strTable +='</table>';					
			var oTable = $(strTable)
					.insertAfter(textarea)
					.hover(function(){
						!oTable.hasClass('jqTransformTextarea-focus') && oTable.addClass('jqTransformTextarea-hover');
					},function(){
						oTable.removeClass('jqTransformTextarea-hover');					
					})
				;
				
			textarea
				.focus(function(){oTable.removeClass('jqTransformTextarea-hover').addClass('jqTransformTextarea-focus');})
				.blur(function(){oTable.removeClass('jqTransformTextarea-focus');})
				.appendTo($('#jqTransformTextarea-mm div',oTable))
			;
			this.oTable = oTable;
			if($.browser.safari){
				$('#jqTransformTextarea-mm',oTable)
					.addClass('jqTransformSafariTextarea')
					.find('div')
						.css('height',textarea.height())
						.css('width',textarea.width())
				;
			}
		});
	};
	
	/***************************
	  Select 
	 ***************************/	
	$.fn.jqTransSelect = function(){
		return this.each(function(index){
			var $select = $(this);

			if($select.hasClass('jqTransformHidden')) {return;}
			if($select.attr('multiple')) {return;}

			var oLabel  =  jqTransformGetLabel($select);
			/* First thing we do is Wrap it */
			var $wrapper = $select
				.addClass('jqTransformHidden')
				.wrap('<div class="jqTransformSelectWrapper"></div>')
				.parent()
				.css({zIndex: 10-index})
			;
			
			/* Now add the html for the select */
			$wrapper.prepend('<div><span></span><a href="#" class="jqTransformSelectOpen"></a></div><ul></ul>');
			var $ul = $('ul', $wrapper).css('width',$select.width()).hide();
			/* Now we add the options */
			$('option', this).each(function(i){
				var oLi = $('<li><a href="#" index="'+ i +'">'+ $(this).html() +'</a></li>');
				$ul.append(oLi);
			});
			
			/* Add click handler to the a */
			$ul.find('a').click(function(){
					$('a.selected', $wrapper).removeClass('selected');
					$(this).addClass('selected');	
					/* Fire the onchange event */
					if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
					$select[0].selectedIndex = $(this).attr('index');
					$('span:eq(0)', $wrapper).html($(this).html());
					$ul.hide();
					return false;
			});
			/* Set the default */
			$('a:eq('+ this.selectedIndex +')', $ul).click();
			$('span:first', $wrapper).click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
			oLabel && oLabel.click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
			this.oLabel = oLabel;
			
			/* Apply the click handler to the Open */
			var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper)
				.click(function(){
					//Check if box is already open to still allow toggle, but close all other selects
					if( $ul.css('display') == 'none' ) {jqTransformHideSelect();} 
					if($select.attr('disabled')){return false;}

					$ul.slideToggle('fast', function(){					
						var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
						$ul.animate({scrollTop: offSet});
					});
					return false;
				})
			;

			// Set the new width
			var iSelectWidth = $select.outerWidth();
			var oSpan = $('span:first',$wrapper);
			var newWidth = (iSelectWidth > oSpan.innerWidth())?iSelectWidth+oLinkOpen.outerWidth():$wrapper.width();
			$wrapper.css('width',newWidth);
			$ul.css('width',newWidth-2);
			oSpan.css({width:iSelectWidth});
		
			// Calculate the height if necessary, less elements that the default height
			//show the ul to calculate the block, if ul is not displayed li height value is 0
			$ul.css({display:'block',visibility:'hidden'});
			var iSelectHeight = ($('li',$ul).length)*($('li:first',$ul).height());//+1 else bug ff
			(iSelectHeight < $ul.height()) && $ul.css({height:iSelectHeight,'overflow':'hidden'});//hidden else bug with ff
			$ul.css({display:'none',visibility:'visible'});
			
		});
	};
	$.fn.jqTransform = function(options){
		var opt = $.extend({},defaultOptions,options);
		
		/* each form */
		 return this.each(function(){
			var selfForm = $(this);
			if(selfForm.hasClass('jqtransformdone')) {return;}
			selfForm.addClass('jqtransformdone');
			
			$('input:submit, input:reset, input[type="button"]', this).jqTransInputButton();			
			$('input:text, input:password', this).jqTransInputText();			
			$('input:checkbox', this).jqTransCheckBox();
			$('input:radio', this).jqTransRadio();
			$('textarea', this).jqTransTextarea();
			
			if( $('select', this).jqTransSelect().length > 0 ){jqTransformAddDocumentListener();}
			selfForm.bind('reset',function(){var action = function(){jqTransformReset(this);}; window.setTimeout(action, 10);});
			
			//preloading dont needed anymore since normal, focus and hover image are the same one
			/*if(opt.preloadImg && !jqTransformImgPreloaded){
				jqTransformImgPreloaded = true;
				var oInputText = $('input:text:first', selfForm);
				if(oInputText.length > 0){
					//pour ie on eleve les ""
					var strWrapperImgUrl = oInputText.get(0).wrapper.css('background-image');
					jqTransformPreloadHoverFocusImg(strWrapperImgUrl);					
					var strInnerImgUrl = $('div.jqTransformInputInner',$(oInputText.get(0).wrapper)).css('background-image');
					jqTransformPreloadHoverFocusImg(strInnerImgUrl);
				}
				
				var oTextarea = $('textarea',selfForm);
				if(oTextarea.length > 0){
					var oTable = oTextarea.get(0).oTable;
					$('td',oTable).each(function(){
						var strImgBack = $(this).css('background-image');
						jqTransformPreloadHoverFocusImg(strImgBack);
					});
				}
			}*/
			
			
		}); /* End Form each */
				
	};/* End the Plugin */

})(jQuery);
				   