(function($){
   $.fn.jNice = function(options){
      var self = this;
      var safari = $.browser.safari;
      /* We need to check for safari to fix the input:text problem */
      $(document).mousedown(checkExternalClick);
      return this.each(function(){
                 $('input:text:visible, input:password', this).each(TextAdd);
                 if (safari){$('.jNiceInputWrapper').each(function(){$(this).addClass('jNiceSafari').find('input').css('width', $(this).width()+11);});}
                 $("select").selectbox();
                 $('textarea', this).each(TextareaAdd);
                 $(this).bind('reset',function(){var action = function(){ Reset(this); }; window.setTimeout(action, 10); });
                 $('.jNiceHidden').css({opacity:0});

      });
   };
   var Reset = function(form){
   		var sel;
        $('.jNiceSelectWrapper select', form).each(function(){
                 sel = (this.selectedIndex<0) ? 0 : this.selectedIndex;
                 $('ul', $(this).parent()).each(function(){$('a:eq('+ sel +')', this).click();});
        });
        $('a.jNiceCheckbox, a.jNiceRadio', form).removeClass('jNiceChecked');
        $('input:checkbox, input:radio', form).each(function(){
                 if(this.checked){$('a', $(this).parent()).addClass('jNiceChecked');}
        });
   };
   var TextAdd = function(){
        var baha = $(this).attr("id");
        var $input = $(this).addClass('jNiceInput').wrap('<div id="w_'+baha+'" class="jNiceInputWrapper "><div id="i_'+baha+'" class="jNiceInputInner "></div></div>');
        var $wrapper = $input.parents('.jNiceInputWrapper');
        $input.focus(function(){
        			$wrapper.addClass('jNiceInputWrapper_hover');
        })
        .blur(function(){
        			$wrapper.removeClass('jNiceInputWrapper_hover');
        });
   };
   var TextareaAdd = function(){
        var $input = $(this);
        if(screen.width < 1024)
                   $input.attr("cols", "67");
        else
                   $input.attr("cols", "93");
  		$input.focus(function(){
                   $input.addClass("textareaactive");
   		})
        .blur(function(){
                   $input.removeClass("textareaactive");
   		});
   };
   var SelectHide = function(){
   		$('.jNiceSelectWrapper ul:visible').hide();
   };
   var checkExternalClick = function(event) {
     	if ($(event.target).parents('.jNiceSelectWrapper').length === 0) {
            SelectHide();
        }
   };
   $(function(){
        $('form.jNice').jNice();
   });
})(jQuery);

jQuery.fn.extend({
	selectbox: function(options) {
    		return this.each(function() {
            			new jQuery.SelectBox(this, options);
            });
    }
});
jQuery.fn.extend({
	selectboxread: function(options) {
    		return this.each(function() {
            			new jQuery.SelectBoxREAD(this, options);
            });
    }
});
if (!window.console) {
  	var console = {
      		log: function(msg) {	 }

    }
}
jQuery.SelectBox = function(selectobj, options) {
    	var opt = options || {};
        opt.inputClass = opt.inputClass || "selectbox";
        opt.containerClass = opt.containerClass || "selectbox-wrapper";
        opt.hoverClass = opt.hoverClass || "current";
        opt.currentClass = opt.selectedClass || "selected";
        opt.debug = opt.debug || false;
        var elm_id = selectobj.id;
        var elm_title = selectobj.title;
        var active = 0;	var inFocus = false;
        var hasfocus = 0;
        var $select = $(selectobj);
        var elm_width = $select.css("width");
		var elm_height = $select.css("height");
        var $container = setupContainer(opt);
        var $input = setupInput(opt);
//        $select.before($input).before($container);
        $select.hide().before($input).before($container);
        if ($select.attr('onchange')) var $change = $select.attr('onchange');
        $container.hide();
        init();
        $input
        	.click(function(){
                   if (!inFocus) {
                   		  $container.toggle();
                   }
            })
            .focus(function(){
                   $input.css("background-position", "right center");
                   if ($container.not(':visible')) {
                   	       inFocus = true;
                           $container.show();
                   }
            })
            .keydown(function(event) {
            	   switch(event.keyCode) {
                    			case 38:
                                				event.preventDefault();
                                                moveSelect(-1);
                                                break;
                                case 40:
                                				event.preventDefault();
                                                moveSelect(1);
                                                break;
                                case 13:
                                				event.preventDefault();
                                                $('li.'+opt.hoverClass).trigger('click');
                                                break;
                                case 27:	
												hideMe();
												break;
					}	
			})
            .blur(function() {
                   $input.css("background-position", "right top");
                   if ($container.is(':visible') && hasfocus > 0 ) {
                   		  if(opt.debug) console.log('container visible and has focus')
                   } else {
                   		  if($.browser.msie){
                                     if(document.activeElement.getAttribute('id').indexOf('_container')==-1){
                                               hideMe();
                                     } else {
                                               $input.focus();
                                     }
                          } else {
                                  hideMe();
                          }
                   }
            });
            function hideMe() {
            		hasfocus = 0;
                    $container.hide();
           	}
            function init() {
            		$container.append(getSelectOptions($input.attr('id'))).hide();
                    var width = elm_width;
                    $container.width(width);
            }
            function setupContainer(options) {
                    var container = document.createElement("div");
                    $container = $(container);
                    $container.attr('id', elm_id+'_container');
                    $container.addClass(options.containerClass);
					if($.browser.msie){
 					   $container.css("height", "150px");
					   var elm_marginwidth = elm_width;
					   elm_marginwidth = elm_marginwidth.replace("px","");
					   elm_marginwidth = elm_marginwidth / 2;
					   if(elm_id == "sele_syst_domi") elm_marginwidth = elm_marginwidth * 2;
					   if(elm_id == "sele_syst_tempbusc" || elm_id == "sele_syst_tempbusc2" || 
					      elm_id == "sele_syst_tempoper" || elm_id == "sele_syst_tempbusc3") elm_marginwidth = 0;
					   $container.css("margin-left", "-"+elm_marginwidth);
					   if(elm_id == "sele_syst_domi") $container.css("height", "500px");
					}else{
 					   if(elm_height == "auto") $container.css("max-height", "250px");

					   $container.css("height", "auto");
					   if(elm_id == "sele_syst_domi") $container.css("max-height", "500px");
					}
                    return $container;
            }
            function setupInput(options) {
            		var input = document.createElement("input");
                    var $input = $(input);
                    $input.css("width", elm_width);
                    $input.attr("id", elm_id+"_input");
                    $input.attr("type", "text");
                    $input.addClass(options.inputClass);
                    $input.attr("autocomplete", "off");
                    $input.attr("maxlength", elm_title);
                    $input.attr("readonly", "readonly");
                    $input.attr("tabIndex", $select.attr("tabindex"));
                    return $input;
            }
            function moveSelect(step) {
                    var lis = $("li", $container);
                    if (!lis || lis.length == 0)
                         return false;
                         active += step;
                         if (active < 0) {
                             active = lis.size();
                         } else if (active > lis.size()) {
                             active = 0;
                         }
						 scroll(lis, active);
                         lis.removeClass(opt.hoverClass);
                         $(lis[active]).addClass(opt.hoverClass);


			 }
            function scroll(list, active) {
                    var el = $(list[active]).get(0);
                    var list = $container.get(0);
                    if (el.offsetTop + el.offsetHeight > list.scrollTop + list.clientHeight) {
                         list.scrollTop = el.offsetTop + el.offsetHeight - list.clientHeight;
                    } else if(el.offsetTop < list.scrollTop) {
                         list.scrollTop = el.offsetTop;
                    }
            }
            function setCurrent() {
                    var li = $("li."+opt.currentClass, $container).get(0);
                    var ar = (''+li.id).split('_input_');
                    var el = ar[ar.length-1];
                    $select.val(el);
                    var valor = $(li).html();
                    valor = valor.slice(0,elm_title);
                    $input.val(valor);
                    if ($change){
                        var attr = $change;
                        typeof attr == 'function' ? attr() : eval(attr);
                    }

                    return true;
            }
            function getCurrentSelected() {
            		return $select.val();
            }
            function getCurrentValue() {
            		return $input.val();
            }
            function getSelectOptions(parentid) {
            		var select_options = new Array();
                    var ul = document.createElement('ul');
                    $select.children('option').each(function() {
                                      var li = document.createElement('li');
                                      li.setAttribute('id', parentid + '_' + $(this).val());
                                      li.innerHTML = $(this).html();
                                      if ($(this).is(':selected')) {
                                                      var valor = $(this).html();
                                                      valor = valor.slice(0,elm_title);
                                                      $input.val(valor);
                                                      $(li).addClass(opt.currentClass);
                                      }
                                      ul.appendChild(li);
                                      $(li)
                                      			.mouseover(function(event) {
                                                  				hasfocus = 1;
                                                                if (opt.debug) console.log('over on : '+this.id);
                                                                jQuery(event.target, $container).addClass(opt.hoverClass);
                                                })
                                                .mouseout(function(event) {
                                                				hasfocus = -1;
                                                                if (opt.debug) console.log('out on : '+this.id);
                                                                jQuery(event.target, $container).removeClass(opt.hoverClass);
                                                })
                                                .click(function(event) {
                                                			    var fl = $('li.'+opt.hoverClass, $container).get(0);
                                                                if (opt.debug) console.log('click on :'+this.id);
                                                                $('li.'+opt.currentClass).removeClass(opt.currentClass);
                                                                $(this).addClass(opt.currentClass);
                                                                setCurrent();
                                                                $select.get(0).blur();
                                                                hideMe();
                                                 });
                    });
                    return ul;
             }
};
jQuery.SelectBoxREAD = function(selectobj, options) {
    	var opt = options || {};
        opt.inputClass = opt.inputClass || "selectbox selectboxdisabled";
        opt.containerClass = opt.containerClass || "selectbox-wrapper";
        opt.hoverClass = opt.hoverClass || "current";
        opt.currentClass = opt.selectedClass || "selected";
        opt.debug = opt.debug || false;
        var elm_id = selectobj.id;
        var elm_title = selectobj.title;
        var active = 0;	var inFocus = false;
        var hasfocus = 0;
        var $select = $(selectobj);
        var elm_width = $select.css("width");
        var $container = setupContainer(opt);
        var $input = setupInput(opt);
        $select.hide().before($input).before($container);
        $container.hide();
        init();
            function init() {
            		$container.append(getSelectOptions($input.attr('id'))).hide();
                    var width = elm_width;
                    $container.width(width);
            }
            function setupContainer(options) {
                    var container = document.createElement("div");
                    $container = $(container);
                    $container.attr('id', elm_id+'_container');
                    $container.addClass(options.containerClass);
                    return $container;
            }
            function setupInput(options) {
            		var input = document.createElement("input");
                    var $input = $(input);
                    $input.css("width", elm_width);
                    $input.attr("id", elm_id+"_input");
                    $input.attr("type", "text");
                    $input.addClass(options.inputClass);
                    $input.attr("autocomplete", "off");
                    $input.attr("maxlength", elm_title);
                    $input.attr("readonly", "readonly");
                    $input.attr("tabIndex", $select.attr("tabindex"));
                    return $input;
            }
            function getCurrentSelected() {
            		return $select.val();
            }
            function getCurrentValue() {
            		return $input.val();
            }
            function getSelectOptions(parentid) {
            		var select_options = new Array();
                    var ul = document.createElement('ul');
                    $select.children('option').each(function() {
                                      var li = document.createElement('li');
                                      li.setAttribute('id', parentid + '_' + $(this).val());
                                      li.innerHTML = $(this).html();
                                      if ($(this).is(':selected')) {
                                                      var valor = $(this).html();
                                                      valor = valor.slice(0,elm_title);
                                                      $input.val(valor);
                                                      $(li).addClass(opt.currentClass);
                                      }
                                      ul.appendChild(li);
                    });
                    return ul;
             }
};
function FormatN(num) {
  sep = ".";
  decpoint = ",";
  num = num.toString();
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";
  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return x;
}
function AbriPopuOcor(sUrl) {
    var iEsq = parseInt((screen.width-955)/2);
    var iTop = parseInt((screen.height-600)/2);
    var sWin = window.open(sUrl,'','width=955,height=600,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
    sWin.moveTo(iEsq,iTop);
}
function AbriPopuClie(sUrl) {
    var iEsq = parseInt((screen.width-1020)/2);
    var iTop = parseInt((screen.height-555)/2);
    var sWin = window.open(sUrl,'','width=1020,height=555,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
    sWin.moveTo(iEsq,iTop);
}
function AbriPopuRepr(sUrl) {
    var iEsq = parseInt((screen.width-1020)/2);
    var iTop = parseInt((screen.height-600)/2);
    var sWin = window.open(sUrl,'','width=1020,height=600,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
    sWin.moveTo(iEsq,iTop);
}
function AbriPopuForn(sUrl) {
    var iEsq = parseInt((screen.width-1020)/2);
    var iTop = parseInt((screen.height-440)/2);
    var sWin = window.open(sUrl,'','width=1020,height=440,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
    sWin.moveTo(iEsq,iTop);
}
function AbriPopuFaq(sUrl) {
    var iEsq = parseInt((screen.width-955)/2);
    var iTop = parseInt((screen.height-500)/2);
    var sWin = window.open(sUrl,'','width=955,height=500,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
    sWin.moveTo(iEsq,iTop);
}

function setread(elem, valu){
 if($('#'+elem).attr("type") == "text"){
    $('#'+elem).attr("readonly", true);
    $('#'+elem).val(valu);
    $('#w_'+elem).addClass('invalid_input1');
    $('#i_'+elem).addClass('invalid_input2');
    $('#'+elem).css('background-color', '#F2F2F3');
 }else{
    $('#'+elem).val(valu);
    $('#'+elem+'_input').remove();
    $('#'+elem+'_container').remove();
    $('#'+elem).selectboxread();
 }
}
function unsetread(elem){
 if($('#'+elem).attr("type") == "text"){
    $('#'+elem).removeAttr("readonly");
    $('#w_'+elem).removeClass('invalid_input1');
    $('#i_'+elem).removeClass('invalid_input2');
    $('#'+elem).css('background-color', '#FFFFFF');
 }else{
    $('#'+elem+'_input').remove();
    $('#'+elem+'_container').remove();
    $('#'+elem).selectbox();
 }
}
function valumask(elem, valu){
    elem = '#'+elem;
    var defi = $(elem+'_mask').val();
	$(elem).unmask();
    $(elem).val(valu);
    $(elem).mask(defi);
}
function reloadselect(sele_id, sele_value) {
                    sele_id = '#'+sele_id;
                    $(sele_id).val(sele_value);
                    $(sele_id+'_input').remove();
                    $(sele_id+'_container').remove();
                    $(sele_id).selectbox();
}
function zeroselect(sele_id) {
                    sele_id = '#'+sele_id;
                    $(sele_id).attr('selectedIndex', 0);
                    $(sele_id+'_input').remove();
                    $(sele_id+'_container').remove();
                    $(sele_id).selectbox();
}
function umselect(sele_id) {
                    sele_id = '#'+sele_id;
                    $(sele_id).attr('selectedIndex', 1);
                    $(sele_id+'_input').remove();
                    $(sele_id+'_container').remove();
                    $(sele_id).selectbox();
}
this.tooltip = function(){
            		var xOffset = 180;
                    var yOffset = -79;
                    $(".tooltrigger").hover(
						function(e){ $("#"+this.title)
                            			.css("top",(e.pageY-xOffset)+"px")
                                        .css("left",(e.pageX+yOffset)+"px")
                                        .show();
						},	
						function(){ $("#"+this.title).hide(); }
					);
                    $(".tooltrigger").mousemove(function(e){
                    		$("#"+this.title)
                            			.css("top",(e.pageY - xOffset) + "px")
                                        .css("left",(e.pageX + yOffset) + "px");
                    });
					$(".tooltrigger").mouseout(function(){ $("#"+this.title).hide();});
					$(".tooltrigger").mouseleave(function(){ $("#"+this.title).hide();});
};

function domitip(id) {
            		var xOffset = 115;
                    var yOffset = -79;
                    $("#tdclie"+id).hover(
						function(e){ $("#clie"+id)
                            			.css("top",(e.pageY-xOffset)+"px")
                                        .css("left",(e.pageX+yOffset)+"px")
                                        .show();
						},	
						function(){ $("#clie"+id).hide(); }
					);
                    $("#tdclie"+id).mousemove(function(e){
                    		$("#clie"+id)
                            			.css("top",(e.pageY - xOffset) + "px")
                                        .css("left",(e.pageX + yOffset) + "px")
										.show();;
                    });
					$("#tdclie"+id).mouseout(function(){ $("#clie"+id).hide();});
					$("#tdclie"+id).mouseleave(function(){ $("#clie"+id).hide();});

//					alert($("#clie"+id).css('display'));
};
function domitipremove(id) {
//alert(id);
					$(".domitrigger[title='clie"+id+"']").mouseout(function(){ $("#clie"+id).hide();});
					$(".domitrigger[title='clie"+id+"']").mouseleave(function(){ $("#clie"+id).hide();});
};

