/**
 * @author jacek
 * @email webmaster@jdstar.pl
 */

//    required: {type: "required", re: /[^.*]/, msg: "This field is required."},
//    alpha: {type: "alpha", re: /^[a-z ._-]+$/i, msg: "This field accepts alphabetic characters only."},
//    alphanum: {type: "alphanum", re: /^[a-z0-9 ._-]+$/i, msg: "This field accepts alphanumeric characters only."},
//    integer: {type: "integer", re: /^[-+]?\d+$/, msg: "Please enter a valid integer."},
//    real: {type: "real", re: /^[-+]?\d*\.?\d+$/, msg: "Please enter a valid number."},
//    date: {type: "date", re: /^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$/, msg: "Please enter a valid date (mm/dd/yyyy)."},
//      email: {type: "email", re:   /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i, msg: "Please enter a valid email."},
//    phone: {type: "phone", re: /^[\d\s ().-]+$/, msg: "Please enter a valid phone."},
//    url: {type: "url", re: /^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~])*$/i, msg: "Please enter a valid url."},

/**
 * Definicja wyrażeń regularnych dla typów zmiennych oraz komunikatów o błedach
 * (to do przyszłego wykorzystania)
 */
var regex = new Array();
var msg = new Array();
regex['string'] = /[^.*]/;
msg['string'] = 'Pole wymagane - typ: znakowy';
regex['email'] = /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i;
msg['email'] = 'Błędny adres email';
// regex['date'] =
// /^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$/;
// msg['date'] = 'Błędna data';
regex['integer'] = /^[-+]?\d+$/;
msg['integer'] = 'To nie jest liczba całkowita';
regex['real'] = /^[-+]?\d*\.?\d+$/;
msg['real'] = 'To nie jest liczba rzeczywista';
regex['date'] = /^(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/i;
msg['date'] = 'Niepoprawna forma zapisu daty [RRRR-MM-DD]';
regex['datetime'] = /^(19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/i;
msg['datetime'] = 'Niepoprawna forma zapisu czasu [RRRR-MM-DD hh:mm:ss]';
regex['ip'] = /^(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)\.(2[0-4]\d|25[0-5]|[01]?\d\d?)$/i;

msg['ip'] = 'Błędny adres IP';

function errorMessage(msg)
{
  return "<span class='error'>"+msg+"</span>";
} 
/**
 * Funkcja sprawdzająca poprawność pól input na podstawie wartości tagu valid w
 * tym polu dorobić warunki do rozbicie require i only validate - jeśli puste, i
 * kilka warunków w tagu valid
 */

function validateForm(){
  var notvalid = 0;
  var valids = new Array();
  var validattr = '', vatr;
  var valuefield = '';
  var pos = null;
  
  $.each($("form *[alt^='req_']"), function(i, val){
    validattr = $(this).attr('alt');
    vatr = validattr.split('_');
    // alert(vatr[1]);
    if (!regex[vatr[1]].test($(this).val())) {
      $(this).next('span.ui-state-error').show('slow');
      $(this).addClass('ui-state-error');
      notvalid = notvalid + 1;
    }
    else {
      $(this).removeClass('ui-state-error');
      $(this).next('span.ui-state-error').hide('slow');
    }
  });
  
  if (notvalid > 0) 
    return false;
  else 
    return true;
}

// odczytanie pozycji absolutnej względem okna
var getPosition = function (e){
  var top = e.pageY;// +opts.topOff;
  var left = e.pageX;// +opts.leftOff;
  alert('TOP:'+top+', LEFT:'+left);
};

// Konfiguracja pluginu 'date_input'

/*  jQuery.extend(DateInput.DEFAULT_OPTS, { month_names: ["Styczeń", "Luty",
  "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień",
  "Październik", "Listopad", "Grudzień"], short_month_names: ["Sty", "Lut",
  "Mar", "Kwi", "Maj", "Cze", "Lip", "Sie", "Wrz", "Paź", "Lis", "gru"],
  short_day_names: ["Nie", "Pon", "Wto", "Śro", "Czw", "Pią", "Sob"] });
  $.extend(DateInput.DEFAULT_OPTS, { stringToDate: function(string) { var
  matches; if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
  return new Date(matches[1], matches[2] - 1, matches[3]); } else { return
  null; }; }, dateToString: function(date) { var month = (date.getMonth() +
  1).toString(); var dom = date.getDate().toString(); if (month.length == 1)
  month = "0" + month; if (dom.length == 1) dom = "0" + dom; return
  date.getFullYear() + "-" + month + "-" + dom; } });
 */

/**
 * dopasowanie rozmiaru layoutu do rozmiaru okna przegladarki
 */  
function resizeLayout(){
  var winHeight = $(window).height();
  var winWidth = $(window).width();
  var headHeight = $('#head').height();
  var th = $('#tmon').height();
  var mh = $('#menuh').height();
  var left = $('#left').width();
   
  if (!jQuery.support.boxModel) {
    // alert(headHeight);
    // $('#monitor').height(th);
    if(th>0) th+=3;
    else th=2;
    $('#content').height(winHeight - headHeight - 40);	
    $('#main').height((winHeight - headHeight - (th) - 68));
    // $('#main').height(winHeight - (headHeight + mh + th + 10));
    // $('#main').height(winHeight - (headHeight + mh + th + 42));
    $('#page').width(winWidth-20);
    //$('#headcenter').width(winWidth-20-222);
    $('#center').width(winWidth-22-(left+1));
    $('#main').width('100%');
	  // $('#main').height((winHeight - headHeight - th - 80));
  }
  // kod dla mozillowatych
  else {
    // $('#monitor').height(th);
    if(th>0) th+=2;
    else th=1;
    $('#content').height(winHeight - headHeight - 26);
    $('#main').height((winHeight - headHeight - (th) - 48));
    $('#leftmenu').height(winHeight - headHeight - 96 - $('#leftowner').height());
    $('#page').css("width", (winWidth-5) + "px");
    //$('#headcenter').css("width", (winWidth-20-224) + "px");
    $('#tmon').css("width", (winWidth-8-left) + "px");
    $('#center').css("width", (winWidth-12-left) + "px");
  };
  if ($.browser.opera) {
    // alert(document.documentElement.clientHeight );
    $('#content').height(self.innerHeight - headHeight - 20);
    $('#main').height(self.innerHeight - headHeight - th - 12);
  }
}  
/**
 * dopasowanie rozmiaru layoutu do rozmiaru okna przegladarki - dla okna bez
 * menu
 */  
function resizeLayout2(){
  var winHeight = $(window).height();
  var winWidth = $(window).width();
  var headHeight = $('#head').height();
  // var th = $('#tmon').height();
  var mh = $('#menuh').height();
  var left = $('#left').width();
   
  if (!jQuery.support.boxModel) {
    // alert(headHeight);
    // $('#monitor').height(th);
    if(th>0) th+=3;
    else th=2;
    $('#content').height(winHeight - headHeight - 40);	
    $('#main').height((winHeight - headHeight  - 28));
    // $('#main').height(winHeight - (headHeight + mh + th + 10));
    // $('#main').height(winHeight - (headHeight + mh + th + 42));
    $('#page').width(winWidth-20);
    $('#headcenter').width(winWidth-20-222);
    $('#center').width(winWidth-22-(left+1));
    $('#main').width('100%');
	  // $('#main').height((winHeight - headHeight - th - 80));
  }
  // kod dla mozillowatych
  else {
    // $('#monitor').height(th);
    // if(th>0) th+=2;
    // else th=1;
    //$('#content').height(winHeight - headHeight - 26);
    $('#main').height((winHeight - headHeight  - 44));
    //$('#page').css("width", (winWidth-20) + "px");
    //$('#headcenter').css("width", (winWidth-20-224) + "px");
    // $('#tmon').css("width", (winWidth-20-139) + "px");
    //$('#center').css("width", (winWidth-20-139) + "px");
  };
  if ($.browser.opera) {
    // alert(document.documentElement.clientHeight );
    $('#content').height(self.innerHeight - headHeight - 20);
    $('#main').height(self.innerHeight - headHeight - th - 12);
  }
} 

//Tooltipy
/*(function($) {
jQuery.fn.easyTip = function(id)
{
    if(!document.getElementById('tool_tip'))
    {
       $("body").append('<div id="tool_tip_action">&nbsp;<'+'/div>');               
    }
    $("#" + id).hide();

    $(this).bind("mousemove", function(e)
    {
        $("#tool_tip_action").html('<div>'+$(this).attr('title')+'<'+'/div>').css({"left": e.pageX + 10, "top" : e.pageY + 10}).show();
    }).bind("mouseout", function()
    {
        $("#tool_tip_action").hide().css({"left": 0, "top" : 0});
    });
}
})(jQuery);*/




(function($) {
	jQuery.fn.easyTip = function(options){
	    var defaults = { // default configuration properties
	        xOffset: 10,        
	        yOffset: 25,
	        tooltipId: "easyTooltip",
	        clickRemove: false,
	        content: "",
	        useElement: ""
	    };

	    var options = $.extend(defaults, options);  
	    var content;
	    var url;

	    this.each(function() {                  
	        var title = $(this).attr("title");
	        var url = $(this).attr("tooltipURL");
	        $(this).hover(function(e){
	            if (url != "" && url != undefined) {
	                content = '<span class="loadingimage"></span> Loading...';
	                tooltip(content);
	                $('#'+options.tooltipId).load(url, {"id":$(this).attr("value")}); 
	            } else {
	                content = (options.content != "") ? options.content : title;
	                content = (options.useElement != "") ? $("#" + options.useElement).html() : content;
	                $(this).attr("title","");
	                if (content != "" && content != undefined){         
	                    tooltip(content);
	                }
	            }

	            function tooltip(content) {
	                $("body").append("<div class='ui-corner-all ui-widget ui-widget-content' id='"+ options.tooltipId +"'>"+ content +"</div>");      
	                $("#" + options.tooltipId)
	                    .css("position","absolute")
	                    .css("top",(e.pageY - options.yOffset) + "px")
	                    .css("left",(e.pageX + options.xOffset) + "px")                     
	                    .css("display","none")
	                    .fadeIn("fast")
	            }

	        },
	        function(){ 
	            $("#" + options.tooltipId).remove();
	            $(this).attr("title",title);
	        }); 
	        $(this).mousemove(function(e){
	            $("#" + options.tooltipId)
	                .css("top",(e.pageY - options.yOffset) + "px")
	                .css("left",(e.pageX + options.xOffset) + "px")                 
	        }); 
	        if(options.clickRemove){
	            $(this).mousedown(function(e){
	                $("#" + options.tooltipId).remove();
	                $(this).attr("title",title);
	            });             
	        }
	    });

	};
})(jQuery);

(function($){
    $.fn.extend({
         center: function (options) {
              var options =  $.extend({ // Default values
                   inside:window, // element, center into window
                   transition: 0, // millisecond, transition time
                   minX:0, // pixel, minimum left element value
                   minY:0, // pixel, minimum top element value
                   vertical:true, // booleen, center vertical
                   withScrolling:true, // booleen, take care of element inside
										// scrollTop when minX < 0 and window is
										// small or when window is big
                   horizontal:true // booleen, center horizontal
              }, options);
              return this.each(function() {
                   var props = {position:'absolute'};
                   if (options.vertical) {
                        var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                        if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                        top = (top > options.minY ? top : options.minY);
                        $.extend(props, {top: top+'px'});
                   }
                   if (options.horizontal) {
                         var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                         if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                         left = (left > options.minX ? left : options.minX);
                         $.extend(props, {left: left+'px'});
                   }
                   if (options.transition > 0) $(this).animate(props, options.transition);
                   else $(this).css(props);
                   return $(this);
              });
         }
    });
})(jQuery);


function toJsonString(o) {
    var UNDEFINED
    switch (typeof o) {
        case 'string': return '"' + encodeJS(o) + '"'
        case 'number': return String(o)
        case 'object':
            if(o) {
                var a = []
                if (o.constructor == Array) {
                    for (var i = 0; i <o.length; i++) {
                        var json = toJsonString(o[i])
                        if(json != UNDEFINED) a[a.length] = json
              }
                    return '[' + a.join(',') + ']'
                } else if (o.constructor == Date) {
                    return 'new Date(' + o.getTime() + ')'
                } else {
                    for (var p in o) {
                        var json = toJsonString(o[p])
                        if (json != UNDEFINED) a[a.length] = (/^[A-Za-z_]\w*$/.test(p) ? ('"' + p + '":') : ('"' + encodeJS(p) + '":')) + json
                    }
                    return '{' + a.join(',') + '}'
                }
            }
            return 'null'
        case 'boolean'  : return String(o)
        case 'function' : return
        case 'undefined': return 'null'
    }
}
function encodeJS(s) {
    return (!/[\x00-\x19\'\\]/.test(s)) ? s : s.replace(/([\\'])/g, '\\$1').replace(/\r/g, '\\r').replace(/\n/g, '\\n').replace(/\t/g, '\\t').replace(/[\x00-\x19]/g, '')
}
function serialize(x,s,n,c,z){c=x?x.constructor:c;n=n?'':'s=';s=s||'s'
 if(c==Function||c==RegExp)n+=x
 else{if(!x||typeof(x)!='object'||x==Math)return
n+(typeof(x)=='string'?'\"'+x.replace(/\"/g,'\\"').replace(/\'/g,"\\'")+'\"':x==Math?'Math':x)
 n+='new '+/function(.+)\(/.exec(c)[1]+'('+(typeof(z=x.valueOf())=='object'?'':'"'+z+'"')+')'}
 for(z in
x)n+=';'+(c=/\d+/.test(z)?s+'['+z+']':s+'.'+z)+'='+serialize(x[z],c,1);return n
}

function unserialize(x){eval(x);return s} 

