jQuery.noConflict();
function cropImage(aspectRatioValue, trueSizeArray, setSelectArray, minSizeArray) {
    jQuery(function() {
        jQuery('#cropbox').Jcrop({
        	aspectRatio:	aspectRatioValue,
        	bgOpacity:		0.4,
        	minSize:		minSizeArray,
        	setSelect:		setSelectArray,
        	trueSize:		trueSizeArray,
        	onSelect:		updateCoords,
        	onChange:		updateCoords
        });
    });
    
	function updateCoords(c)
	{
		jQuery("#x").val(c.x);
		jQuery("#y").val(c.y);
		jQuery("#w").val(c.w);
		jQuery("#h").val(c.h);
		jQuery("#x2").val(c.x2);
		jQuery("#y2").val(c.y2);
	};
}

function autoscroll(box, item, type) {
	var item_count;
	var current_item = 0;
	var box_height;
	var item_height;
	var item_excess = 0;
	
	var scroll_pause = 5000;
	var scroll_jump = 33; //34
	var scroll_jump_animation_time = 1000; // 2000

	if(type == 'pulse') {
		scroll_jump = 33;
		scroll_jump_animation_time = 1000;
	}
	
	if (scroll_jump_animation_time >100 && scroll_pause-100 < scroll_jump_animation_time) {
		scroll_pause = scroll_jump_animation_time + 100;
	}
	jQuery(document).ready(function(){
 		item_count = jQuery(item).size();
 		box_height = parseInt(jQuery(box).css("height"));
 		item_height = parseInt(jQuery(item).css("height")); 		
 		if(item_count*item_height > box_height) { 			
 			item_excess = item_count*item_height - box_height;
 		}
 		for (var x = 0; x < item_count; x++)
		{
  			jQuery(item+":eq("+x+")").css('top', x*item_height+'px');
  		}  		
  		item_interval = setInterval(item_scroll, scroll_pause);
	});

	function item_scroll() {
		for (var x = 0;x < item_count; x++)
		{
			var current_item_top = parseInt(jQuery(item+":eq("+x+")").css('top'));
			if(current_item_top+item_height+item_excess <= 0) {
				jQuery(item+":eq("+x+")").css('top', (box_height - parseInt(jQuery(box).css("margin-top")) - parseInt(jQuery(box).css("margin-bottom")))+item_height+'px');
			}
  			jQuery(item+":eq(" + x + ")")
 				.animate({"top": "-="+scroll_jump+"px"}, scroll_jump_animation_time);
 		}
	}
}

//funkcja do przeładowywania pola miejscowosc przy rejestracji, dla mode = 'search' przy wyszukiwaniu
function autocompleter_city(mode, scriptDirectory) {
	jQuery(document).ready(
    function()
    {
    	if(!scriptDirectory) {
    		scriptDirectory = "../../lib/util/autocompleter_city.php";
    	}
    	if(mode != 'search') {
    		if(jQuery("#kraj_id").val() == 1) {
      	 		jQuery('#miejscowosc').attr('disabled', false);
      	 		jQuery('#wojewodztwo_id').attr('disabled', false);
     	  	}
      	 	else {
      	 		jQuery('#miejscowosc').attr('disabled', true);
      	 		jQuery('#wojewodztwo_id').attr('disabled', true);
      	 	}
       	}
    
    	jQuery("#miejscowosc").keyup(
    	function(event)
        {
       		lookup(jQuery("#miejscowosc").val(), scriptDirectory);
    	});
    	
    	jQuery("#miejscowosc").click(
    	function(event)
        {
       		lookup(jQuery("#miejscowosc").val(), scriptDirectory);
    	});
    	
    	if(mode != 'search') {
    		jQuery("#kraj_id").change(
    		function(event)
        	{
	       		if(jQuery("#kraj_id").val() == 1) {
       				jQuery('#miejscowosc').attr('disabled', false);
       				jQuery('#wojewodztwo_id').attr('disabled', false);
       			}
       			else {
	       			jQuery('#miejscowosc').attr('disabled', true);
       				jQuery('#wojewodztwo_id').attr('disabled', true);
       			}
    		});
   		}
   	});
}
function lookup(inputString, scriptDirectory) {
	if(inputString.length == 0 || jQuery("#wojewodztwo_id").val() == 17) {
    	// Hide the suggestion box.
    	jQuery('#suggestions').hide();
    } else {
    	jQuery.post(scriptDirectory + "/util/autocompleter_city.php", {queryString: ""+inputString+"", districtId: ""+jQuery("#wojewodztwo_id").val()+""}, function(data){
        	if(data.length >0) {
        		jQuery('#suggestions').show();
            	jQuery('#autoSuggestionsList').html(data);
         	}
    	});
	}
} // lookup

function fill(cityValue, districtValue) {
	jQuery('#miejscowosc').val(cityValue);
	jQuery('#wojewodztwo_id').val(districtValue);
	setTimeout("jQuery('#suggestions').hide();", 200);
}

//funkcja do informowania o ilości pozostałych znaków
function textLimit(textLimit, form_name, textarea_name, counter_name) {
        jQuery(document).ready(
        function()
        {
                jQuery("form[name="+form_name+"] textarea[name="+textarea_name+"]").keyup(
                function()
                {
                        var count_chars = jQuery(this).val().length;
                        if (count_chars > textLimit)
                        {
                                var new_value = jQuery(this).val().substring(0, textLimit);
                                jQuery(this).val(new_value)
                        }
                        jQuery("#"+counter_name+" span").html(""+textLimit - jQuery(this).val().length+"");
                });
        });
}

// zaznacza/odznacza elementy checkbox
function checkUncheckAll(theElement) {
     var theForm = theElement.form, z = 0;
	 for(z=0; z<theForm.length;z++){
      if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall'){
	  theForm[z].checked = theElement.checked;
	  }
     }
    }

function addget(adres,i,getname) {
	adres += getname;
	adres += "=";
	adres += i+1;
	window.location.assign(adres);
}

/*element html musi być w postaci: <select name='atrybut przekazywany w gecie' id=element_id > */
/*hyperlink = strona na którą ma przekierować po zmianie select*/
function submitOnChangeSelection(element_id, hyperlink) {
jQuery(document).ready(
		function()
		{
        	jQuery("#"+element_id).change(function() {
        		while(hyperlink.contains('&amp;'))
        			hyperlink = hyperlink.replace('&amp;', '&');
        		hyperlink = hyperlink.replace('&amp;', '&');
        		hyperlink = hyperlink.replace('&amp;', '&');
        		hyperlink = hyperlink.replace('&amp;', '&');
        		var getName = jQuery("#"+element_id).attr('name');
        		var getValue = jQuery("#"+element_id+" option:selected").attr('value');
        		var lastSign = hyperlink.substring(hyperlink.length-1, hyperlink.length);
        		if(lastSign == '?' || lastSign == '&')
        			address = (hyperlink+getName+'='+getValue);
        		else
        			address = (hyperlink+'&'+getName+'='+getValue);
        		window.location.assign(address);
        	});
		});
}

function disable(elementDisableDepend,elementToDisable,index) {
	if(document.getElementById(elementDisableDepend).selectedIndex==index){ 
		document.getElementById(elementToDisable).disabled=false;
	}
	else {
		document.getElementById(elementToDisable).disabled=true;
	}
}

function showGift(giftUrl) {
	jQuery('#giftShowDiv').css('background','url('+giftUrl+')');
}

function hideGift() {
	jQuery('#giftShowDiv').css('background','none');	
}

/**	
 *	służy do wysyłania tylko niepustych danych formularza
 *	domyślnie formName = 'searchform'
 */
function submitOnlyFilledFields(formName) {
jQuery(document).ready(
	function()
    {
    	if(!formName) formName = 'searchform';
    	jQuery('form[name='+formName+']').submit(function() {
    		//var action = jQuery("form").attr('action');
    		//var page1 = action.substring(action.length-17, action.length);	//search_result.php
    		//var page2 = action.substring(action.length-26, action.length);	//search_result_advanced.php
	   		//if(page1 == 'search_result.php' || page2 == 'search_result_advanced.php') {
    			jQuery("form[name="+formName+"] input, form textarea, form select").each(function() {
    				if(!this.value || this.value == 0)
    					switch(this.type) {
							case 'select-one':
								jQuery("select[name="+this.name+"]").attr('disabled', true);
								break;
							default:
								jQuery("input[name="+this.name+"]").attr('disabled', 'true');
						}
    		 		});
    		//}
    		return true;
    	 });
    }); 
}

var Pasek = new Class({
	
	initialize:function(width)
	{
          this.total = $('pasek').getStyle('width').toInt();
          this.width = width;
          $('pasek').setStyle('width',this.total+11);
	},
	
	paintBlock:function()
	{
          var elementy = this.total / 10;
          postep = this.width / 10;     // Ilość pól do zamalowania

          razem = 0;
          if (this.width == 0)
          {
                 for (k=1;k<11;k++)
                         {
                             a_element = new Element( 'a' , { 'href':this.url+'&vote='+k});
                             my_element = new Element( 'div' , { 'class': 'div10n','html':'&nbsp;'});
                             my_element.setStyles({ 'width':elementy+'px','display':'block','float':'left' });
                              if (k == 10)
                              {
                                my_element.setStyles({ 'border':'none'});
                              }
                             a_element.adopt(my_element);
                             $('pasek_container').adopt(a_element);
               }
               
               return;
          }
	
          
          for (i=1;i<postep;i++)
          {
              twdth = elementy;
              a_element = new Element( 'a' , { 'href':this.url+'&vote='+i});
              my_element = new Element( 'div' , { 'class': 'div10p','html':'&nbsp;'});
              my_element.setStyles({ 'width':twdth+'px','display':'block','float':'left' });
              razem = razem + twdth;
              if (i+1==postep) 
              {
               //my_element.setStyles({ 'border':'none'});
              }
              a_element.adopt(my_element);
              $('pasek_container').adopt(a_element);
          }
          //Dodanie ostatniego bloku pomniejszonego 
          i--;
          thpwg = 0;
          if (postep>i)
          {
              
              thpwg = postep -i;
              i++;
              //alert(thpwg);
              thpwg = (thpwg * elementy);
              thpwg = parseInt(thpwg);
              thpwg = thpwg;
              razem = razem + thpwg;
              a_element = new Element( 'a' , { 'href':this.url+'&vote='+i, 'title':this.title});
              my_element = new Element( 'div' , { 'class': 'div10p','html':'&nbsp;'});
              my_element.setStyles({ 'width':thpwg+'px','display':'block','float':'left' });
              if((razem % thpwg) != 0) my_element.setStyles({ 'border':'none'});
              a_element.adopt(my_element);
              $('pasek_container').adopt(a_element);
          }
          if (this.total != razem)
          {
          
               if (thpwg == elementy)
               {
                   for (k=i+1;k<11;k++)
                   {
                        a_element = new Element( 'a' , { 'href':this.url+'&vote='+k, 'title':this.title});
                        my_element = new Element( 'div' , { 'class': 'div10n','html':'&nbsp;'});
                        my_element.setStyles({ 'width':thpwg+'px','display':'block','float':'left' });
                         if (k == 10)
                         {
                           my_element.setStyles({ 'border':'none'});
                         }
                        a_element.adopt(my_element);
                        $('pasek_container').adopt(a_element);
                   }
               }
               else
               {
                    
                    k = i;
                    rest = elementy-thpwg;
                    if (i==10) rest = rest -1;
                    a_element = new Element( 'a' , { 'href':this.url+'&vote='+k, 'title':this.title});
                    my_element = new Element( 'div' , { 'class': 'div10n','html':'&nbsp;'});
                    my_element.setStyles({ 'width':rest+'px','display':'block','float':'left' });
                    a_element.adopt(my_element);
                    $('pasek_container').adopt(a_element);
                    //alert(i);
                    if (i != 10)
                    {
                         
                         for (k=i+1;k<11;k++)
                         {
                             a_element = new Element( 'a' , { 'href':this.url+'&vote='+k, 'title':this.title});
                             my_element = new Element( 'div' , { 'class': 'div10n','html':'&nbsp;'});
                             my_element.setStyles({ 'width':elementy+'px','display':'block','float':'left' });
                              if (k == 10)
                              {
                                my_element.setStyles({ 'border':'none'});
                              }
                             a_element.adopt(my_element);
                             $('pasek_container').adopt(a_element);
                         }
                    }
               }
          
          }
          
	
	},
	
	setTitle: function(title)
	{
          this.title = title;
	},
	
	setWidth: function(width){
               
                this.width = width;
                $('pasek_container').innerHTML = '';
                this.paintBlock();
		
		},
     setURL: function(url){
          
          this.url = url;
     
     
     }
	

});

//jCarousel
function jCarouselAutoscroll(element, bookmarkIdPrefix) {
	var autoSlow = 2;
	var autoFast = 0.01;
	var carousel = null;
	var maxSize = 15;
	
	jQuery(document).ready(function() {
    	jQuery(element).jcarousel({
    		vertical: true,
    		size: maxSize,
        	scroll: 1,
        	animation: 'slow',
        	auto: autoSlow,
        	wrap: 'last',
        	//easing: "bounceout",
        	initCallback: mycarousel_initCallback
        	//buttonPrevEvent: 'mouseOver',
        	//buttonNextEvent: 'mouseOver',
        	//itemLoadCallback: itemLoadCallbackFunction,
        	//itemVisibleInCallback: {
	        	//onBeforeAnimation: mycarousel_itemVisibleInCallbackBeforeAnimation
    	    	//},
        	//itemVisibleOutCallback: mycarousel_itemVisibleOutCallback
    	});
	});
	
	function itemLoadCallbackFunction(jc, state) {
		//if(state == 'init')alert('wait');
	};
	
	function mycarousel_itemVisibleInCallbackBeforeAnimation(jc, item, index, state)
	{
		//alert('mycarousel_itemVisibleInCallbackBeforeAnimation');
		//if(state != 'init') {
			var idx = jc.index(index, jc.options.size);
    		carousel.add(index, jc.get(idx).html());
    		carousel.selected=idx;
    	//}
	};
	
	function mycarousel_itemVisibleInCallbackAfterAnimation(jc, item, index, state)
	{
		//alert('mycarousel_itemVisibleInCallbackAfterAnimation');
    	var idx = jc.index(index, jc.options.size);
    	carousel.add(index, jc.get(idx).html());
		carousel.selected=idx;
	};
	
	function mycarousel_itemVisibleOutCallback(jc, item, index, state)
	{
		//alert('mycarousel_itemVisibleOutCallback');
		if(jc.options.size > maxSize && (index>jc.options.size || index<1)){
   			jc.remove(index);
   		}
   		jc.play();
	};
	
	function mycarousel_initCallback(jc, state)
	{
		if (state == 'init') {
			carousel = jc;
			jc.selected = 1;
			jc.disabled = false;
			if(jQuery(element).children().length > maxSize) jc.size(jQuery(element).children().length);
			if(jQuery(element).children().length <= maxSize) jc.disabled = true;
			jc.bookmark = 1;
			jc.length = jQuery(element).children().length;
			jc.startAutoOrig = jc.startAuto;
            jc.startAuto = function() {
            	if (!jc.paused) {
                	jc.startAutoOrig();
				}
			}
            jc.pause = function() {
            	jc.paused = true;
                jc.stopAuto();
			};
            jc.play = function() {
            	if(!jc.disabled) {
           			jc.paused = false;
					jc.startAuto();
				}
			};
			jc.clip.mouseover(function() {
				jc.pause();
			});
			jc.clip.mouseout(function() {
				jc.play();
			});
			jc.buttonPrev.bind('mouseover', function() {
				jc.options.auto = autoFast;
				jc.options.animation = 'slow';
				if(!jc.disabled) {
					jc.prev();
				}
				jc.options.scroll = -1;
			});
			jc.buttonPrev.bind('mouseout', function() {
				jc.options.auto = autoSlow;
				jc.options.scroll = 1;
				jc.options.animation = 'slow';
			});
			jc.buttonNext.bind('mouseover', function() {
				jc.options.auto = autoFast;
				jc.options.animation = 'slow';
				if(!jc.disabled) {
					jc.next();
				}
				jc.options.scroll = 1;
			});
			jc.buttonNext.bind('mouseout', function() {
				jc.options.auto = autoSlow;
				jc.options.scroll = 1;
				jc.options.animation = 'slow';
			});
			
			jQuery('[id^="' + bookmarkIdPrefix + '"]').click(function() {
				var id = jQuery(this).attr('id');
				var newBookmark = parseInt(id.substring(id.length-1, id.length));
				if(carousel.bookmark != newBookmark) {
					jc.pause();
					jc.bookmark = newBookmark;
					var sex = null;
					switch(carousel.bookmark) {
						case 2: sex = 'woman'; break;
						case 3: sex = 'man'; break;
						default: sex = 'all';
					}
			    	jQuery.post('./ajax/getOnlineUsers.php', {queryString: sex}, function(data){
			    		jc.jsonData = data;
			    		//jc.setup();
			    		jc.reset();
			    	});
				}
			});
    	}
    	else if (state == 'reset') {
    		carousel = jc;
    		jc.setup();
    		var userArray = jQuery.evalJSON(jc.jsonData);
    		jQuery.each(userArray, function(i, user) {
    			jc.add(i+1, html_a_helper(user.login, user.href) + ' ' + user.wiek + ' | ' + user.wojewodztwo);
			});
			jc.length = jQuery(element).children().length;
			if(jc.length > maxSize) jc.options.size = jc.length;
			else jc.options.size = maxSize;
			//alert(
    			//'jc.start: ' + jc.start + '\n' +
    			//'jc.last: ' + jc.last + '\n' +
    			//'jc.options.size: ' + jc.options.size + '\n' +
    			//'jc.offset: ' + jc.offset
    		//);
    		
    	}
    	if(jQuery(element).children().length <= maxSize) {
    		jc.disabled = true;
    		jc.buttons(false, false);
    	}
    	else {
    		jc.disabled = false;
    		jc.buttons(true, true);
    	}
    	jc.play();
	};
};

function html_li_helper(content) {
	var ret = '<li';
	//if(href) {
		//ret += ' href="' + href '"';
	//}
	ret += '>' + content + '</li>';
	return ret;
};

function html_a_helper(content, href) {
	var ret = '<a';
	if(href) {
		ret += ' href="' + href + '"';
	}
	ret += '>' + content + '</a>';
	return ret;
};

//progressbar

function beginUpload(element) {

	var percentage = 0;
	var waiting_for_upload = 0;
	
	jQuery(element).fadeIn();
	var i = setInterval(function() {
      	jQuery.post('./ajax/getUploadProgress.php', {id: progress_key}, function(jsonData) {
      		var data = jQuery.evalJSON(jsonData);
      		
      		if (data == null) {
      		
           		if (percentage > 0){
					jQuery(element).progressBar(100);
					clearInterval(i);						
		//			alert("Plik wgrany pomyslnie, zyczymy milego dnia!");
		//			location.reload(true);
           		}
					
           		waiting_for_upload = waiting_for_upload + 1;
          
           
				if (waiting_for_upload == 10){
					clearInterval(i);
		//			alert("Nikczemniku, probojesz wgrac za duzy plik!");
					location.reload(true);							
				}	
				return;
            	
      		}
            	
      		percentage = Math.floor(100 * parseInt(data.bytes_uploaded) / parseInt(data.bytes_total));
            jQuery(element).progressBar(percentage);
        });
    }, 1000);
    return false;
};
