(function($) {
    if ($("#d")[0]) {
        if ($("#d")[0].options.length > 1) {
            $('#d').removeAttr("disabled");
        }
    }

    if (isIE6() && (typeof supersleight!='undefined')) {
        $('body').supersleight();
    }
})(jQuery);

/*
 * jQuery message plug-in 1.0
 * http://bassistance.de/jquery-plugins/jquery-plugin-message/
 * Copyright (c) 2009 Jörn Zaefferer
 * $Id: jquery.message.js 6407 2009-06-19 09:07:26Z joern.zaefferer $
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function($){var helper,visible,timeout1,timeout2;$.fn.message=function(message){message=$.trim(message||this.text());if(!message){return;}clearTimeout(timeout1);clearTimeout(timeout2);initHelper();helper.find("p").html(message);helper.show().animate({opacity:$.message.defaults.opacity},$.message.defaults.fadeInDuration);visible=true;active=false;timeout1=setTimeout(function(){visible=false;},$.message.defaults.minDuration+$.message.defaults.displayDurationPerCharacter*Math.sqrt(message.length));timeout2=setTimeout(fadeOutHelper,$.message.defaults.totalTimeout);};function initHelper(){if(!helper){helper=$($.message.defaults.template).appendTo(document.body);$(window).bind("mousemove click keypress",fadeOutHelper);}}function fadeOutHelper(){if(helper.is(":visible")&&!helper.is(":animated")&&!visible){helper.animate({opacity:0},$.message.defaults.fadeOutDuration,function(){$(this).hide()})}}$.message={};$.message.defaults={opacity:0.9,fadeOutDuration:300,fadeInDuration:200,displayDurationPerCharacter:110,minDuration:2500,totalTimeout:6000,template:'<div class="jquery-message"><p></p></div>'}})(jQuery);

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}

	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break;

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};

	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};

})(jQuery);

function jq_czyscDzielnice() {
    $('#d').attr("disabled","disabled");
    $('#d > option:not(:first-child)').remove();
}

function jq_updateDzielnice(action,params) {
    jq_czyscDzielnice();
    $.getJSON(action,params,function(data){
        if(!jQuery.isEmptyObject(data)) {
            var d = $('#d');
            $.each(data, function(k, v) {
                d.append($('<option></option>').val(k).html(v));
            });
            if (d[0].options.length > 1) {
                d.removeAttr("disabled");
            }
        }
    });
}

function jq_dodajDoNotesu(link, dodane) {

    $.get(link, function(data) {
        $('#notes').html(data);
        $("#"+dodane).fadeIn(100, function () {
            $("#"+dodane).fadeOut(3000);
        });

        $("#notesInfoBox").fadeIn(100, function () {
            $("#notesInfoBox").fadeOut(3000);
        });

        var endColor = $('#notes').css('color');
        $("#notes").animate({ color: "#ff0000" }, 100).animate({ color: endColor }, 3000);

    });
}

function initLightbox() {
    if (window._initLightbox) {return} else {
        window._initLightbox = true;
    };

    jQuery(function() {
        /* lightboxy do okien */
        jQuery('a.okno').each(function() {
            jQuery(this).fancybox({
                overlayColor: '#282828',
                overlayOpacity: 0.8,
                transitionIn: 'elastic',
                transitionOut: 'elastic',
                height: '75%',
                type: 'iframe'
            });
        });

        jQuery('a.print').fancybox({
            overlayColor: '#282828',
            overlayOpacity: 0.8,
            transitionIn: 'elastic',
            transitionOut: 'elastic',
            height: '90%',
            width: 800,
            type: 'iframe'
        });

      var msg = [];
      msg['photo'] = 'Photo ';
      msg['of'] = ' of ';
      if (typeof LOCALE != 'undefined' && LOCALE == 'pl') {
        msg['photo'] = 'Zdjęcie ';
        msg['of'] = ' z ';
      }

        /* lightboxy do zdjec */
        jQuery('a[rel="lightbox[duze]"]').fancybox({
            overlayColor: '#282828',
            overlayOpacity: 0.8,
            transitionIn: 'elastic',
            transitionOut: 'none',
            titleFormat: function(title, currentArray, currentIndex, currentOpts) {
                return '<span id="fancybox-title-wrap"><span id="fancybox-title-left"></span><span id="fancybox-title-main">'+ msg['photo'] + (currentIndex + 1) + msg['of'] + currentArray.length + '</span><span id="fancybox-title-right"></span></span>';
            }
        });

        jQuery('a[rel="lightbox[male]"]').fancybox({
            overlayColor: '#282828',
            overlayOpacity: 0.8,
            transitionIn: 'elastic',
            transitionOut: 'none',
            titleFormat: function(title, currentArray, currentIndex, currentOpts) {
                return '<span id="fancybox-title-wrap"><span id="fancybox-title-left"></span><span id="fancybox-title-main">'+ msg['photo'] + (currentIndex + 1) + msg['of'] + currentArray.length + '</span><span id="fancybox-title-right"></span></span>';
            }
        });
    });
}

function no(strToUrl,name,width,height)
{
    window.open(strToUrl, name, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width= ' + (width) + ',height=' + (height) + ',left=' + (screen.width / 2 - width / 2) + ',top=' + (screen.height / 2 - height / 2));
}

function isIE6() {
    return jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7;
}

function drukuj(x) {
    if (isIE6()) {
        alert('Używasz bardzo starej przeglądarki. Jeśli drukowanie nie rozpocznie się automatycznie, w menu u góry wybierz Plik -> Drukuj');
    }
    jQuery(x).jqprint();
    return false;
}

(function($) {
	$.fn.emailencode = function(options) {
		var settings = jQuery.extend({
			atsign: "*",
			replaceText: true
		}, options);

		return this.each(function() {
			var address = $(this).attr("href");
			var formattedAddress = address.replace(settings.atsign, "@");
			$(this).attr("href", "mailto:" + formattedAddress);
			if (settings.replaceText) {
                if (formattedAddress.indexOf('?')>0) {
                    formattedAddress = formattedAddress.substring(0, formattedAddress.indexOf('?'));
                }
                $(this).text(formattedAddress);
            }
		});
	};
})(jQuery);

function notepadAddRemove(url,thisButton,otherButton) {
    j(thisButton).siblings(".loadingOverlay").show();
    j.post(url, function(responseData) {
        var count = responseData.replace(/[^0-9]/g,"");
        j('.notepad-counter').each(function() {
            j(this).html(count);
        });
        j(thisButton).siblings(".loadingOverlay").hide();
        j(thisButton).hide();
        j(otherButton).show();
        j().message("Liczba ofert w notesie: "+count); /* requires message plugin */
    });
}

function notepadRemove(link,callerElem) {
    j(callerElem).siblings(".loadingOverlay").show();
    j.post(link, function(responseData) {
        j('.notepad-counter').each(function() {
            j(this).html(responseData.replace(/[^0-9]/g,""));
        });
        j(callerElem).closest(".search_results_list_item").remove();
        if (j(".search_results_list_item").length===0) {
            j(".notepadButtons").remove();
            j("#notepadEmpty").show();
        }
    });
}

function clearDropdown(dropdown) {
    j(dropdown).attr("disabled","disabled");
    j(dropdown).find('option:not(:first-child)').remove();
}

function updateDropdown(dropdown, actionUrl, params) {
    var dd = j('#'+dropdown);
    clearDropdown(dd);

    j.getJSON(actionUrl,params,function(responseData){
        if(!j.isEmptyObject(responseData)) {

            j.each(responseData, function(k, v) {
                //dd.append(j('<option></option>').val(k).html(v));
                dd.append(j("<option />").val(k).text(v));
            });

            if (dd[0].options.length > 1) {
                dd.removeAttr("disabled");
            } else {
                dd.attr("disabled","disabled");
            }
        }
    });
}

function compareSelected(checkboxName, url) {
    var checkedBoxes = j('input:checkbox[name='+checkboxName+']:checked');
    if (checkedBoxes.length<2) {
        alert("Musisz zaznaczyć przynajmniej 2 oferty do porównania");
        return;
    }
    var offersToCompare = [];
    j(checkedBoxes).each(function(i) {
        offersToCompare[i] = j(this).val();
    });
    j.fancybox.showActivity();
    j.post(url,{o:offersToCompare}, function(responseData){
        j.fancybox({
            content: responseData,
            hideOnOverlayClick: false,
            titleShow: false,
            title: 'Porównanie ofert',
            overlayOpacity: 0.5,
            centerOnScroll:true
        });
    });
}

function removeFromComparison(offer) {
    if (j(".compItem").length==1) {
        j.fancybox.close();
    } else {
        j('.'+offer).remove();
    }
}

var hoverNav = function(gallery) {
    var g;
    if (gallery) {
        g = jQuery(gallery);
    } else {
        g = jQuery("#offer_photos");
    }
    if (g.length > 0) {
        g.each(function() {
            var container = this;
            var nav = jQuery('.photo-small-ul', this);
            jQuery('li', nav).each(function() {
                jQuery(this).hover(function() {
                    jQuery('li', nav).removeClass('on');
                    jQuery(this).addClass('on');
                    var i = jQuery('li', container).index(this);
                    jQuery('.photo-div', container).hide();
                    jQuery(jQuery('.photo-div', container)[i]).show();
                });
            });
        });
    }
};

