jQuery.fn.extend({
    scrollTo : function(speed, easing, val) {
        return this.each(function() {
            var targetOffset = $(this).offset().top + val;
            $('html,body').animate({
                scrollTop: targetOffset
            }, speed, easing);
        });
    }
});

window.alert = function(text) {
	$("body").append("<div class=\"pole_message_info\">"+text+"</div>");
	$("#blackout").css("display","block");
	wysoko=$("body").css("height");
	if(wysoko=="auto") {
		wysoko=$(document).height();
	}
	$("#blackout").css("height",wysoko);
	//$('html, body').animate({scrollTop:0}, 'fast');
	var hideMsg = function(){
		$(".pole_message_info").fadeTo('fast','0',function(){
			$(".pole_message_info").css("display","none");
			if($(".pole_message_info").css("display")=="block" || $(".pole_message").css("display")=="block" || $(".pole_message_info").css("display")=="block"){
				
			}else{
				$("#blackout").css("display","none");
			}
			$(".pole_message_info").remove();
		});
	};
	
	$(".pole_message_info").click(function() { hideMsg(); });
	setTimeout(hideMsg, 1500);
	
	
}


$(document).ready(function () {
	if($(".pole_message_err").css("display")=="block" || $(".pole_message").css("display")=="block" || $(".pole_message_info").css("display")=="block"){
		$("#blackout").css("display","block");
		wysoko=$("body").css("height");
		if(wysoko=="auto") {
			wysoko=$(document).height();
		}
		$("#blackout").css("height",wysoko);
		$('html, body').animate({scrollTop:0}, 'fast');
		
	}
	$(".pole_message_err").click(function(){
		$(".pole_message_err").fadeTo('fast','0',function(){
			$(".pole_message_err").css("display","none");
			if($(".pole_message_err").css("display")=="block" || $(".pole_message").css("display")=="block" || $(".pole_message_info").css("display")=="block"){
				
			}else{
				$("#blackout").css("display","none");
			}
		});
	});
	$(".pole_message").click(function(){
		$(".pole_message").fadeTo('fast','0',function(){
			$(".pole_message").css("display","none");
			if($(".pole_message_err").css("display")=="block" || $(".pole_message").css("display")=="block" || $(".pole_message_info").css("display")=="block"){
				
			}else{
				$("#blackout").css("display","none");
			}
		});
	});
	$(".pole_message_info").click(function(){
		$(".pole_message_info").fadeTo('fast','0',function(){
			$(".pole_message_info").css("display","none");
			if($(".pole_message_err").css("display")=="block" || $(".pole_message").css("display")=="block" || $(".pole_message_info").css("display")=="block"){
				
			}else{
				$("#blackout").css("display","none");
			}
		});
	});
    var $contentMiddle = $('#contentMiddle');
    var $product = $('#product');
    var $goToTop = $('#goToTop');
    var numInc = 1;
    var $productManufacturerData = $product.find('tr.manufacturer td.data');
    if($contentMiddle.find('h1.top_text').html() != undefined)
        if($contentMiddle.find('h1.top_text').html().match(/przechowalnia/ig))
            $('body').addClass('isStorage');
    if($productManufacturerData.html() == ''){
        $productManufacturerData.parent().addClass('displayNone');;
    }
    $goToTop.click(function(){
        $product.scrollTo('slow','swing');
    });
    $('#mycarousel').jcarousel({
        vertical: false,
        scroll: 1
    });
    $product.find('div.wrapper-product-top div.content div.wrapper-status-shop_options table tr').each(function(){
        if(numInc % 2) $(this).addClass('odd');
        else $(this).addClass('even');
        numInc++;
    });
    if($product.find('div.wrapper-product-top div.photos ul.additional_photos').html() != undefined){
        $product.addClass('isAdditionalPhotos');
    }
    if($contentMiddle.find('div.pagination').html() != undefined) $contentMiddle.addClass('isPagination');
    var browser = new Object();
    browser.name = '';
    var aditionalClass = '';
    $.browser.mozilla ?  browser.name = 'mozilla' : $.browser.msie ? browser.name = 'ie' : $.browser.opera ? browser.name = 'opera' : $.browser.safari ? browser.name = 'safari' : browser.name = 'unknown';
    aditionalClass = browser.name+' '+browser.name+'_version-'+$.browser.version+' ps';
    aditionalClass = aditionalClass.replace(/\./g, '-');
    $('body').addClass(aditionalClass).parent().attr('id','ps');
    $('#contentLeft div.menuBox_Promotions div.in ul.list_Menu_Promotions').cycle();
    $('#rotator').append('<div id="nav">').find('ul').cycle({pager : '#nav'});
	/**
	 * IEFix < 8
	 *
	 * dodaje clear div'a(<div class="clearFix"> </div>) po elemencie z clasa "clear"
	 */
	if( $.browser.msie == true && parseInt(jQuery.browser.version) < 8 )
	{

		try {
			$('.clear').each( function () {

				try {$(this).append('<div class="clearFix"> </div>');}
				catch(err)	{ }
			});
		}
		catch(err)	{ }
	}

	/**
	 * Automatycznie czyszczenie inputa z zapamientanym stanem podstawowym
	 */
	$('input.autoClearInput').each( function (k,e){
		$(e).attr('data-valuedefault', $(e).attr('value') );
		$(e).blur(function () {
			if( $(this).val() == undefined || $(this).val() == '' ) $(this).val( $(this).attr('data-valuedefault') );
		});

		$(e).focus( function () {
			if( $(this).val() == $(this).attr('data-valuedefault') ) $(this).val( '' );
		});
	});

	/**
	 * LightBox/PopUp bind
	 */

	if( typeof gallery_type != 'undefined' && gallery_type == 'lighbox' )
	{
		var lightboxArr = new Array()
		$('a[rel^=gallery]').each(function()
		{
			if( jQuery.inArray($(this).attr('rel'),lightboxArr) < 0 )
			{
				lightboxArr.push($(this).attr('rel'));
			}
		});

		$('a[rel^=gallery]').click(function () {return false;});

		$.each(lightboxArr,function(){
			$('a[rel^='+this+']').lightBox();
		});
	}
	else
	{
	    $('a[rel^=gallery]').click(function() {
			var link_zdj=$(this).attr('href');
			var i=0;
			$('a[rel^=gallery]').each(function()
			{
				if($(this).attr('href')==link_zdj) {
					return false;
				}else{
					i++;
				}
			});
			zdj = window.open('pokaz_zdjecie.php?id_prod='+product_id.toString()+'&img='+ i.toString() , 'Zdjęcie', 'screenY=0,screenX=0,left=0,top=0,width=200,height=200,status=no,scrollbars=yes,resizable=yes,menubar=no');
			zdj.focus();
			return false;
	    });
	}

	/**
	 * Cech wpywajace na modyfikacje ceny
	 */
	if( $('.show_product_options').length > 0 ) {
		change_prices();
		$('.show_product_options').change(function(){
			change_prices();
		});
	}

	/**
	 * Inicjalizacja modulu filtrow
	 */
	filters_init();

	/**
	 * Inicjalizacja "podpowiadacza" do szukaj
	 */
    $("input.autocomplete").each( function () {

		$(this).autocomplete('smartsearch.php', {
			minChars: 2,
			max: 50,
			width: $(this).width(),
			selectFirst: false
		} );
	});

	/**
	 * Inicjalizacja ToolTip'a
	 */
	ToolTip.init();


      /*sortowanie*/
      $('.sort_Manufactures ul').after('<span class="strzalka"><a> </a></span>');
      $('.strzalka a').click(function(){
          if($(".sort_Manufactures ul").css("display")=="block"){
            $('.sort_Manufactures ul').slideUp();
            $(this).removeClass("open");
          }
          else {
            $('.sort_Manufactures ul').slideDown();
            $(this).addClass("open");
          }
      });
     




});

var ToolTip = {

	text: '',
	toolTipOver: false,

	hide: function (obj) {
		obj.attr('title', ToolTip.text);
		$('#tooltip').css('display', 'none');
	},

	show: function (obj, e) {
		$('#tooltip2').css('display', 'block');
		ToolTip.text = obj.attr('title');
		if( ToolTip.text.length == 0 ) return;
		obj.attr('title', '');
		$('#tooltip2content').html(ToolTip.text);
		$('#tooltip2').css('display', 'block');

		$('#tooltip2').css('left', e.pageX - $('#tooltip2').get(0).offsetWidth - 5 + 'px');
		$('#tooltip2').css('top', e.pageY - $('#tooltip2').get(0).offsetHeight - 5 + 'px');
	},

	init: function() {
		$('.tt_rollover').hover(function(e) {
			var handle = $(this);
			$(this).css('cursor', 'default');
			ToolTip.show(handle, e);
		}, function() {
			ToolTip.hide($(this));
		});
	}
};

/**
 * Modyfikuje ceny na podstawie wybranych cech
 */
function change_prices() {

	var tmp_price_add=0;
	var tmp_price_set=0;

	jQuery('select.show_product_options option:selected').each( function(){

		str=jQuery(this).html().replace(/\s|&nbsp;/g,'').match(/\(.*\)/g)+'';

		if(str=='null') return;

		is_add=str.search(/\+/);
		str=str.match(/\d+\.?\d*/g)+'';
		number=parseFloat(str.replace(/,/g,'.'));

		if(number>0){
			if(is_add>0)
				tmp_price_add+=number;
			else
				tmp_price_set=number;

		}
	});

	//jeżeli ustawiono cene w cechach powiązanych
	if(tmp_price_set>0){

		//jezeli produkt ma cenę promocyjną
		if(prom_price>0) {
			vat_value=((show_product_tax*(tmp_price_set+tmp_price_add))/(show_product_tax+100)).toFixed(2);
			netto=(tmp_price_set+tmp_price_add-vat_value);
			netto=parseFloat(netto.toFixed(2));

			jQuery('#prom_price').html((tmp_price_set+tmp_price_add).toString().replace(/\./g,','));
			jQuery('#prom_price_net').html(netto.toString().replace(/\./g,','));
			jQuery('#prom_price_formated').html((tmp_price_set+tmp_price_add).number_format());
			jQuery('#prom_price_formated_net').html(netto.number_format());

		} else {

			vat_value=((show_product_tax*(tmp_price_set+tmp_price_add))/(show_product_tax+100)).toFixed(2);
			netto=(tmp_price_set+tmp_price_add-vat_value);
			netto=parseFloat(netto.toFixed(2));

			jQuery('#price').html((tmp_price_set+tmp_price_add).toString().replace(/\./g,','));
			jQuery('#price_net').html(netto.toString().replace(/\./g,','));
			jQuery('#price_formated').html((tmp_price_set+tmp_price_add).number_format());
			jQuery('#price_formated_net').html(netto.number_format());
		}

	} else if(tmp_price_set==0) {

		//jezeli produkt ma cenę promocyjną
		if(prom_price>0){

			vat_value=((show_product_tax*(prom_price+tmp_price_add))/(show_product_tax+100)).toFixed(2);
			netto=(prom_price+tmp_price_add-vat_value);
			netto=parseFloat(netto.toFixed(2));
			jQuery('#prom_price').html((prom_price+tmp_price_add).toString().replace(/\./g,','));
			jQuery('#prom_price_net').html(netto.toString().replace(/\./g,','));
			jQuery('#prom_price_formated').html((prom_price+tmp_price_add).number_format());
			jQuery('#prom_price_formated_net').html(netto.number_format());

		} else {

			vat_value=((show_product_tax*(price+tmp_price_add))/(show_product_tax+100)).toFixed(2);
			netto=(price+tmp_price_add-vat_value);
			netto=parseFloat(netto.toFixed(2));

			jQuery('#price').html((price+tmp_price_add).toString().replace(/\./g,','));
			jQuery('#price_net').html(netto.toString().replace(/\./g,','));
			jQuery('#price_formated').html((price+tmp_price_add).number_format());
			jQuery('#price_formated_net').html(netto.number_format());

		}
	}
}

/**
 * Obsluga filtrow
 */
function filters_init()
{
	$('div.filters div.filter_option div.option p span[rel]').click(function () {

		if( $( 'input[name="'+$(this).attr('rel')+'"]' ).attr('checked') == undefined ||
			$( 'input[name="'+$(this).attr('rel')+'"]' ).attr('checked') == false )
			$( 'input[name="'+$(this).attr('rel')+'"]' ).attr('checked', 'checked');

		$(this).parents('form').submit();
	});

	$('.showall').click( function () {

		var height_old = $(this).parent().parent().css('height');
		$(this).parent().parent().css('height', 'auto');

		$(this).css('display', 'none');
		$('.all[rel="'+$(this).attr('rel')+'"]' ).css('display', 'block');

		var height_new = $(this).parent().parent().height();

		$(this).parent().parent().css('height', height_old);
		$(this).parent().parent().animate( {
			height: height_new
		}, 200, 'linear' );

	});

	$('div.filters div.filter_option > div.label').click( function () {

		if( $(this).parent().hasClass('active') == true )
		{
			$(this).parent().find('div.option').animate( {
				height: 0
			}, 200, 'linear', function(){
				$(this).parent().removeClass('active');
				$(this).css('display', 'none');
			});
		}
		else
		{
			var div_option = $(this).parent().find('div.option');
			div_option.css('height', 'auto');
			var height = div_option.height();

			div_option.css('display', 'block');
			div_option.css('height', 0);
			$(this).parent().addClass('active');

			$(this).parent().find('div.option').animate( {
				height: height
			}, 200, 'linear', function(){
				$(this).parent().addClass('active');
			});
		}
	});
}


/************************************************ NEW JS WAVE ************************************************/

function ajaxCartAdd(pid) {
 $.getJSON('/cart_order_custom', function(data) {
  if(typeof data["cart"][pid] == 'undefined') {
   url = '/ajax-ac'+pid+'.html';
  } else {
   url = '/ajax-ac'+pid+'-'+(parseInt(data["cart"][pid]["count"])+1)+'.html';
  }
  console.log(url);
  $.getJSON(url, function(data) {
   //$("#HowMuchFree").html('<a href="/shopcart">Koszyk</a><br/>produktów: '+data["totalCartCounter"]+'<br/>'+round(data["totalCart"], 2)+' zł<br/>Do darmowej przesyłki<br/>pozostało '+data["toFreeShipVisual"]+' zł');
   alert('Produkt został dodany do koszyka<br/>Aktualnie w koszyku znajduje się '+data["cart"][pid]["count"]+data["cart"][pid]["unit"]+' tego produktu');
  });
 });



}

function ajaxStorageAdd(pid) {
 $.get('/index.php?zapisz_produkt='+pid, function(data) {
  alert('Produkt został dodany do przechowalni');
 });
}

function substr (str, start, len) {
    // Returns part of a string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/substr
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // +      revised by: Theriault
    // +      improved by: Brett Zamir (http://brett-zamir.me)
    // %    note 1: Handles rare Unicode characters if 'unicode.semantics' ini (PHP6) is set to 'on'
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: false
    // *       example 3: ini_set('unicode.semantics',  'on');
    // *       example 3: substr('a\uD801\uDC00', 0, -1);
    // *       returns 3: 'a'
    // *       example 4: ini_set('unicode.semantics',  'on');
    // *       example 4: substr('a\uD801\uDC00', 0, 2);
    // *       returns 4: 'a\uD801\uDC00'
    // *       example 5: ini_set('unicode.semantics',  'on');
    // *       example 5: substr('a\uD801\uDC00', -1, 1);
    // *       returns 5: '\uD801\uDC00'
    // *       example 6: ini_set('unicode.semantics',  'on');
    // *       example 6: substr('a\uD801\uDC00z\uD801\uDC00', -3, 2);
    // *       returns 6: '\uD801\uDC00z'
    // *       example 7: ini_set('unicode.semantics',  'on');
    // *       example 7: substr('a\uD801\uDC00z\uD801\uDC00', -3, -1)
    // *       returns 7: '\uD801\uDC00z'
    // Add: (?) Use unicode.runtime_encoding (e.g., with string wrapped in "binary" or "Binary" class) to
    // allow access of binary (see file_get_contents()) by: charCodeAt(x) & 0xFF (see https://developer.mozilla.org/En/Using_XMLHttpRequest ) or require conversion first?
    var i = 0,
        allBMP = true,
        es = 0,
        el = 0,
        se = 0,
        ret = '';
    str += '';
    var end = str.length;

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT
    switch ((this.php_js.ini['unicode.semantics'] && this.php_js.ini['unicode.semantics'].local_value.toLowerCase())) {
    case 'on':
        // Full-blown Unicode including non-Basic-Multilingual-Plane characters
        // strlen()
        for (i = 0; i < str.length; i++) {
            if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) {
                allBMP = false;
                break;
            }
        }

        if (!allBMP) {
            if (start < 0) {
                for (i = end - 1, es = (start += end); i >= es; i--) {
                    if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) {
                        start--;
                        es--;
                    }
                }
            } else {
                var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
                while ((surrogatePairs.exec(str)) != null) {
                    var li = surrogatePairs.lastIndex;
                    if (li - 2 < start) {
                        start++;
                    } else {
                        break;
                    }
                }
            }

            if (start >= end || start < 0) {
                return false;
            }
            if (len < 0) {
                for (i = end - 1, el = (end += len); i >= el; i--) {
                    if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) {
                        end--;
                        el--;
                    }
                }
                if (start > end) {
                    return false;
                }
                return str.slice(start, end);
            } else {
                se = start + len;
                for (i = start; i < se; i++) {
                    ret += str.charAt(i);
                    if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) {
                        se++; // Go one further, since one of the "characters" is part of a surrogate pair
                    }
                }
                return ret;
            }
            break;
        }
        // Fall-through
    case 'off':
        // assumes there are no non-BMP characters;
        //    if there may be such characters, then it is best to turn it on (critical in true XHTML/XML)
    default:
        if (start < 0) {
            start += end;
        }
        end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
        // PHP returns false if start does not fall within the string.
        // PHP returns false if the calculated end comes before the calculated start.
        // PHP returns an empty string if start and end are the same.
        // Otherwise, PHP returns the portion of the string from start to end.
        return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end);
    }
    return undefined; // Please Netbeans
}


function substr_count (haystack, needle, offset, length) {
    // Returns the number of times a substring occurs in the string  
    // 
    // version: 1102.614
    // discuss at: http://phpjs.org/functions/substr_count
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: substr_count('Kevin van Zonneveld', 'e');
    // *     returns 1: 3
    // *     example 2: substr_count('Kevin van Zonneveld', 'K', 1);
    // *     returns 2: 0
    // *     example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10);
    // *     returns 3: false
    var pos = 0,
        cnt = 0;
 
    haystack += '';
    needle += '';
    if (isNaN(offset)) {
        offset = 0;
    }
    if (isNaN(length)) {
        length = 0;
    }
    offset--;
 
    while ((offset = haystack.indexOf(needle, offset + 1)) != -1) {
        if (length > 0 && (offset + needle.length) > length) {
            return false;
        } else {
            cnt++;
        }
    }
 
    return cnt;
}

function round (value, precision, mode) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Onno Marsman
    // +      input by: Greenseed
    // +    revised by: T.Wild
    // +      input by: meo
    // +      input by: William
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Josep Sanz (http://www.ws3.es/)
    // +    revised by: Rafał Kukawski (http://blog.kukawski.pl/)
    // %        note 1: Great work. Ideas for improvement:
    // %        note 1:  - code more compliant with developer guidelines
    // %        note 1:  - for implementing PHP constant arguments look at
    // %        note 1:  the pathinfo() function, it offers the greatest
    // %        note 1:  flexibility & compatibility possible
    // *     example 1: round(1241757, -3);
    // *     returns 1: 1242000
    // *     example 2: round(3.6);
    // *     returns 2: 4
    // *     example 3: round(2.835, 2);
    // *     returns 3: 2.84
    // *     example 4: round(1.1749999999999, 2);
    // *     returns 4: 1.17
    // *     example 5: round(58551.799999999996, 2);
    // *     returns 5: 58551.8
    var m, f, isHalf, sgn; // helper variables
    precision |= 0; // making sure precision is integer
    m = Math.pow(10, precision);
    value *= m;
    sgn = (value > 0) | -(value < 0); // sign of the number
    isHalf = value % 1 === 0.5 * sgn;
    f = Math.floor(value);

    if (isHalf) {
        switch (mode) {
        case 'PHP_ROUND_HALF_DOWN':
            value = f + (sgn < 0); // rounds .5 toward zero
            break;
        case 'PHP_ROUND_HALF_EVEN':
            value = f + (f % 2 * sgn); // rouds .5 towards the next even integer
            break;
        case 'PHP_ROUND_HALF_ODD':
            value = f + !(f % 2); // rounds .5 towards the next odd integer
            break;
        default:
            value = f + (sgn > 0); // rounds .5 away from zero
        }
    }

    return (isHalf ? value : Math.round(value)) / m;
}
