
var ajaxContent;
var ajaxURL = '';

var IE = document.all?true:false;
var IE7 = false;
if (!IE) 
	document.captureEvents(Event.MOUSEMOVE)

$(document).ready(function() {
	//document.onmousemove = getMouseXY;
	if (IE && parseInt(jQuery.browser.version) >= 7) {
		IE7 = true;
	}

	$.ajaxSetup({
		url : ajaxURL,
		//async: false,
		//cache: false,
		type: "post",
		dataType: "html",
		success: function(data) {
            var $out = $('#'+ajaxContent);
            //$out.html('Form success handler received: <strong>' + typeof data + '</strong>');
            if (typeof data == 'object' && data.nodeType)
                data = elementToString(data.documentElement, true);
            else if (typeof data == 'object')
                data = objToString(data);
            //$out.append('<div><pre>'+ data +'</pre></div>');
            $out.html(data);
			// alert(data);
		}//,
		//timeout: 3000,
		/*
		error: function(data) {
			alert('Błąd AJAX #01');	//alert(data);
		},
		*/
		//beforeSend: function(data) {
			//ajaxIndicator.style.display='block';
			//ajaxIndicatorCounter++;
		//},
		//complete: function(data) {
			//ajaxIndicatorCounter--;
			//alert(ajaxIndicatorCounter);
			//if (ajaxIndicatorCounter < 1)
			//	ajaxIndicator.style.display='none';
		//}
	});

	$("#ajax_msg").ajaxError(function(event, request, settings, thrownError) {
		$(this).append("<li>Error requesting page " + settings.url + "<br/><b>" + thrownError + "</b></li>");
		$(this).show();
		alert(objToString(request));
	});
	$("#ajax_msg").click(function() {
		$(this).hide();
		$(this).html('');
	})
	$(window).scroll(function() { 
		var tsc = $(this).scrollTop();
		$("#ajax_msg").css('top', (tsc+5)+'px');
		centerElemX('kategorie_sel');
		centerElemY('kategorie_sel');
	});
	/*
	$('#firma_ask_form').ajaxForm(function() { 
		alert("Thank you for your comment!"); 
	});
	*/
	//	$('.error_msg').animate({opacity: 1.0}, 20000, function() {
	//		$(this).slideUp(2000); //fadeOut

});

function aLoad(aDest, aUrl, aData) {
	$('#'+aDest).html('<img src="/gfx/indicator.gif" alt="" />');
	ajaxContent = aDest;
	$.ajax({
		url : aUrl,
		data: aData
	});
}

function inline_append(cUrl, cParams, retfield)
{
	ajaxContent = retfield;
	$.ajax({
		url: cUrl,
		data: cParams,
		success: function(data) {
			var $out = $('#'+ajaxContent);
			$out.append(data);
		}
	});
}

function inline_edit(vname, vtype, retfield)
{
	ajaxContent = retfield;
	$.ajax({
		url: "/ajaxed/form",
		data: 'varname='+vname+'&vartype='+vtype+'&retfield='+retfield
	});
}

function inline_save(vname, vtype, retfield, value)
{
	//alert('_action=save&varname='+vname+'&vartype='+vtype+'&retfield='+retfield+'&value='+value);
	//return;
	ajaxContent = retfield;
	$.ajax({
		url : "/ajaxed/form",
		data: '_action=save&varname='+vname+'&vartype='+vtype+'&retfield='+retfield+'&value='+value
	});
}

function setActiveTab(elem)
{
	$(elem).parent().each(function()
	{
		$(this).prevAll().removeClass('active');
		$(this).nextAll().removeClass('active');
		$(this).addClass('active');
	});
}

/*  jQuery FORM */
/*
// prepare the form when the DOM is ready 
$(document).ready(function() { 
    var options = { 
        target:        '#output1',   // target element(s) to be updated with server response 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse  // post-submit callback 
 
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 
 
    // bind form using 'ajaxForm' 
    $('#myForm1').ajaxForm(options); 
}); 
*/

function centerElemX(elemId)
{
	var w_width = $('#'+elemId).width();	//css('width');
	var s_width = $(window).width();
	var d_width = s_width - w_width;
	var scroll = $(window).scrollLeft();
	$('#'+elemId).css('left', Math.round(d_width / 2) + scroll);
}

function centerElemY(elemId)
{
	var w_height = $('#'+elemId).height();	//css('width');
	var s_height = $(window).height();
	var d_height = s_height - w_height;
	var scroll = $(window).scrollTop();
	$('#'+elemId).css('top', Math.round(d_height / 2) + scroll);
}

function clearFrom(elem_pre, start_id, end_id)
{
	for (var n=start_id; n<=end_id; n++)
	{
		$('#'+elem_pre+n).empty();
	}
}

function create_window(loadId, loadURL, loadParams, windowClass)
{
	if ($('#'+loadId).html() == null )
		$("#ajax_msg").after('<div id="'+loadId+'" class="'+windowClass+'"></div>');
	aLoad(loadId, loadURL, loadParams);
	centerElemX(loadId);
	centerElemY(loadId);
}

function disableForm(formData, jqForm, options) {
	var formElement = jqForm[0];
	$(formElement).find("input,textarea").css('background-color', '#eee');
	$(formElement).find("input[name='subm_button']").hide();
	$(formElement).find("input[name='subm_button']").after('<img src="/gfx/indicator.gif" alt="" /> Proszę czekać...');
}

// pre-submit callback 
function showRequest(formData, jqForm, options) { 
	// formData is an array; here we use $.param to convert it to a string to display it 
	// but the form plugin does this for you automatically when it submits the data 
	var queryString = $.param(formData); 

	// jqForm is a jQuery object encapsulating the form element.  To access the 
	// DOM element for the form do this: 
	// var formElement = jqForm[0]; 

	alert('About to submit: \n\n' + queryString); 

	// here we could return false to prevent the form from being submitted; 
	// returning anything other than false will allow the form submit to continue 
	return true; 
}

// post-submit callback 
function showResponse(responseText, statusText)  { 
	// for normal html responses, the first argument to the success callback 
	// is the XMLHttpRequest object's responseText property 

	// if the ajaxForm method was passed an Options Object with the dataType 
	// property set to 'xml' then the first argument to the success callback 
	// is the XMLHttpRequest object's responseXML property 

	// if the ajaxForm method was passed an Options Object with the dataType 
	// property set to 'json' then the first argument to the success callback 
	// is the json data object returned by the server 

	alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
		'\n\nThe output div should have already been updated with the responseText.'); 
}

// helper
function objToString(o) {
	var s = '{\n';
	for (var p in o)
		s += '    ' + p + ': ' + o[p] + '\n';
	return s + '}';
}

// helper
function elementToString(n, useRefs) {
	var attr = "", nest = "", a = n.attributes;
	for (var i=0; a && i < a.length; i++)thrownError
		attr += ' ' + a[i].nodeName + '="' + a[i].nodeValue + '"';

	if (n.hasChildNodes == false)
		return "<" + n.nodeName + "\/>";

	for (var i=0; i < n.childNodes.length; i++) {
		var c = n.childNodes.item(i);
		if (c.nodeType == 1)       nest += elementToString(c);
		else if (c.nodeType == 2)  attr += " " + c.nodeName + "=\"" + c.nodeValue + "\" ";
		else if (c.nodeType == 3)  nest += c.nodeValue;
	}
	var s = "<" + n.nodeName + attr + ">" + nest + "<\/" + n.nodeName + ">";
	return useRefs ? s.replace(/</g,'&lt;').replace(/>/g,'&gt;') : s;
};

function closeWindow(elem_id) {
	var mWindow = parent.document.getElementById(elem_id);
	$(mWindow).fadeOut(250, function () {	// slideUp , fadeOut , hide
		 $(this).remove();
	});
}

function ismaxlength(obj) {
	var mlength=obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
	if (obj.getAttribute && obj.value.length>mlength)
		obj.value=obj.value.substring(0,mlength)
}

function showGalleryImage(image_path)
{
	//$('#gallery_preview').fadeOut(250, function () {	// slideUp , fadeOut , hide
	//	 $(this).remove();
	//});
	$('#gallery_preview').remove();
	$('<div id="gallery_preview"><img class="gallery_indicator" src="/gfx/indicator.gif" style="float:left;" /></div>').insertBefore('#main');
	$('#gallery_preview').css('top', ($(window).height()/2 + $(window).scrollTop() - 10) + 'px');
	$('#gallery_preview').css('left', ($(window).width()/2 + $(window).scrollLeft() - 10) + 'px');
	$('<img src="'+image_path+'" class="gallery_image" style="filter:alpha(opacity=0); -moz-opacity:0; -khtml-opacity: 0; opacity: 0; //ddisplay:none; cursor:pointer;" title="Kliknij aby zamknąć podgląd";>').insertBefore('.gallery_indicator');
	// 
	$('#gallery_preview .gallery_image').load(function() {
		iwidth = $(this).width();
		iheight = $(this).height();
		xpos = ($(window).width()-iwidth)/2 + $(window).scrollLeft();
		ypos = ($(window).height()-iheight)/2 + $(window).scrollTop();
		$(this).queue(function () {
			$('#gallery_preview').animate({top : ypos}, 200).animate({left : xpos}, 200).animate({width : iwidth},500).animate({height : iheight},500, function() { 
				$('#gallery_preview .gallery_indicator').remove();
				$('#gallery_preview .gallery_image').fadeTo(1, 100);
				//$('#gallery_preview .gallery_image').show(100);
			});
			
			
			$(this).dequeue();
		});
			//
		$(this).click(function() {
			$(this).hide();
			$('#gallery_preview').remove();
		});
		//alert($(this).height());
	});
}

