$(document).ready(function() {

       jQuery.preLoadImages("/images/menu/aktualnosci_n.png", "/images/menu/aktualnosci_o.png", "/images/menu/do_pobrania_n.png", "/images/menu/do_pobrania_o.png", "/images/menu/dolacz_do_nas_n.png", "/images/menu/dolacz_do_nas_o.png", "/images/menu/dzialalnosc_n.png", "/images/menu/dzialalnosc_o.png", "/images/menu/galerie_n.png", "/images/menu/galerie_o.png", "/images/menu/home_n.png", "/images/menu/home_o.png", "/images/menu/o_nas_n.png", "/images/menu/o_nas_o.png", "/images/menu/partnerzy_i_ilinki_n.png", "/images/menu/partnerzy_i_ilinki_o.png");

	if ($('#right-panel-active').length > 0) { 

		$('#home-right-column').sortable({
			connectWith: '.dragbox',
			handle: '.drag-and-drop',
			update: function() { getOrder(); },
			cursor: 'move',
			placeholder: 'placeholder',
			forcePlaceholderSize: true,
			opacity: 0.4

		});  

		restoreOrder();

	}

    $('.drag-and-drop').tipTip();
	
	$('a.fancybox').fancybox({'titleShow':true, 'titlePosition':'over', 'cyclic' : true });
	$('a.fancybox2').fancybox({'titleShow':true, 'titlePosition':'over', 'cyclic' : true });
	
 	$('.drag-and-drop').mouseover(function() {
             document.body.style.cursor = 'pointer';
        });

 	$('.drag-and-drop').mouseout(function() {
             document.body.style.cursor = 'default';
        });

        // karuzela - po kliknieciu na zdjeie przenosi nas do zasobu
 	$('.carousel #content-box').mouseover(function() {
             document.body.style.cursor = 'pointer';
        });

 	$('.carousel #content-box').mouseout(function() {
             document.body.style.cursor = 'default';
        });

 	$('.carousel #content-box').click(function() {
                var tempElement1 = $('.carousel #left-box #element1');
                var tempElement2 = $('.carousel #left-box #element2');
                var tempElement3 = $('.carousel #left-box #element3');

if ($(tempElement1).hasClass('element1_link_hover')) {
    document.location.href = $(tempElement1).find('a').attr("href");
}

if ($(tempElement2).hasClass('element2_link_hover')) {
    document.location.href = $(tempElement2).find('a').attr("href");
}

if ($(tempElement3).hasClass('element3_link_hover')) {
    document.location.href = $(tempElement3).find('a').attr("href");
}


               
        });


	$('.thickbox').click(function() {
            $(this).attr('title', $(this).attr('rel'));            
         });
	// mechanizm zakladek
	
	$('.tabs-set a').click(function() {
		var obj = $(this).parent();
		var id = $(this).attr('rel');
		
		// zabezpieczenie przed ponownym kliknieciem tego samego
		if (! $(obj).hasClass('tab-content-dark')) {

			$(obj).toggleClass('tab-content-dark');
			$(obj).toggleClass('tab-content-light');

			right_bar = $(obj).next();

			$(right_bar).toggleClass('tab-right-dark');
			$(right_bar).toggleClass('tab-right-light');

			// odznaczamy pozostale 
			$('.tabs-set').children().each(function() {
				if ($(this).attr('id') != ('tab-item' + id)) {
					var obj = $(this).find('a').parent();

					$(obj).removeClass('tab-content-light');
					$(obj).removeClass('tab-content-dark');
					$(obj).addClass('tab-content-light');

					right_bar = $(obj).next();

					$(right_bar).removeClass('tab-right-dark');
					$(right_bar).removeClass('tab-right-light');
					$(right_bar).addClass('tab-right-light');
				}
			});
			
			// chowamy ukrywamy wiadomosci
			$('.tabs-news-container').children().each(function() {
				if ($(this).attr('id') != ('news-tab-' + id)) {
					$(this).hide();
				} else {
					$(this).show();
				}
			});

		}

	});
	
	// pokaz lokalizacje
	$('#view_map').click(function() {
		$.getScript('/js/jquery-1.3.2.min.js');
	});
	
	
	// submit komentarza
	$('#submitComment').click(function() {
		$('#commentForm').submit();
	});
	
	$('#commentForm input[type=text]').keypress(function(e) {
		  if (e.keyCode == '13') {
		     e.preventDefault();
		     $('#commentForm').submit();
		   }
		});
	
	
	
	// menu hover
	
	var menuElementOverlay = $('<div id="menuOverlayOverlay"></div>');
	$(menuElementOverlay).css({ 'position' : 'absolute', 'background-color' : '#bf0800', 'height' : '15px', 'z-index' :  '2000' });
	$(menuElementOverlay).css('margin-top', '-14px');
	$(menuElementOverlay).css({ 'border-left' : '1px solid #ababad', 'border-right' : '1px solid #ababad' });


        $('.top-menu li').each(function() {
            if ($(this).attr('id')) {
                if ($('#menu-element-' + $(this).attr('id')).length > 0) {
                    var arrow = $('<img src="/images/arr_more.png" />');
                    $(arrow).css('position', 'absolute');
                    $(arrow).css('z-index', '2100');
                    $(arrow).css('margin-top', '60px');


                    position = $(this).position();
                    $(arrow).css('left', position.left + 10);

                    $(this).prepend($(arrow));
                }
            }

        });

	$('.top-menu li').mouseover(function() {
		if ($('#menu-element-' + $(this).attr('id')).length > 0) {
			var parent = $('#menu-element-' + $(this).attr('id'));
			
		    $(menuElementOverlay).css('width', $(this).width() - 1);
 		
		    $(parent).css('margin-left', '-1px');
		    
		    position = $(this).position();
		    
		    $(parent).css('left', position.left);
		    
		    $(parent).prepend($(menuElementOverlay));
     	            $(parent).css('visibility', 'visible');

		}
		 
	});
	$('.top-menu li').mouseout(function() {
		   var parent = $('#menu-element-' + $(this).attr('id'));
		   $('#menu-element-' + $(this).attr('id')).css('visibility', 'hidden');
		   // $('.top-menu li div').css('visibility', 'hidden');
                   // $(parent).find('img').remove();
	    });
	
	
	// zmiana wielkosci czcionki
	
	maxi=24;
	mini=12;
	step=2;
	// subject=".basic-text-content";
	subject = '#container_lev_1';
	dColor="#CCC";
	eColor="#09C";
	
	$.fn.getFontSize = function(){
	    return parseInt(($(this).css("font-size")).replace("px",""));
	}
	$.fn.disableLink = function() {
	    $(this).css({color:dColor,cursor:"default"});
	}
	$.fn.enableLink = function() {
	    $(this).css({color:eColor,cursor:"pointer"});
	}
	$.fn.checkDisabled = function() {
	    if($(this).css({color:dColor})||$(this).css({cursor:"default"})) return true;
	    else return false;
	}
	
	if (! $.cookie('font-size')) {
		$.cookie('font-size', 0);
	}
	
	// przywracanie wartosci z ciastka
	current = parseInt(($(subject).css("font-size")).replace("px",""));
	$(subject).css("font-size",current + parseInt($.cookie('font-size')));
	
	$('#content-title-box').css('font-size', 12);
	
	$(".change-font-size .font-plus").click(function(){
	    current = parseInt(($(subject).css("font-size")).replace("px",""));
	    if(current<maxi) {
	        $(subject).css("font-size",current+step);
	        $.cookie('font-size', parseInt($.cookie('font-size')) + step);
	        
	        $('#content-title-box').css('font-size', 12);
	        // if($("#minus").checkDisabled())
	        //     $("#minus").enableLink();
	    }
	    // if((current+step)==maxi) $(this).disableLink();
	});
	$(".change-font-size .font-minus").click(function(){
		current = parseInt(($(subject).css("font-size")).replace("px",""));
	    if(current>mini) {
	        $(subject).css("font-size",current-step);
	        $.cookie('font-size', parseInt($.cookie('font-size')) - step);
	        
	        $('#content-title-box').css('font-size', 12);
	        
	        // if($("#plus").checkDisabled())
	        //     $("#plus").enableLink();
	    }
	    // if((current-step)==mini) $(this).disableLink();
	});
	
	
	// dodawanie do newslettera
	$('#newsletter_submit').click(function() {
		initNewsletter();
	});
	
	$('input#newsletter_input').keypress(function(e) {
		  if (e.keyCode == '13') {
		     e.preventDefault();
		     initNewsletter();
		   }
		});

	$('#newsletter_submit2').click(function() {
		initNewsletter2();
	});
	
	$('input#newsletter_input2').keypress(function(e) {
		  if (e.keyCode == '13') {
		     e.preventDefault();
		     initNewsletter2();
		   }
		});

	
	 
	if ($('.carousel').length > 0) {
	
	// It's carousel script
	$('.carousel li').mouseenter(function(evt) {
		
		// kasuj wszystko oprocz aktualnego
		carouselMouseout($('.carousel #element1'));
		carouselMouseout($('.carousel #element2'));
		carouselMouseout($('.carousel #element3'));
		
		$('.carousel').find('ul').parent().append('<div id="carousel_stop"></div>');
		carouselMouseover($(this));
	});

	$('.carousel li').mouseleave(function(evt) {
		
		$('#carousel_stop').remove();
	    // carouselMouseout($(this));
	    
	    var leaveId = $(this).attr('id');
	    
	    leaveIdStr = leaveId.substr((leaveId.length - 1), 1); 
	    
	     $('#carousel-current').attr('rel', leaveIdStr);
	     // carouseMouseover($(this));
	});
	
	// domyslne wyswietlanie w petli
	carouselAutomate();
	
	}
	
	// inicjalizacja sondy
	initPoll();
	
	
});

function initNewsletter() {
	$.ajax({ 
		url: "newsletter.php",
		type: "POST",
		data: "email=" + $('#newsletter_input').val(),
		success: function(msg) {
                    var warning = false;
                    for (o = 0; i < msg.length; i++) {
                        if (msg[i] == '@') {
                            warning = true;
                            break;
                        }
                    }

	            $('#newsletterMessage').text(msg).show().css('border', '1px solid green');
                    $('#newsletterMessage').css('color', 'green');

                    if (! warning) {
                        $('#newsletterMessage').css('border', '1px solid red');
                        $('#newsletterMessage').css('color', 'red');
                    }
      }});
	
}

function initNewsletter2() {
	$.ajax({ 
		url: "newsletter.php",
		type: "POST",
		data: "email=" + $('#newsletter_input2').val(),
		success: function(msg) {
                    var warning = false;
                    for (i = 0; i < msg.length; i++) {
                        if (msg[i] == '@') {
                            warning = true;
                            break;
                        }
                    }

	            $('#newsletterMessage2').text(msg).show().css('border', '1px solid green');
                    $('#newsletterMessage2').css('color', 'green');

                    if (! warning) {
                        $('#newsletterMessage2').css('border', '1px solid red');
                        $('#newsletterMessage2').css('color', 'red');
                    }
      }});
	
}

// funkcja do sondy
function initPoll() {
	// testujemy wyniki
	
	
	$('#pollForm').ajaxForm(function(myData) {
		// robimy mega splita :D
		var parameters = myData.split('|'); 
		
		if (parameters[0] == '1') {
			$('#pollForm').hide();
			
			$.ajax({
				  url: 'vote_results.php',
				  success: function(data) {
				    
				    var parent = $('#pollForm').parent();     
				
				    $(parent).html($(data).find('.small-box-content').html()).fadeIn();
				    
				    $(parent).find('#pollMessage').html(parameters[1]).show();
				    
				    $('#pollForm').parent().fadeIn();
				  }
				});	
			
		}
		
		// alert(parameters[0]);
		
		$('#pollMessage').html(parameters[1]).show();
		
	});
	
	$('#submitPollForm').click(function() {
		$('#pollForm').submit();
	});
	
	 // blokada aby bylo mozna zaznaczyc tylko n wartosci
	$('#pollForm').find('input[type=checkbox]').click(function() {
		// alert($('#pollMultiple').val());
		
		valo = $('#pollMultipleNow').val();
		
		if ($('#pollMultiple').val() <= valo && $(this).attr('checked')) {
			alert('Można zaznaczyć maksymalnie ' + $('#pollMultiple').val() + '!');
			$(this).removeAttr('checked');
				
			return;
		}
		
		if ($(this).attr('checked')) {
			valo = $('#pollMultipleNow').val();
			$('#pollMultipleNow').val(parseInt(valo) + 1);
			
		} else {
			valo = $('#pollMultipleNow').val();
			$('#pollMultipleNow').val(parseInt(valo) - 1);
		}
		
	});
	
}

// automatyczne wyswietlanie karuzeli
function carouselAutomate() {
	if (! ($('#carousel_stop').length > 0)) {
	
	var elements = $('.carousel').find('ul').find('li');
	
	var currentElementFind = $('.carousel').find('#carousel-current');
	
	// jezeli nie istnieje aktualny element
	if (! ($(currentElementFind).length > 0) || $(currentElementFind).attr('rel') == 3) {
		$(currentElementFind).remove();
		carouselMouseout($('.carousel').find('ul').find('#element3'));
		
		var currentElement = $('<div id="carousel-current" rel="1"></div>');
		$('.carousel').find('ul').parent().append($(currentElement));
	} else {
		int = $(currentElementFind).attr('rel');
		
		$(currentElementFind).attr('rel', (parseInt(int) + 1));
		var currentElement = currentElementFind;
		
		// zmiana poprzedniego elementu
		carouselMouseout($('.carousel').find('ul').find('#element' + parseInt(int)));
		
	}
	
	var changeElement = $('.carousel').find('ul').find('#element' + $(currentElement).attr('rel'));
	
	// domyslna wartosc zaznaczona
	carouselMouseover($(changeElement));

	}
	
	setTimeout('carouselAutomate()', 5000);
}


// karuzela wyswietlanie po najechaniu mysza
function carouselMouseover(obj) {
	// zabezpieczenie - wydajnosc
	if (! ($('#' + $(obj).attr('id') + '_hover').length > 0)) {
	
	var position = $(obj).position();
	
	var hover_object = $('<div id="' + $(obj).attr('id') + '_hover"></div>');
	$('.carousel').find('ul').after(hover_object);
	
	$('#' + $(obj).attr('id') + '_hover').css({ 'top' : position.top, 'left' : ($(obj).width() + position.left) - 7 });
	$('#' + $(obj).attr('id') + '_hover').addClass($(obj).attr('id') + "_hover");
	
	$(obj).addClass('borders_' + $(obj).attr('id'));
	
	$(obj).removeClass("shadow");
	$(obj).addClass($(obj).attr('id') + '_link_hover');
	
	// zalaczanie zdjecia po najechaniu
	var newImage = $('<img style="display: none; height: 280px; width: 409px" class="new_image" src="' + $(obj).attr('rel') + '" />');
	
	// $('.carousel').find('#content-box').append($(newImage));
	$('.carousel').find('#content-box').prepend($(newImage));
	var imgObj = $('.carousel').find('#content-box').find('img[class!=new_image]');
	
	
	if ($(obj).find('a').attr('title')) {
		// opis dla zdjecia
		$('#content-title-box').show();
		var contentBoxPosition = $('#content-box').position();

		$('#content-title-box').text($(obj).find('a').attr('title'));
		if (! $.browser.msie) {
		    $('#content-title-box').css({ "top" : contentBoxPosition.top + 254, 'left' : (contentBoxPosition.left + 392) - $('#content-title-box').width()});
		} else {
			$('#content-title-box').css({ "top" : contentBoxPosition.top + 254, 'left' : (contentBoxPosition.left + 392) - $('#content-title-box').width()});
		}    
	} else {
		$('#content-title-box').hide();
	}
	
	// alert($(imgObj).html());
	
	// kasowanie starych elementow
	// alert($('.carousel #content-box').find('img:last').html());
	
	// wersja rozszerzona
	$(imgObj).fadeOut(function() {
		$(imgObj).remove();
		$(newImage).fadeIn();
		$(newImage).removeClass('new_image');
	}); 
	
	
	// wersja podstawowa
	/* 
	$(imgObj).remove();
	$(newImage).show();
	$(newImage).removeClass('new_image'); */
	}
}

//karuzela wyswietlanie po opuszczeniu obszaru
function carouselMouseout(obj) {
	var position = $(obj).position();
	
	$(obj).removeClass('borders_' + $(obj).attr('id'));
	
	$(obj).addClass('shadow');
	$(obj).removeClass($(obj).attr('id') + '_link_hover');
	
	$('#' + $(obj).attr('id') + '_hover').remove();
	
	
/*	fix? 
	if ($('.carousel').find('#content-box').find('img[class!=new_image]').length > 1) {
		
		firstObj = $('.carousel').find('#content-box').find('img:first');
		
		$('.carousel').find('#content-box').find('img[class!=new_image]').each(function() {
			$(this).remove();
		});
		
		$('.carousel').find('#content-box').append($(firstObj));
	} */
	
}

function getOrder() {
	// save custom order to cookie
	
	var sortorder='';
	
	$('.dragbox').each(function(){
		var itemorder = $(this).sortable('toArray');
		var columnId = $(this).attr('id');
		sortorder += columnId + ',';
	});

	
	$.cookie('dragbox-saved-new', sortorder, { expires: 7, path: "/" });
}
 

// przywracanie kolejnosci z ciasteczek
function restoreOrder() {
    var elements = $.cookie('dragbox-saved-new');
    
	var parentElements = new Array();
	var z = 0;
	
    $('.dragbox').each(function(){
		var columnId = $(this).attr('id');
		parentElements[z] = columnId;
		z++;
		
	});
    
    
    if (elements) {
        var arr = elements.split(',');
        
        if (arr.length == 6) {

        // przechodzenie przez oryginalna kolejnosc
        for (i = 0; i < parentElements.length; i++) {
        	if (parentElements[i]) {
                    if (arr[i]) {
        		// kopiujemy element z ciastka
        		var obj = $('#' + arr[i]).clone();

        		// tworzymy kopie elementu
        		$(obj).attr('id', $(obj).attr('id') + '_copy'); 
        		
        		// odwolanie sie do starej wersji
        		var parent = $('#' + parentElements[i]);
        		
        		// usuniecie z kopii (jezeli istnieje) klasy po ktorej wykrywamy usuwanie
        		$(obj).removeClass('remove-all-boxes');
        		
        		// dodajemy element przed stara wersja
        		$(parent).before($(obj));
        		
        		// dodajemy klase do starej wersji
        		$(parent).addClass('remove-all-boxes');
                        }
        	}
        }
        
    	// kasujemy przedrostek _copy
    	for (i = 0; i < arr.length; i++) {
    		if (arr[i]) {
    		    var idName = $('#' + arr[i] + '_copy').attr('id');
    		    var fixName = idName.substr(0, idName.length - 5);
    		    
    		    $('#' + arr[i] + '_copy').attr('id', fixName);
    		}
    	}

        // usuwamy stare wersje (kolejnosc)
        $('.remove-all-boxes').remove();

        }
    }     
    
}

/*!
 * jQuery Form Plugin
 * version: 2.43 (12-MAR-2010)
 * @requires jQuery v1.3.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {

/*
	Usage Note:
	-----------
	Do not use both ajaxSubmit and ajaxForm on the same form.  These
	functions are intended to be exclusive.  Use ajaxSubmit if you want
	to bind your own submit handler to the form.  For example,

	$(document).ready(function() {
		$('#myForm').bind('submit', function() {
			$(this).ajaxSubmit({
				target: '#output'
			});
			return false; // <-- important!
		});
	});

	Use ajaxForm when you want the plugin to manage all the event binding
	for you.  For example,

	$(document).ready(function() {
		$('#myForm').ajaxForm({
			target: '#output'
		});
	});

	When using ajaxForm, the ajaxSubmit function will be invoked for you
	at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
	// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
	if (!this.length) {
		log('ajaxSubmit: skipping submit process - no element selected');
		return this;
	}

	if (typeof options == 'function')
		options = { success: options };

	var url = $.trim(this.attr('action'));
	if (url) {
		// clean url (don't include hash vaue)
		url = (url.match(/^([^#]+)/)||[])[1];
   	}
   	url = url || window.location.href || '';

	options = $.extend({
		url:  url,
		type: this.attr('method') || 'GET',
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
	}, options || {});

	// hook for manipulating the form data before it is extracted;
	// convenient for use with rich editors like tinyMCE or FCKEditor
	var veto = {};
	this.trigger('form-pre-serialize', [this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
		return this;
	}

	// provide opportunity to alter form data before it is serialized
	if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSerialize callback');
		return this;
	}

	var a = this.formToArray(options.semantic);
	if (options.data) {
		options.extraData = options.data;
		for (var n in options.data) {
		  if(options.data[n] instanceof Array) {
			for (var k in options.data[n])
			  a.push( { name: n, value: options.data[n][k] } );
		  }
		  else
			 a.push( { name: n, value: options.data[n] } );
		}
	}

	// give pre-submit callback an opportunity to abort the submit
	if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSubmit callback');
		return this;
	}

	// fire vetoable 'validate' event
	this.trigger('form-submit-validate', [a, this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
		return this;
	}

	var q = $.param(a);

	if (options.type.toUpperCase() == 'GET') {
		options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
		options.data = null;  // data is null for 'get'
	}
	else
		options.data = q; // data is the query string for 'post'

	var $form = this, callbacks = [];
	if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
	if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

	// perform a load on the target only if dataType is not provided
	if (!options.dataType && options.target) {
		var oldSuccess = options.success || function(){};
		callbacks.push(function(data) {
			var fn = options.replaceTarget ? 'replaceWith' : 'html';
			$(options.target)[fn](data).each(oldSuccess, arguments);
		});
	}
	else if (options.success)
		callbacks.push(options.success);

	options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
		for (var i=0, max=callbacks.length; i < max; i++)
			callbacks[i].apply(options, [data, status, xhr || $form, $form]);
	};

	// are there files to upload?
	var files = $('input:file', this).fieldValue();
	var found = false;
	for (var j=0; j < files.length; j++)
		if (files[j])
			found = true;

	var multipart = false;
//	var mp = 'multipart/form-data';
//	multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

	// options.iframe allows user to force iframe mode
	// 06-NOV-09: now defaulting to iframe mode if file input is detected
   if ((files.length && options.iframe !== false) || options.iframe || found || multipart) {
	   // hack to fix Safari hang (thanks to Tim Molendijk for this)
	   // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
	   if (options.closeKeepAlive)
		   $.get(options.closeKeepAlive, fileUpload);
	   else
		   fileUpload();
	   }
   else
	   $.ajax(options);

	// fire 'notify' event
	this.trigger('form-submit-notify', [this, options]);
	return this;


	// private function for handling file uploads (hat tip to YAHOO!)
	function fileUpload() {
		var form = $form[0];

		if ($(':input[name=submit]', form).length) {
			alert('Error: Form elements must not be named "submit".');
			return;
		}

		var opts = $.extend({}, $.ajaxSettings, options);
		var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

		var id = 'jqFormIO' + (new Date().getTime());
		var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ opts.iframeSrc +'" onload="(jQuery(this).data(\'form-plugin-onload\'))()" />');
		var io = $io[0];

		$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

		var xhr = { // mock object
			aborted: 0,
			responseText: null,
			responseXML: null,
			status: 0,
			statusText: 'n/a',
			getAllResponseHeaders: function() {},
			getResponseHeader: function() {},
			setRequestHeader: function() {},
			abort: function() {
				this.aborted = 1;
				$io.attr('src', opts.iframeSrc); // abort op in progress
			}
		};

		var g = opts.global;
		// trigger ajax global events so that activity/block indicators work like normal
		if (g && ! $.active++) $.event.trigger("ajaxStart");
		if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && $.active--;
			return;
		}
		if (xhr.aborted)
			return;

		var cbInvoked = false;
		var timedOut = 0;

		// add submitting element to data if we know it
		var sub = form.clk;
		if (sub) {
			var n = sub.name;
			if (n && !sub.disabled) {
				opts.extraData = opts.extraData || {};
				opts.extraData[n] = sub.value;
				if (sub.type == "image") {
					opts.extraData[n+'.x'] = form.clk_x;
					opts.extraData[n+'.y'] = form.clk_y;
				}
			}
		}

		// take a breath so that pending repaints get some cpu time before the upload starts
		function doSubmit() {
			// make sure form attrs are set
			var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST')
				form.setAttribute('method', 'POST');
			if (form.getAttribute('action') != opts.url)
				form.setAttribute('action', opts.url);

			// ie borks in some cases when setting encoding
			if (! opts.skipEncodingOverride) {
				$form.attr({
					encoding: 'multipart/form-data',
					enctype:  'multipart/form-data'
				});
			}

			// support timout
			if (opts.timeout)
				setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

			// add "extra" data to form if provided in options
			var extraInputs = [];
			try {
				if (opts.extraData)
					for (var n in opts.extraData)
						extraInputs.push(
							$('<input type="hidden" name="'+n+'" value="'+opts.extraData[n]+'" />')
								.appendTo(form)[0]);

				// add iframe to doc and submit the form
				$io.appendTo('body');
				$io.data('form-plugin-onload', cb);
				form.submit();
			}
			finally {
				// reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
				t ? form.setAttribute('target', t) : $form.removeAttr('target');
				$(extraInputs).remove();
			}
		};

		if (opts.forceSync)
			doSubmit();
		else
			setTimeout(doSubmit, 10); // this lets dom updates render
	
		var domCheckCount = 100;

		function cb() {
			if (cbInvoked) 
				return;

			var ok = true;
			try {
				if (timedOut) throw 'timeout';
				// extract the server response from the iframe
				var data, doc;

				doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
				
				var isXml = opts.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
				log('isXml='+isXml);
				if (!isXml && (doc.body == null || doc.body.innerHTML == '')) {
				 	if (--domCheckCount) {
						// in some browsers (Opera) the iframe DOM is not always traversable when
						// the onload callback fires, so we loop a bit to accommodate
				 		log('requeing onLoad callback, DOM not available');
						setTimeout(cb, 250);
						return;
					}
					log('Could not access iframe DOM after 100 tries.');
					return;
				}

				log('response detected');
				cbInvoked = true;
				xhr.responseText = doc.body ? doc.body.innerHTML : null;
				xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
				xhr.getResponseHeader = function(header){
					var headers = {'content-type': opts.dataType};
					return headers[header];
				};

				if (opts.dataType == 'json' || opts.dataType == 'script') {
					// see if user embedded response in textarea
					var ta = doc.getElementsByTagName('textarea')[0];
					if (ta)
						xhr.responseText = ta.value;
					else {
						// account for browsers injecting pre around json response
						var pre = doc.getElementsByTagName('pre')[0];
						if (pre)
							xhr.responseText = pre.innerHTML;
					}			  
				}
				else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
					xhr.responseXML = toXml(xhr.responseText);
				}
				data = $.httpData(xhr, opts.dataType);
			}
			catch(e){
				log('error caught:',e);
				ok = false;
				xhr.error = e;
				$.handleError(opts, xhr, 'error', e);
			}

			// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
			if (ok) {
				opts.success(data, 'success');
				if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
			}
			if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
			if (g && ! --$.active) $.event.trigger("ajaxStop");
			if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

			// clean up
			setTimeout(function() {
				$io.removeData('form-plugin-onload');
				$io.remove();
				xhr.responseXML = null;
			}, 100);
		};

		function toXml(s, doc) {
			if (window.ActiveXObject) {
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = 'false';
				doc.loadXML(s);
			}
			else
				doc = (new DOMParser()).parseFromString(s, 'text/xml');
			return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
		};
	};
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *	is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *	used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
	return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
		e.preventDefault();
		$(this).ajaxSubmit(options);
	}).bind('click.form-plugin', function(e) {
		var target = e.target;
		var $el = $(target);
		if (!($el.is(":submit,input:image"))) {
			// is this a child element of the submit el?  (ex: a span within a button)
			var t = $el.closest(':submit');
			if (t.length == 0)
				return;
			target = t[0];
		}
		var form = this;
		form.clk = target;
		if (target.type == 'image') {
			if (e.offsetX != undefined) {
				form.clk_x = e.offsetX;
				form.clk_y = e.offsetY;
			} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
				var offset = $el.offset();
				form.clk_x = e.pageX - offset.left;
				form.clk_y = e.pageY - offset.top;
			} else {
				form.clk_x = e.pageX - target.offsetLeft;
				form.clk_y = e.pageY - target.offsetTop;
			}
		}
		// clear form vars
		setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
	});
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
	return this.unbind('submit.form-plugin click.form-plugin');
};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
	var a = [];
	if (this.length == 0) return a;

	var form = this[0];
	var els = semantic ? form.getElementsByTagName('*') : form.elements;
	if (!els) return a;
	for(var i=0, max=els.length; i < max; i++) {
		var el = els[i];
		var n = el.name;
		if (!n) continue;

		if (semantic && form.clk && el.type == "image") {
			// handle image inputs on the fly when semantic == true
			if(!el.disabled && form.clk == el) {
				a.push({name: n, value: $(el).val()});
				a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
			continue;
		}

		var v = $.fieldValue(el, true);
		if (v && v.constructor == Array) {
			for(var j=0, jmax=v.length; j < jmax; j++)
				a.push({name: n, value: v[j]});
		}
		else if (v !== null && typeof v != 'undefined')
			a.push({name: n, value: v});
	}

	if (!semantic && form.clk) {
		// input type=='image' are not found in elements array! handle it here
		var $input = $(form.clk), input = $input[0], n = input.name;
		if (n && !input.disabled && input.type == 'image') {
			a.push({name: n, value: $input.val()});
			a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
		}
	}
	return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
	//hand off to jQuery.param for proper encoding
	return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
	var a = [];
	this.each(function() {
		var n = this.name;
		if (!n) return;
		var v = $.fieldValue(this, successful);
		if (v && v.constructor == Array) {
			for (var i=0,max=v.length; i < max; i++)
				a.push({name: n, value: v[i]});
		}
		else if (v !== null && typeof v != 'undefined')
			a.push({name: this.name, value: v});
	});
	//hand off to jQuery.param for proper encoding
	return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *	  <input name="A" type="text" />
 *	  <input name="A" type="text" />
 *	  <input name="B" type="checkbox" value="B1" />
 *	  <input name="B" type="checkbox" value="B2"/>
 *	  <input name="C" type="radio" value="C1" />
 *	  <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *	   array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
	for (var val=[], i=0, max=this.length; i < max; i++) {
		var el = this[i];
		var v = $.fieldValue(el, successful);
		if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
			continue;
		v.constructor == Array ? $.merge(val, v) : val.push(v);
	}
	return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
	var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	if (typeof successful == 'undefined') successful = true;

	if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1))
			return null;

	if (tag == 'select') {
		var index = el.selectedIndex;
		if (index < 0) return null;
		var a = [], ops = el.options;
		var one = (t == 'select-one');
		var max = (one ? index+1 : ops.length);
		for(var i=(one ? index : 0); i < max; i++) {
			var op = ops[i];
			if (op.selected) {
				var v = op.value;
				if (!v) // extra pain for IE...
					v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
				if (one) return v;
				a.push(v);
			}
		}
		return a;
	}
	return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
	return this.each(function() {
		$('input,select,textarea', this).clearFields();
	});
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
	return this.each(function() {
		var t = this.type, tag = this.tagName.toLowerCase();
		if (t == 'text' || t == 'password' || tag == 'textarea')
			this.value = '';
		else if (t == 'checkbox' || t == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
	return this.each(function() {
		// guard against an input with the name of 'reset'
		// note that IE reports the reset function as an 'object'
		if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
			this.reset();
	});
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
	if (b == undefined) b = true;
	return this.each(function() {
		this.disabled = !b;
	});
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
	if (select == undefined) select = true;
	return this.each(function() {
		var t = this.type;
		if (t == 'checkbox' || t == 'radio')
			this.checked = select;
		else if (this.tagName.toLowerCase() == 'option') {
			var $sel = $(this).parent('select');
			if (select && $sel[0] && $sel[0].type == 'select-one') {
				// deselect all other options
				$sel.find('option').selected(false);
			}
			this.selected = select;
		}
	});
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
	if ($.fn.ajaxSubmit.debug) {
		var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
		if (window.console && window.console.log)
			window.console.log(msg);
		else if (window.opera && window.opera.postError)
			window.opera.postError(msg);
	}
};

})(jQuery);



(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

