/*
	Podpowiedzi do inputów tekstowych
*/
/*
(function($) {
  $.fn.inputPrompt = function() {
		this.each( function() {
			this.orgValue = this.value;

			$(this).focus( function() {
				if ( this.value == this.orgValue ) {
					this.value = '';
				}
			});

			$(this).blur( function() {
				if ( this.value == '' ) {
					this.value = this.orgValue;
				}
			});
		});
  };
})(jQuery);
*/

/*
	Zamiana <hr /> na <div class="hr"><hr /></div>

	extendHR([options]) {
		...
	}

	className = String
*/
(function($) {
  $.fn.extendHR = function(className) {
		if ( className ) {
			this.wrap('<div></div>').parent().addClass( className );
		} else {
			this.wrap('<div class="hr"></div>');
		}
  };
})(jQuery);


/*
	Wyróżnianie kolejnych wierszy tabeli poprzez przypisanie (cykliczne) każdemu wierszowi jednej z podanych klas

	options = {
		cycle = new Array();
	};
*/
(function($) {
  $.fn.zebraTable = function(options) {
		if ( options && options.cycle && options.cycle.length > 1 ) {
			this.each( function() {
				var i = 0;
				var maxi = options.cycle.length-1;

				$('tbody tr', this).each( function() {
					$(this).addClass(options.cycle[i]);
					(i<maxi)?i++:i=0;
				});
			});
		}
  };
})(jQuery);


/*
	Wyróżnianie kolejnych elementów listy (ul) poprzez przypisanie (cykliczne) każdemu wierszowi jednej z podanych klas

	options = {
		cycle = new Array();
	};
*/
(function($) {
  $.fn.zebraUL = function(options) {
		if ( options && options.cycle && options.cycle.length > 1 ) {
			this.each( function() {
				var i = 0;
				var maxi = options.cycle.length-1;

				$('li', this).each( function() {
					$(this).addClass(options.cycle[i]);
					(i<maxi)?i++:i=0;
				});
			});
		}
  };
})(jQuery);


/*
expandTrigger
*/
(function($) {
  $.fn.receipesSearchPanel = function() {
		if ( this && this.length ) {
			$( $(this).attr('rel') ).hide();
			$(this).toggle(
				function() {
					$( $(this).attr('rel') ).show();
					$(this).addClass('expanded');

					return false;
				},
				function() {
					$( $(this).attr('rel') ).hide();
					$(this).removeClass('expanded');

					return false;
				}
			);
		}
  };
})(jQuery);



/*
expandableWhy
*/
(function($) {
  $.fn.expandableWhy = function() {

		if ( this && this.length ) {
			$('.whyMore', this).hide();

			$('.more-less', this).toggle(
				function() {
					var $this = $(this);
					$this.parents('.expandable').find('.whyMore').show();
					$this.addClass('expanded');

					return false;
				},
				function() {
					var $this = $(this);
					$this.parents('.expandable').find('.whyMore').hide();
					$this.removeClass('expanded');

					return false;
				}
			);
		}
  };
})(jQuery);


/*
 * wyrownanie bloczków
 */

(function($) {
  $.fn.equalize = function( children ) {
    if(!children){
      return this;
    }
    this.each(function(){
      if( typeof children == "string" ){
	var thisChildren = $(children, this);
      }
      else if(children instanceof jQuery){
	var thisChildren = children;
      }
      if(thisChildren instanceof jQuery && thisChildren.length > 0){
				var hMax = Math.max.apply( null, thisChildren.map(function(){ return $(this).height(); }).toArray() );
				thisChildren.height( hMax );
      }
    });

    return this;
  };
})(jQuery);



(function($) {
  $.fn.playerTriggerIco = function() {
    this.each( function() {
			var $this = $(this);

			$this.parents('a').css('background-image', 'url('+$this.attr('src')+')');
			$this.wrapAll("<span></span>").css('visibility','hidden').parent().addClass("playerIco");
		});
  };
  
  $.fn.addPhotoTriggerIco = function() {
    this.each( function() {
			var $this = $(this);

			$this.parents('a').css('background-image', 'url('+$this.attr('src')+')');
			$this.wrapAll("<span></span>").css('visibility','hidden').parent().addClass("addPhoto");
		});
  };
})(jQuery);


/*
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// MAIN
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

// $(document).ready( function() { ... });
$(function() {

    /* wyrownanie wysokosci boksow */
    //$('.receipesList').equalize('.receipesListItem .content');
    $('.receipesList').equalize('.receipesListItem .receipesListItemContainer');
    $('.categories > ul').equalize('ul');
    $('.przygotowanie ol, ul.prizeOrderStepsList, ul.threeStepsList').equalize('li');
    $('.split-v').equalize('.groupbox');
    $('.magazineList').equalize('li .content');


    if (location.hash == "#playMovie") {
        setTimeout(function() { $('a.playMovieTrigger').trigger('click'); }, 1000);
    }

    $('#playerTrigger img').playerTriggerIco();
    $('#addPhotoTrigger img').addPhotoTriggerIco();

    // wysokosci boksow w szkole gotowania
    $('#coockingSchool #movieList div.boxContainer').each(function(i) {
        if (!(i % 2)) {
            var $this = $(this);
            var $next = $this.next();
            $this.add($next).height(Math.max($this.height(), $next.height()));
        }
    });

    // linki w nowym oknie
    $('#fbfan, .FBlikebox a,a.newWindow').attr('target', '_blank');


    $('a[rel=_blank]').attr('target', '_blank');

    $("#photoWrapper .tabs").tabs("#photoWrapper div.items > div.item", {
        // enable "cross-fading" effect
        effect: 'fade',
        fadeOutSpeed: "slow",
        // start from the beginning after the last tab
        rotate: true
        // use the slideshow plugin. It accepts its own configuration
    }).slideshow({ autoplay: true, interval: 5000 });

    // Zakładki - Ranking przepisów
    $("#receipesRankContainer .tabs").tabs("#receipesRankContainer div.tabContentContainer div.tabContent", {
        // enable "cross-fading" effect
        effect: 'fade',
        fadeOutSpeed: 0,
        // start from the beginning after the last tab
        rotate: false
        // use the slideshow plugin. It accepts its own configuration
    });


    $("#tabs-receipeWrapper .tabs-receipe").tabs("#tabs-content-receipeWrapper .tab-content-receipe-item", {
        // enable "cross-fading" effect
        current: 'active',
        tabs: 'li',
        effect: 'fade',
        fadeOutSpeed: 0,
        // start from the beginning after the last tab
        rotate: false
        // use the slideshow plugin. It accepts its own configuration
    });

    // zakladki - dzieci - gry
    $('ul.gametabs').tabs('#gry-dla-dzieci > .tabContent', { effect: 'fade' });

    // zakladki - szukaj klubowiczow
    $('#membersSearch ul.tabs').tabs('#membersSearch > div.collapsable > div > form', { effect: 'fade' });

    $(".receipeDetailsTabsNav .receipeDetailsTabs").tabs(".receipeDetailsTabItems .receipeDetailsTabItem", {
        // enable "cross-fading" effect
        current: 'active',
        tabs: 'li',
        effect: 'fade',
        fadeOutSpeed: 0,
        // start from the beginning after the last tab
        rotate: false
        // use the slideshow plugin. It accepts its own configuration
    });

    $('#searchReceipes a.expandTrigger').receipesSearchPanel();

    $('table.eventsList,table.topReceipes,table.searchResults').zebraTable({ cycle: ['odd', 'even'] });
    $('ul.zebra').zebraUL({ cycle: ['odd', 'even'] });
    $('hr').extendHR();
    //	$('input[type=text]').inputPrompt();

    /*
    * podmiana elementow <select> na listy a checkboxami
    */


    if ($('a.overlayExpose').length) {
        $('a.overlayExpose').overlay({
            // each trigger uses the same overlay with the id "gallery"
            target: '#overlayExposeContainer',
            // optional exposing effect
            expose: '#fcf5c2',
            top: '10%'
            // let the gallery plugin do its magic!
        }).gallery({
            // the plugin accepts its own set of configuration options
            speed: 800
        });
    }

    /* FLV Player */
    $('a[rel=#flvOverlay]').overlay({
        // optional exposing effect
        expose: '#fcf5c2',
        // let the gallery plugin do its magic!
        effect: 'default',

        onBeforeLoad: function() {
            // grab wrapper element inside content
            this.getContent().find(".contentWrap").load(this.getTrigger().attr("href"));
        }

    });
    /**/

    /* FLV Player */
    $('a[rel=#contestOverlay]').overlay({
        // optional exposing effect
        expose: '#444439',
        // let the gallery plugin do its magic!
        effect: 'default',

        onBeforeLoad: function() {
            // grab wrapper element inside content
            this.getContent().find(".contestWrap").load(this.getTrigger().attr("href"));
        }

    });

	var lbon = 0;


	$.fn.lightboxForm = function() {
		if (lbon) return;
		$('#lightboxForm').css({visibility: 'visible'});
		lbon = 1;		
	}

	
    $('.konkursGaleria a.wezUdzial').click(function() {
		$(this).lightboxForm();
    });

    $('#lightboxForm a.close').click(function() {
		if (!lbon) return;
		obj = $(this).parents('#lightboxForm');
		obj.css({visibility: 'hidden'});
		lbon = 0;
    });
/*	
    $('#lightboxForm input.text').focus(function() {
		$(this).blur();
		$(this).siblings('input.file').trigger('click');
    });
*/	


    $('#lightboxForm input.file').change(function() {
		$(this).siblings('input.text').val($(this).val()).blur();
    });


	$.fn.justshowLBImage = function() {
		if (lbon) return;
		obj2 = $('#lightboxGallery');
		var w = obj2.find('img').width()+30;
		var h = obj2.find('img').height()+30;
		if (w>30 && h>30) obj2.find('.lightboxAbs').css({margin: h/-2+'px 0 0 '+w/-2+'px'});
		obj2.find('.lightboxAbs').css({width: w+'px'});
		obj2.css({visibility: 'visible'});
		lbon = 1;		
	};
	$.fn.showLBImage = function() {
		if (lbon) return;
		obj = $(this).parents('li').eq(0).find('.details');
		obj2 = $('#lightboxGallery');
		obj.clone().appendTo(obj2.find('.lightboxAbs .lb_window'));
		var w = obj2.find('img').width()+30;
		var h = obj2.find('img').height()+30;
		obj2.find('.lightboxAbs').css({width: w+'px', margin: h/-2+'px 0 0 '+w/-2+'px'});
		obj2.css({visibility: 'visible'});
		lbon = 1;		
	};
	$.fn.hideLBImage = function() {
		if (!lbon) return;
		obj2 = $('#lightboxGallery');
		obj2.css({visibility: 'hidden'});
		obj2.find('.details').remove();
		lbon = 0;
	};

	
    $('.konkursGaleria ul.gallery li a').not('.nxt a, .bck a').click(function() {
		$(this).showLBImage();
    });
    $('#lightboxGallery a.close').click(function() {
		$(this).hideLBImage();
    });
// fb dla kanapek	-karol - zakomentowanie 
//	fb_hidelike = function() {
//		if ($('#Kanapki2011 .games #fb-like')[0]) $('#Kanapki2011 .games #fb-like').remove();		
//	};
//	fb_showlike = function(d) {
//		fb_hidelike();		
//		$('#Kanapki2011 .games').append('<div id="fb-like"><iframe allowTransparency="true"  src="http://www.facebook.com/plugins/like.php?app_id=226699874019891&amp;href=http%3A%2F%2Fwww.winiary.pl%2Fkanapki.aspx%2Fkanapkowe-zabawy-galeria%3Fid%3D'+d+'&amp;send=false&amp;layout=button_count&amp;width=0&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:21px;" allowTransparency="true"></iframe></div>');

//	};
	
	
    $('div.carousel')
    $('div.carousel').prepend('<a class="prevPage browse left"></a>').append('<a class="nextPage browse right"></a>').find("div.scrollable").scrollable({
        size: 3,
        keyboard: false,
        onBeforeSeek: function() {
            if (this.getIndex() == 0) {
                var items = this.getItems();
                if ($('a img', items[3]).length == 0) {
                    var spanImg = $('a .spanImg', items[3]);
                    $('a', items[3]).prepend('<img alt="" src="' + spanImg.text() + '" height="82px" width="65px">');
                    spanImg.remove();
                }
                if ($('a img', items[4]).length == 0) {
                    var spanImg = $('a .spanImg', items[4]);
                    $('a', items[4]).prepend('<img alt="" src="' + spanImg.text() + '" height="82px" width="65px">');
                    spanImg.remove();
                }
                if ($('a img', items[5]).length == 0) {
                    var spanImg = $('a .spanImg', items[5]);
                    $('a', items[5]).prepend('<img alt="" src="' + spanImg.text() + '" height="82px" width="65px">');
                    spanImg.remove();
                }                               
            }
        }
    });

    $('div.carousel').each(function() {
        $(this).height($('ul', this).height());
    });

    $("#hometabs > ul").tabs("#hometabs div.panes > div", { effect: 'fade' });

    //DD_roundies.addRule('.rounded3px', '3px', true);
    DD_roundies.addRule('.r3', '3px');
    DD_roundies.addRule('.r5', '5px');

    DD_roundies.addRule('#tab-first.active', '5px 0 0 0', true);
    DD_roundies.addRule('#tab-last.active', '0 5px 0 0', true);

    $('li.category')
      .find('div.title')
      .append('<span></span>')
	.find('span')
	.click(
	  function() {
	      $(this).closest('div').toggleClass('box').closest('li').toggleClass('collapsed').toggleClass('r5');
	  })
	.end()
      .end()
      .filter('li + li')
	.addClass('collapsed')
	.removeClass('r5')
	  .find('div.title')
	  .addClass('box');


    $('#subNavigation .active a[href*=#]').click(
      function() {
          var id = $(this).attr('href').replace(/^[^#]*/, '');

          $(id).find('.title.box span').trigger('click');
      });

    $('select').dropdown();
    $('.append').appender();
    $('form a.cleanForm').click(function() {
        var F = $(this).closest('form');
        F.find('.target').empty();
        F.find(':checkbox, :radio').attr('checked', 'checked');
        F.find(':text').val('').trigger('blur');
        F.find('div.dropdown select').val('').trigger('change');
        return false;
    });

    var fbtimer = null;
    var fbon = false;
    $.fn.hideLikebox = function() {
        $("#facebook-likebox-outer").removeClass('shown');
    } // hover na wyszukiwarce nie moze wywolywac likeboxa
    $("#facebook-likebox .handle").click(
		function() {
		    if ($("#facebook-likebox-outer").hasClass('shown')) $("#facebook-likebox-outer").animate({ right: '-394px' }, "600", $.fn.hideLikebox);
		    else $("#facebook-likebox-outer").addClass('shown').animate({ right: '-1px' }, "600");
		});


    if (window.location.hash != '') {
        $('a[href$=' + window.location.hash + ']').trigger('click');
        if (window.location.hash.indexOf('comment-') > -1) {
            $('a[href$=#tab-komentarze]').trigger('click');
            var posTop = $('li.' + window.location.hash.replace('#', '')).addClass('highlight').position().top;
            window.scrollTo(0, posTop);
        }
    }

    $('.expandable').expandableWhy();

    $('#searchReceipes form').submit(function() {
        $(this).find('.append input:text').remove();
    });

    var origProducts = $('select[name=productID]'), filteredProducts = origProducts.parent();
    filteredProducts.hide();
    $('select#ProductCategories').change(function() {
        var groupID = $(this).val();
        var filteredList = $('<select name="productID"></select>').html('<option value="">Wybierz produkt</option>' + origProducts.find('#group-' + groupID).html());
        filteredProducts.empty().append(filteredList).show().find('select').dropdown();
    });

    $('.shortNavi .expandableInfo').hover(
		function() {
		    $(this).addClass('expandableInfo-expanded');
		},
		function() {
		    $(this).removeClass('expandableInfo-expanded');
		}
	);

    /*
    *
    *
    */
    $('#membersSearch a.btn-zwin-rozwin').click(function() {
        $(this).toggleClass('btn-zwiniety');
        $('#membersSearch .collapsable').toggle();
    });
    /*
    * zlaszanie do moderatora
    */
    var modForm = $('#modForm').css({ 'position': 'absolute' }).hide();
    if (modForm.length > 0) {
        $('a.abuse, a[href$=#zglos-naduzycie]').click(function() {
            // var xy = $(this).offset();
            var $this = $(this);
            var xy = $this.position();

            modForm.toggle().css({ top: xy.top, right: '30px' });
            return false;
        });
        $('a.default', modForm).click(function() {
            modForm.toggle();
            return false;
        });
    }

    $('body.ie6 table.searchResults img.thumb').parent().hover(
      function() {
          $(this).addClass('hover');
      },
      function() {
          $(this).removeClass('hover');
      }
    );

    $('body.ie6 div.filter').hover(
      function() {
          $(this).addClass('hover');
      },
      function() {
          $(this).removeClass('hover');
      }
    );


    $('input[type=text]').focus(function() {
        var temp = $(this).data('placeholder');
        if (temp) { this.value = (this.value == temp) ? '' : this.value; }
    }).blur(function() {
        var temp = $(this).data('placeholder');
        if (temp) { this.value = (this.value == '') ? temp : this.value; }
    });

    $('input:text[name=mainKeyword]').data('placeholder', 'Szukaj w serwisie').trigger('blur');
    $('input:text[name=keyword]').data('placeholder', 'Szukane słowo...').trigger('blur');
    $('input:text[name=component]').data('placeholder', 'Nazwa składnika...').trigger('blur');
    $('#coockingSchool input:text[name=phrase]').data('placeholder', 'Szukaj porady kulinarnej...').trigger('blur');
    $('input#email').data('placeholder', 'Twój adres e-mail...').trigger('blur');
    $('input#pomyslna-szukaj').data('placeholder', 'Wpisz nazwę składnika').trigger('blur');
    $('input#favSoup').data('placeholder', 'Szukaj...').trigger('blur');

    if (typeof window.pageTrackPlayer == "undefined") { window.pageTrackPlayer = function() { } };

    $('a#quizAnswersTrigger').click(function() {
        $this = $(this);
        $($this.attr('rel')).show();
        $this.remove();

        return false;
    });
    $($('a#quizAnswersTrigger').attr('rel')).hide();

    /* kącik razosnych zakupów */
    if ($('#klubKRZ').length == 1) {
        function forceRecalculate() {
            var changed = false;
            $('.basket-order input.number-short')
	  .each(function() {
	      if ($(this).val() != $(this).data('origVal')) { changed = true; }
	  });
            return changed;
        }
        $('.basket-order input.number-short')
	.keyup(function() {
	    if (forceRecalculate()) {
	        $('a.dalej').hide();
	        $('#btnprzelicz').fadeIn();
	    }
	    else {
	        $('#btnprzelicz').hide();
	        $('a.dalej').fadeIn();
	    }
	})
	.blur(function() {
	    $(this).val(parseInt($(this).val(), 10) || 1);
	})
	.each(function() {
	    $(this).data('origVal', $(this).val());
	});

        $('#deliveryaddress input[type=text]')
	.change(function() {
	    $('#agree').attr('checked', false);
	})
	.blur(function() {
	    $('.field-validation-valid:empty').parent().remove();
	})
	.each(function() {
	    $(this).data('origVal', $(this).val());
	});

        $('#agree')
	.change(function() {
	    if (!$(this).is(':checked')) {
	        $('#deliveryaddress input[type=text]').val('');
	    }
	    else {
	        $('#deliveryaddress input[type=text]')
		       .each(function() {
		           $(this).val($(this).data('origVal'));
		       });
	    }
	});

        $('#btnkoszyk')
	.hover(function() {
	    $('#klubInfoBar .lista').show()
	});
        $('#klubInfoBar').bind('mouseleave', function() { $('#klubInfoBar .lista').hide() });

        if ($('.basket-order').length > 0) {
            window.setTimeout(function() {
                $('.actioninfo').animate({ 'opacity': 0 }, 10000);
            }, 5000);
        }
    }


    /* MAJONEZY 2011 */
    $('#Majonezy2011 ul.checkList input[type=radio]').click(function() {
        var $this = $(this);
        var $wishWrapp = $('#cardWishes');

        var $newImg = $('<img />');

        switch (this.id) {
            case 'wishRadio-1':
                $newImg.attr('src', '../Content/Img/Subpages/Majonezy2011/card_wishes-1.png'); break;
            case 'wishRadio-2':
                $newImg.attr('src', '../Content/Img/Subpages/Majonezy2011/card_wishes-2.png'); break;
            case 'wishRadio-3':
                $newImg.attr('src', '../Content/Img/Subpages/Majonezy2011/card_wishes-3.png'); break;
        }

        $wishWrapp.find('img').fadeOut(500, function() {
            $wishWrapp.find('img').remove();
            $wishWrapp.append($newImg);
        });

        $wishWrapp.find('img').show(500);

    }).filter(':checked').each(function() {
        var $this = $(this);

        setTimeout(function() { $this.trigger('click') }, 250);
    });

    $('#Majonezy2011 #senderFirstname').keyup(function() {
        var $senderFirstname = $('#senderFirstname');
        var $cardSignature = $('#cardSignature');

        $cardSignature.text($senderFirstname.val());
    }).trigger('keyup');
	
	
	
	/* KANAPKI 2011 */
	
	$.fn.schoolKidTypeShow = function() {
		$(this).removeClass('shrinked').find('.show').removeClass('shown');
	}
	$.fn.schoolKidTypeHide = function() {
		$(this).addClass('shrinked').find('.show').addClass('shown');
	}
	$('.SchoolKidsTypes li .show').click(function(){
		$(this).parents('.SchoolKidsTypes li').schoolKidTypeShow();
	}).eq(0).parents('.SchoolKidsTypes li').siblings().schoolKidTypeHide();
	$('.SchoolKidsTypes li .hide').click(function(){
		$(this).parents('.SchoolKidsTypes li').schoolKidTypeHide();
	}).eq(0).parents('.SchoolKidsTypes li').siblings().schoolKidTypeHide();
});

var addthis_config = {
	services_compact: 'email, favorites, facebook, google, twitter, blip'
};
