var Config = {
		errorSchema:'<ul class="error_list"></ul>',
		dateSeparator:'-',
		dateFormat: 'dd-mm-yy',
		historyParamName: "h"
};

jQuery.fn.extend({
	  getContext: function() {
		if(this.attr("class")) { 
			var classes=this.attr("class").split(" ");
			var updaters=[];
			$.each(classes, function(i, cl){
				if(/Updater/.test(cl)) {
					var el="#"+cl.replace("Updater", "").replace("js_", "");
					if($(el).size()>0) updaters.push(el);
				}
			});
			return updaters;
		} else return [];
	  }
	});

jQuery.fn.extend({
    fire: function(evttype){
        el = this.get(0);
        if (document.createEvent) {
            var evt = document.createEvent('HTMLEvents');
            evt.initEvent(evttype, false, false);
            el.dispatchEvent(evt);
        } else if (document.createEventObject) {
            $(this).trigger("change");
        }
        return this;
    }
});

$(document).ready(function(){
	   
    $("form :checkbox").click(function(){
        if($.browser.msie){
            $(this).fire("change");
        }
    });
   
}); 

(function($){
	$.getCSS = function( url, media ){
	      $(document.createElement('link') ).attr({
	          href: url,
	          media: media || 'screen',
	         type: 'text/css',
	          rel: 'stylesheet'
	      }).appendTo('head');
	   }
	})(jQuery);

$.ajaxSetup({
	context: $("head, #msg"),
	beforeSend: function() {
//		log("preloader");
	}
});


if(jQuery.validator) {
jQuery.validator.addMethod("greaterThanDate", function(value, element, params) {
		var date=$.datepicker.parseDate('dd-mm-yy', value);
        if (!/Invalid|NaN/.test(date)) {
        	var date2=$.datepicker.parseDate('dd-mm-yy', $(params).val());
            return date >= date2;
        }
        return isNaN(value) && isNaN($(params).val()) || (parseFloat(value) > parseFloat($(params).val())); 
    },'Podany zakres dat jest nieprawidłowy');

}

$(document).ready(function(){
	$(".helpbox").find("img").click(function(){
		$(".helpinfo").hide();
		$(this).nextAll(".helpinfo").show();
	});
	$(".helpbox").parents("fieldset").find("input,select").focus(function(){
		if($(this).parents("fieldset").find(".error_list li").size()==0) {
			$(this).parents("fieldset").find(".helpbox").find("img").trigger("click");
		}
	})
	bindEvents();
	$(".js_placeholder").trigger("blur"); //musi być po bindEvents i nie może być w bindEvents
	$(".js_only").show();
	$("head").ajaxSuccess(function(ev, response){
		if(isJSON(response.responseText))  {
			eval("response="+response.responseText);
			if(response.redirect) {
				return document.location.href=response.redirect;
			}
		}
		bindEvents();
		$("#loader").hide();
	}).ajaxStart(function(ev){
//		log(ev);
		$("#loader").show();
	});
	
	$("#msg").ajaxComplete(function(ev, response){
//		log("msg");
		var response=response.responseText;
		if(isJSON(response)) {
			eval("var response="+response);
			if(response.msg) {
				$(this).html(response.msg).show();
			}
		}
	}).ajaxStart(function(){
		$(this).html("").hide();
	});
	
	
	if($.datepicker) {
		jQuery(function(a){a.datepicker.regional.pl={closeText:"Zamknij",prevText:"&#x3c;Poprzedni",nextText:"Następny&#x3e;",currentText:"Dziś",monthNames:["Styczeń","Luty","Marzec","Kwiecień","Maj","Czerwiec","Lipiec","Sierpień","Wrzesień","Październik","Listopad","Grudzień"],monthNamesShort:["Sty","Lu","Mar","Kw","Maj","Cze","Lip","Sie","Wrz","Pa","Lis","Gru"],dayNames:["Niedziela","Poniedzialek","Wtorek","Środa","Czwartek","Piątek","Sobota"],dayNamesShort:["Nie","Pn","Wt","Śr","Czw","Pt","So"],dayNamesMin:["N","Pn","Wt","Śr","Cz","Pt","So"],weekHeader:"Tydz",dateFormat:"yy-mm-dd",firstDay:1,isRTL:false,showMonthAfterYear:false,yearSuffix:""};a.datepicker.setDefaults(a.datepicker.regional.pl)});
		$.datepicker.setDefaults($.datepicker.regional['pl']);
		$.datepicker.setDefaults({ dateFormat: Config.dateFormat });
	}
	
	$("a.js_ajaxLoad").live("click", function(){
		var rel=$(this).attr('rel');
			var container=rel ? $("#"+rel) : $();
				$.ajax({
					type: $(this).hasClass("js_ajaxPost") ? "POST" : "GET",
					url: $(this).attr("href"), 
					context: $.merge($(this), $("head, #msg"+($(this).getContext().length>0 ? (" ,"+$(this).getContext().join(", ")) : ""))),
					cache: $(this).hasClass("js_cache"),
					success: function(response) {
						if(!isJSON(response))  {
							if(container.size()>0) { 
								container.html(response);
								container.show();
								if($.historyLoad && $(this).filter(Config.historyParamName).attr('id')) {
									$.historyLoad($.query.SET(Config.historyParamName, $(this).filter(Config.historyParamName).attr('id').replace("_", "")).toString());
								}
							}
						};
					}				
				});
		
				

		return false;
	});
	
// $(".js_ajaxForm").unbind("submit").submit(function(ev){
	$(".js_ajaxForm").live("submit", function(ev) {
		$(this).trigger("beforeSubmit");
		if($(this).valid()) {
			$.ajax({
				type: $(this).attr("method"),
				url: $(this).attr("action"), 
				data: $(this).serialize(), 
				context: $.merge($(this), $("head, #msg"+($(this).getContext().length>0 ? (" ,"+$(this).getContext().join(", ")) : ""))),
				success: function(response) {
					var formContext=$(this).filter("form");
					if(isJSON(response)) {
						eval("response="+response);
						formContext.find("input").next("ul").hide();
						formContext.find(".error_global").hide();
						formContext.find(".msg").hide();
						if(response.errors.length>0) {
							$.each(response.errors, function(key, error){
								var field=$("input[name='"+error.field+"'], select[name='"+error.field+"']");
								if(field.size()>0) {
									if(field.nextAll("ul").size()==0) {
										$(Config.errorSchema).appendTo(field.parent("fieldset"));
									}
									field.nextAll("ul").html($("<li>"+error.message+"</li>")).show();
								} else {
									formContext.find(".error_global").html(error.message).show();
								}
								
							})
						}
						if(response.msg) {
							if(formContext.find(".msg").size()>0) {
								formContext.find(".msg").html(response.msg).show();
							} else if($(this).find(".msg").size()>0) {
								$(this).find(".msg").first().html(response.msg).show();
							}
						}
						if(response.status=='ok') {
							$(this).filter(".js_hideAfterSubmit").hide();
						}
						return false;
					} else if($(this).attr("rel") && $("#"+$(this).attr("rel")).size()>0) {
						$("#"+$(this).attr("rel")).html(response);
					}
				}
		});
	} 
		return false;
	});
	
	
	$("a.js_tabLink").click(function(){
		if($(this).attr("rel") && $('#'+$(this).attr("rel")).size()>0) {
			var tab=$('#'+$(this).attr("rel"));
			tab.nextAll(".js_tab").hide();
			tab.prevAll(".js_tab").hide();
			tab.show();
			$(this).addClass('active').siblings("a.js_tabLink").removeClass("active");
			return false;
		}
	});
	
	$("a.js_history").click(function(){
		if(jQuery.browser.msie) {
//			log($(this).attr("href").substr(0,1));
			if($(this).attr("href")) {
				var link=$.query.load($(this).attr("href"));
				var historyLink=link.GET(Config.historyParamName);
				if(historyLink && $.query.GET(Config.historyParamName)!=historyLink) {
					$.historyLoad(link.toString().toString());
					return false;
				}
			}
		}
		if($(this).attr("id")) { 
			var historyLink=$(this).attr('id').replace("_", "");
			if($.query.GET(Config.historyParamName)!=historyLink) {
				$.historyLoad($.query.SET(Config.historyParamName, historyLink).toString());
				return false;
			}
		}
		return true;
	});
	
	$("select[id*='Updater']").change(function(){
		var elName=$(this).attr("id").replace('Updater', '');
		var el=$("#"+elName+$(this).val());
		if(el.size()>0) {
			$("[id*='"+elName+"']:not([id*='Updater'])").hide();
			el.show();
		}
	});
	
	if($.historyInit) {
		$.historyInit(function(){
			if($.query) {
				$.query = $.query.load(location.hash);
				if($.query.get(Config.historyParamName)) { 
					if($("#"+$.query.get(Config.historyParamName)).size()>0) {
//						log($("#"+$.query.get(Config.historyParamName)).data());
						$("#"+$.query.get(Config.historyParamName)).trigger("click");
					}
				}
				if(typeof($.query.keys)=='object') {
					$.each($.query.keys, function(key, value){
						var el=$("#"+key);
						if(key!=Config.historyParamName && el.size()>0) {
							if(el.is("a")) { 
								el.trigger("click"); 
							}
							else if(el.is("input:not([type='checkbox'])") || el.is("select")) {
								el.val(value).trigger("change");
							}
							else if(el.is("input[type='checkbox']")) el.attr("checked", value);
						}
					})
				}
			}
	    });
	};
	
	
});

function bindEvents() {
//	log("bindEvents");
	if($.datepicker) {
		$(".js_datepicker_basic").datepicker({ dateFormat: 'dd-mm-yy' });
		$(".js_datepicker").show().datepicker().live("change", function() {
			var date=this.value.split(Config.dateSeparator);
			var name=this.name.replace("datepicker_", "");
			if(date.length==3) {
	//			Logger.info(date[0]+" "+parseInt(date[0], 10));
				$("input[name='"+name+"[day]']").val(parseInt(date[0], 10));
				$("input[name='"+name+"[month]']").val(parseInt(date[1], 10));
				$("input[name='"+name+"[year]']").val(parseInt(date[2], 10));
				
			} else {
				$("input[name='"+name+"[day]']").val("");
				$("input[name='"+name+"[month]']").val("");
				$("input[name='"+name+"[year]']").val("");
			};
		}).val(function(index, value){
			var name=this.name.replace("datepicker_", "");
			var date=$("input[name*='"+name+"[']");
			if(date.size()==3) {
				var dateArr=[];
				date.each(function(index){
					if(this.value) dateArr.push(this.value<10 ? '0'+this.value : this.value);
				});
			return dateArr.join(Config.dateSeparator);	
			} else return "";
		});
	}
	
	$(".js_placeholder").focus( function(e) {
//		log("focus");
		if( $(this).val()==$(this).attr("title")) {
			$(this).removeClass('placeholder');
			$(this).attr('value', '');
		}
	}).blur( function(e) {
//		log("blur");
		if( $.trim($(this).val())=='' ) {
			$(this).addClass('placeholder');
			$(this).attr('value', $(this).attr("title"));
		}
	});
	
	

	
	if(jQuery.mask) {
		$('input:text').setMask();
	}
	
	
	
}


function isJSON(str) {
    if (/^\s*$/.test(str)) return false;
    str = str.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
};


function log(str) {
	if(typeof(console)!="undefined") {
		console.log(str);
	}
}

var Logger = {
		
	log: function(str) {
		if(typeof(console)!="undefined") {
			console.log(str);
		}
	},
	
	info: function(str) {
		if(typeof(console)!="undefined") {
			console.info(str);
		}
	},
	
	warn: function(str) {
		if(typeof(console)!="undefined") {
			console.warn(str);
		}
	},
	
	error: function(str) {
		if(typeof(console)!="undefined") {
			console.error(str);
		}
	},
	
	trace: function() {
		if(typeof(console)!="undefined") {
			console.trace();
		}
	},
	
	debug: function() {
		if(typeof(console)!="undefined") {
			console.debug();
		}
	},
	
	assert: function(cond, str) {
		if(typeof(console)!="undefined") {
			console.assert(cond, str);
		}
	}
	
};



