var STATYSTYKA = new Array();

$(document).ready(function() {
    if($.browser.msie && $.browser.version < 8)
    {
        var zIndexNumber = 8000;
        $('div').each(function() {
            if(zIndexNumber > 0){
                $(this).css('zIndex', zIndexNumber);
                zIndexNumber -= 1;
            }
        });
    }
});

// super funkcja na wysokosc okna widzianego?
function windowHeight() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}

function windowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return {width: myWidth, height: myHeight};
}
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return {x: scrOfX, y: scrOfY };
}
function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

function findPos(obj) {
    pos = $(obj).position();
    //pos.left = parseInt(pos.left) - parseInt($(obj).width());
    return pos;
    //return [curleft,curtop];
}

function positionElements() {
	// (body - wrap) / 2 + wrap - right
	var fundRight = ($("body").width() - $("#wrap").width()) / 2 + 972 - 120;
//	$("#float_logo").css("left", (fundRight)+"px").fadeIn("fast");

	// pozycjonowanie position:fixed
	var left = parseInt( ($("body").width() - $("#wrap").width()) / 2 );
	$("#left").css('left',left);
//	$("#float_menu").css('left',left);

	var center = left + 122;
	$(".top").css('left',center);
	$("#menu_wrap").css('left',center);
	$("#partners").css('left',center);

	var right = left + $("#wrap").width() - 122;

	$("#right").css('left',right);
	$("#float_logo").css('left',right+2)
}


    function loadPage(container, url){
        var preloader_width = 150;
        var pos = findPos($(container));
        var preloader_top = pos.top + ($(container).height()) / 2 ;
        var preloader_left = pos.left + ($(container).width() - preloader_width) / 2 ;
        $(container).append("<div style='background-color: white; border: 1px solid gray; position: absolute; z-index: 1000; width: " + preloader_width + "px; left: " +preloader_left+ "px; top: " + preloader_top +  "px; text-align: center;padding: 10px 10px 10px 10px'>wczytywanie danych....<br/><img src='/images/preloader.gif'></div>");
        $.get(url, null,
                function(data){
                    setTimeout(function(){$(container).html(data);}, 100);
                }
            );
    }

this.initHeadTitle = function(){
	/*
     $(".head_title").each(function(){
        var wzor = /left/i;
        var next = /^\s*<img.*?src=/i;
        if(!wzor.test($(this).attr('id'))){
            if(!next.test($(this).html()))
                $(this).html('<img src="/images/icons/play.png" align="absmiddle" style="position:relative;left:-24px;bottom:2px;">'+$(this).html());
        } else {
            $(this).css('padding-left', 7);
        }
    });
    */
}

//  profile
    function selectChange(s){
        var text = $(s + ' :selected').text();
        if(text.length > 16){
            text = text.substr(0,16)+ '...'
        }
        $('#select'+$(s).attr('name')+$(s).attr('id')).text(text);
    }

    function companyChange(fid, prefix){
        sel_company = $("#company_"+fid).val();
        var group;
        group = $("#groups_"+fid).val();
        if(!group){
            group = '';
        }
        if(!prefix){
            prefix = '';
        }
        $.get(BASE + '/profile/products?x=c&c=' + $("#company_"+fid).val() + '&g=' + group + '&prefix=' + prefix, { },
                function(response) {
//                    $("#products_"+fid).html(0);
                    $("#products_"+fid).html(response);
                    $("#products_"+fid+" option[value='"+ sel_product +"']").attr("selected", "selected");
                    selectChange('#products_'+fid);
                });
         $.get(BASE + '/profile/groups?x=c&c=' + $("#company_"+fid).val() + '&prefix=' + prefix, { },
                function(response) {
//                    $("#groups_"+fid).html(0);
                    $("#groups_"+fid).html(response);
                    $("#groups_"+fid+" option[value='"+ sel_group +"']").attr("selected", "selected");
                    selectChange('#groups_'+fid);
                });
    }

    function productChange(fid, prefix){
        sel_product = $("#products_" + fid).val();
        $.get(BASE + '/profile/groups?x=p&c=' + $("#company_"+fid).val() + '&p=' + $("#products_"+fid).val() + '&prefix=' + prefix, { },
                function(response) {
//                    $("#groups_"+fid).html(0);
                    $("#groups_"+fid).html(response);
                    $("#groups_"+fid+" option[value='"+ sel_group +"']").attr("selected", "selected");
                    selectChange('#groups_'+fid);
                });
        $("#company_" + fid + " option[value='" + $("#products_" + fid + " option:selected").attr('class') + "']").attr("selected","selected");
        selectChange('#company_'+fid);
    }

    function groupChange(fid, prefix){
        sel_group = $("#groups_"+ fid).val();
        $.get(BASE + '/profile/products?x=g&c=' + $("#company_"+fid).val() + '&g=' + $("#groups_"+fid).val() + '&prefix=' + prefix, { },
                function(response) {
//                    $("#products_"+fid).html(0);
                    $("#products_"+fid).html(response);
                    $("#products_"+fid+" option[value='"+ sel_product +"']").attr("selected", "selected");
                    selectChange('#products_'+fid);
                });
        $.get(BASE + '/profile/companies?x=g&c=' + $("#company_"+fid).val() + '&g=' + $("#groups_"+fid).val() + '&prefix=' + prefix, { },
                function(response) {
//                    $("#company_"+fid).html(0);
                    $("#company_"+fid).html(response);
                    $("#company_"+fid+" option[value='"+ sel_company +"']").attr("selected", "selected");
                    selectChange('#company_'+fid);
                });
    }

var myInterval;

$(document).ready(function(){

	//positionElements();

	$(window).resize(function(){
//		positionElements();
	});


});

// dolne menu zawsze na dole strony/przy krawedzi okna
var menuYloc = null;
var menu = "#float_menu";

$(document).ready(function(){
	var menuOffset = $(menu).offset();

//	if (menuOffset.top < windowHeight()) {
//
//		$(menu).css("top", windowHeight());
//		menuYloc = windowHeight() - (15 + 60);
//		$(menu).css({
//			"top": menuYloc,
//			"position": "absolute"
//		});
//		$(window).scroll(function(){
//			offset = menuYloc + $(document).scrollTop() + "px";
//			$(menu).animate({
//				top: offset
//			}, {
//				duration: 500,
//				queue: false
//			});
//		});
//	}


	// plywajace FUND24
//	var name = "#float_logo";
//	var nameYloc = null;
//	$(name).css("top", windowHeight());
//	nameYloc = 182;//windowHeight() - (318 + 22 + 343);
//	$(name).css("top", nameYloc);
////    alert(nameYloc + ' ' + getDocHeight() + ' ' + windowHeight() + ' ' + getDocHeight()/windowHeight())
//	$(window).scroll(function () {
//		offset = nameYloc+parseInt($(document).scrollTop()*((getDocHeight() - nameYloc - 318 - 22)/(getDocHeight() - windowHeight())))+"px";
//		$(name).animate({top:offset},{duration:500,queue:false});
//	});


	/** #calendar .active borders **/
	$("#calendar .calendarTable table tr").each(function(){
		$(this).children('td.active:first').css('border-left','1px solid #888');
		$(this).children('td.active:last').css('border-right','1px solid #888');
	});

	var borders=0;
	for(ii=1; ii<=6;ii++) { //tr
		for(jj=1; jj<=7; jj++) { //td
			var obj = $('#calendar .calendarTable table tr:eq('+ ii +') td:eq('+ jj +')');
			if (obj.hasClass('active')) {
				obj.css('border-top', '1px solid #888');
				borders++;
				if(borders==7) break;
			}
		}
		if(borders==7) break;
	}
	var borders=0;
	for (ii = 6; ii >= 1; ii--) { //tr
		for (jj = 7; jj >= 1; jj--) { //td
			var obj = $('#calendar .calendarTable table tr:eq(' + ii + ') td:eq(' + jj + ')');
			if (obj.hasClass('active')) {
                obj.css('border-bottom', '1px solid #888');
				borders++;
				if (borders == 7) break;
			}
		}
		if (borders == 7) break;
	}


    // kalendarz
    $(".day_number").each(function(){
        $(this).bt({
            trigger: ['hoverIntent', 'click'],
            fill: '#eee',
            strokeStyle: '#eee',
            shadowColor: '#eee',
            spikeLength: 0,
            spikeGirth: 0,
            padding: 0,
            border: 1,
            height: 'auto',
            width: '350px',
            withCanvas: false,
            cornerRadius: 0,
            hoverIntentOpts: {
                interval: 500,
                timeout: 2000
            },
            closeWhenOthersOpen: true,
            contentSelector: $("#todayEvents")
        }).addClass("tooltip").hoverIntent({
            over: function() {
                //if($(this).attr("active") == "true"){
                    this.btOn();
                //}
            },
            out: function() {
                this.btOff()
            },
            interval: 0,
            timeout: 30
        });
    })

    //initHeadTitle();
//    $(".event").tooltip({showURL: false});
    $(".event").each(function(){
        $(this).bt({
            trigger: ['hoverIntent', 'click'],
//            trigger: ['none', 'click'],
            fill: '#eee',
            strokeStyle: '#eee',
            shadowColor: '#eee',
            spikeLength: 0,
            spikeGirth: 0,
            padding: 0,
            border: 1,
            height: 'auto',
            width: '350px',
            withCanvas: false,
            cornerRadius: 0,
            hoverIntentOpts: {
                interval: 500,
                timeout: 20
            },
            closeWhenOthersOpen: true,
            contentSelector: $("#events_"+$(this).text()),
            dontCloseWhenOver: true,
            overlap: -10
        }).hoverIntent({
            over: function() {
              this.btOn();
            },
            out: function() {
              this.btOff()
            },
            interval: 0,
            timeout: 150
        });
    })

    //   login
    $(".choose").click(function(){
        $(this).css('border-borrom-color', '#D2D3D5');
        if($(this).attr('id') == 'analizy'){
            $("#username_label").text('E-mail:');
            $(".analizy").show();
            if($.browser.msie){
                $("#signin_remember_input").show()
            }
            $("#serwis_info").text('Klienci indywidualni');
        } else {
            $("#username_label").text('Login:');
            $(".analizy").hide();
            if($.browser.msie){
                $("#signin_remember_input").hide()
            }
            $("#serwis_info").text('Klienci korporacyjni');
        }
        $("#loginTopBox .content, #loginTopBox1 .content").show();
        $(".choose").each(function(){
            $(this).removeClass('active')
        })
        $(this).addClass('active');
        $("#rodzajLogowania").val($(this).attr('id'));
    });
    $("#loginTop")
        .mouseenter(function(){
            is_over['.loginChoose'] = true;
            var content = $(".loginChoose");
            var pos = findPos($(this));
            content.css({
                position: 'absolute',
                left: pos.left - 13,
                top: (pos.top + $(this).height()) + 9,
                display: 'block',
                'z-index': 9999,
                width: 89,
                height: 'auto'
            });
        })
        .mouseleave(function(){
            is_over['.loginChoose'] = 0;
            is_over['#loginTopBox'] = 0;
            setTimeout("hideSubmenu('.loginChoose');", timeout);
            setTimeout("hideSubmenu('#loginTopBox');", timeout - 450);
        });

    $(".loginChoose").mouseleave(function(e){
        var c = $("#loginTopBox");
        if(c.length && e.pageX > c.offset().left && e.pageX < c.offset().left + c.width() || e.pageX < 0)
            	return;
        is_over['.loginChoose'] = 0;
        is_over['#loginTopBox'] = 0;
    });


    $("#loginTopBox")
        .mouseenter(function(){
            is_over["#loginTopBox"] = true;
        })
        .mouseover(function(){
            is_over["#loginTopBox"] = true;
        })
        .mouseleave(function(e){
            var c = "#loginTopBox";
            var pos = $(c).offset();

            if(e.pageX > pos.left && e.pageX < pos.left + $(c).width() || e.pageX < 0)
            	return;

            is_over[c] = false;

          //  setTimeout("hideSubmenu('.loginChoose');", timeout);
          //  setTimeout("hideSubmenu('#loginTopBox');", timeout - 50);
        })
        .mouseout(function(e){
            var c = "#loginTopBox";
            var pos = $(c).offset();

            if(e.pageX > pos.left && e.pageX < pos.left + $(c).width() || e.pageX < 0)
            	return;

            is_over[c] = false;

        });


    
 });

var PREEXPAND_LEFT_MARGIN = new Array();
var DOLITTLE = false;

function doexpand(advert_slot_id, width, height, ex_width, ex_height, expand_move)
{
	var top = 0;
	var left = 0;

	if(expand_move == "left")
	{
		left = width - ex_width;
                $("#advert_p_"+advert_slot_id).css({marginLeft: 0});
	}
	if(expand_move == "top")
	{
		top = height - ex_height;
	}
	
	document.getElementById("dslot_"+advert_slot_id).style.width = ex_width + 'px';
	document.getElementById("dslot_"+advert_slot_id).style.height = ex_height + 'px';
	document.getElementById("dslot_"+advert_slot_id).style.top = top + 'px';
	document.getElementById("dslot_"+advert_slot_id).style.left = left + 'px';
	document.getElementById("dslot_"+advert_slot_id).style.zIndex = 3000;
        $("#company_1").hide();
        $("#products_1").hide();
        $("#groups_1").hide();
        return void(0);
}

function dolittle(advert_slot_id, width, height)
{
	var top = 0;
	var left = 0;

        $("#advert_p_"+advert_slot_id).css({marginLeft: PREEXPAND_LEFT_MARGIN[advert_slot_id]});
	
	document.getElementById("dslot_"+advert_slot_id).style.width = width + 'px';
	document.getElementById("dslot_"+advert_slot_id).style.height = height + 'px';
	document.getElementById("dslot_"+advert_slot_id).style.top = top + 'px';
	document.getElementById("dslot_"+advert_slot_id).style.left = left + 'px';
	document.getElementById("dslot_"+advert_slot_id).style.zIndex = 2000;
        $("#company_1").show();
        $("#products_1").show();
        $("#groups_1").show();

}

(function(){
        var setRemoveCallback = function() {
            __flash__removeCallback = function(instance, name) {
                if (instance) {
                    instance[name] = null;
                }
            };
            window.setTimeout(setRemoveCallback, 10);
        };
        setRemoveCallback();
    })();

function isOver(e,c){
    var $c = $(c);
    var pos = $c.offset();
    return (e.pageX > pos.left && e.pageX < pos.left + $c.width() || e.pageX < 0) && 
        (e.pageY > pos.top && e.pageY < pos.top + $c.height() || e.pageY < 0);
}

/*  pretty forms  */

(function ($) {
  var originalVal = $.fn.val;
  $.fn.val = function(value) {
    if ($(this).data('pretty_select') && typeof value != 'undefined') {
        originalVal.call(this, value);
        this.change();
        return;
    }
    if(typeof value == 'undefined')
        return originalVal.call(this);
    return originalVal.call(this, value);
  };
  
  var originalHtml = $.fn.html;
  $.fn.html = function(html){
      var $this = $(this);
      if($(this).data('pretty_select') && typeof html == 'string'){
          html = html.replace(/option/ig,'div');
          html = html.replace(/value=/ig,'class="pretty_option" v=');          
          $(this).data('options').html(html);
          $(this).data('options').children('.pretty_option').each(function(){
              if($(this).attr('selected')){
                  $(this).addClass('pretty_option_selected');
                  originalVal.call($this, $(this).attr('v'));
                  $this.data('value').text($(this).text());
              }
          })
          $(this).data('init_options').call();
          var old = $(this).data('options').children('.pretty_option[v="'+$(this).val()+'"]');
          if(old.length == 0){
              var first = $(this).data('options').children('.pretty_option:first-child');          
              originalVal.call(this, first.attr('v'));
              $(this).data('value').text(first.text());
          }
          return;
      }
      if(typeof html == 'undefined')
        return originalHtml.call(this);
      return originalHtml.call(this, html);
  }
})(jQuery);
        
$(document).click(function(e){            
  $('.pretty_options').each(function(){
    var select_id = '#' + $(this).attr('id').replace('pretty_options','pretty_select');
    if(!isOver(e,this) && !isOver(e, select_id)){
      $(this).hide();
    }
  });
});
