/*
 * cStore
 */
 var chckbx;
var imgFalse = "/themes/new_red/img/chckoff.jpg";
var imgTrue = "/themes/new_red/img/chckon.jpg";

function initck() {
  replaceChecks();
}


function replaceChecks() {
	chckbx = document.getElementsByTagName('input');
	for(var g=0;g<chckbx.length;g++){
		if(chckbx[g].type=='checkbox'){
			var img = document.createElement('img');

			//check if the checkbox is checked
			if(chckbx[g].checked) {
			  img.src = imgTrue;
			} else {
			  img.src = imgFalse;
			}

			//set image ID and onclick action
			img.id = 'checkImage'+g;
			img.style.cursor='pointer';
			img.align='absmiddle';
			//set image
			img.counter=g;
			img.onclick = function(){
				var a=this.counter;


				  if(chckbx[a].checked) {
				      chckbx[a].checked = '';
				      document.getElementById('checkImage'+a).src=imgFalse;

				      //if(chckbx[a].id=="student_selection") {
					    //  document.getElementById('student_selection').checked='';
				      //}

				      if(chckbx[a].id=="radio_id2") {

							document.order_form['dane_klient[firma_wys]'].className='input_disabled';
							document.order_form['dane_klient[imie_wys]'].className='input_disabled';
							document.order_form['dane_klient[nazwisko_wys]'].className='input_disabled';
							document.order_form['dane_klient[adres_wys]'].className='input_disabled';
							document.order_form['dane_klient[miejscowosc_wys]'].className='input_disabled';
							document.order_form['dane_klient[kod_poczt_wys]'].className='input_disabled';
							document.order_form['dane_klient[kraj_wys]'].className='input_disabled';

							document.order_form['dane_klient[firma_wys]'].disabled = true;
							document.order_form['dane_klient[imie_wys]'].disabled = true;
							document.order_form['dane_klient[nazwisko_wys]'].disabled = true;
							document.order_form['dane_klient[adres_wys]'].disabled = true;
							document.order_form['dane_klient[miejscowosc_wys]'].disabled = true;
							document.order_form['dane_klient[kod_poczt_wys]'].disabled = true;
							document.order_form['dane_klient[kraj_wys]'].disabled = true;

							wpisuj(document.order_form);
						}else if(chckbx[a].id=="wrapper_check") {
							document.getElementById('wrapper_table').style.display = 'none';
							var lenn = document.order_details.opakowanie.length;
							for(var s=0;s<lenn;s++) {
								document.order_details.opakowanie[s].checked=false;
							};
						}
				  } else {
				      chckbx[a].checked = 'checked';
				      document.getElementById('checkImage'+a).src=imgTrue;

				      //if(chckbx[a].id=="student_selection") {
					    //  document.getElementById('student_selection').checked='checked';
				      //}

				      if(chckbx[a].id=="radio_id2") {
							document.order_form['dane_klient[firma_wys]'].className='input_normal';
							document.order_form['dane_klient[imie_wys]'].className='input_normal';
							document.order_form['dane_klient[nazwisko_wys]'].className='input_normal';
							document.order_form['dane_klient[adres_wys]'].className='input_normal';
							document.order_form['dane_klient[miejscowosc_wys]'].className='input_normal';
							document.order_form['dane_klient[kod_poczt_wys]'].className='input_normal';
							document.order_form['dane_klient[kraj_wys]'].className='input_normal';

							document.order_form['dane_klient[firma_wys]'].disabled = false;
							document.order_form['dane_klient[imie_wys]'].disabled = false;
							document.order_form['dane_klient[nazwisko_wys]'].disabled = false;
							document.order_form['dane_klient[adres_wys]'].disabled = false;
							document.order_form['dane_klient[miejscowosc_wys]'].disabled = false;
							document.order_form['dane_klient[kod_poczt_wys]'].disabled = false;
							document.order_form['dane_klient[kraj_wys]'].disabled = false;
				      }else if(chckbx[a].id=="wrapper_check") {
							document.getElementById('wrapper_table').style.display = 'block';
					}

				  }
			};

			//place image in front of the checkbox
			chckbx[g].parentNode.insertBefore(img, chckbx[g]);

			//hide the checkbox
			chckbx[g].style.display='none';
		}
	}
}

var catMenuActive = false;
$(document).ready(function () {



    $('body').css('display','block');
    Cufon.replace('#header ul.header.menu li h2 a', {hover: true});
    Cufon.replace('#header ul.header.menu li .mb_h123', {hover: true});
    Cufon.replace('div.menuBox h2 .mb_h123', {hover: true});
    Cufon.replace('span#motto');
    $('#header ul.header.menu li.help h2 a span').css('color','#000');
    $('.menuBox_Categories ul.menu li ul li a span').css('color','#fff');
    $('ul.header .hasChildren ul li a span').css('color','#fff');
    $('ul.header .help.hasChildren ul li a span').css('color','#000');
    $("#ajax_cart_sum").click(function(){
	    $(this).css("display","none");
    });

    $('li.118 a').addClass('over').addClass('118');
    $('li.118 span').addClass('over').addClass('118');

    $('li.155 a').addClass('over').addClass('155');
    $('li.155 span').addClass('over').addClass('155');

    msg = $('.pole_message_info');

    if(msg.length != 0) {
        $("select.show_product_options").css('border', '1px solid #FF6666');

        $("select.show_product_options").change(function() {
            if($(this).value != 0) {
                $(this).css('border', 'none');
            }
        });
    }

    if($.browser.msie == true) {
        $('.clear .txt').css('top','-157px');
    }

    $('li.noElement').parent().remove();

    //-- panel logowania

    $('#log .title_label').click(function() {

        if( ! $('#log .title_label').hasClass('title_label_open')) {
            $('#log .title_label').addClass('title_label_open');
            $('#log').css("overflow", "visible");
        } else {
            $('#log .title_label').removeClass('title_label_open');
            $('#log').css("overflow", "hidden");
        }

    });

    //--

    //-- krotki opis

    $('.description_link').hover(function() {
        $(this).next().show();

    }, function() {
        $(this).next().hide();
    });

    initck();

    //div mess
    var mt=(48-$("#mes_d").height())/2;
    if(mt>0){
	    $("#mes_d").css("margin-top",mt);
    }else{
	    $("#mes_d").css("margin-top","0");
    }
    //--

    //-- menu rozwijane po lewej


    $('.menuBox_Categories .menu li a').mouseover(function() {
       if (!$(this).hasClass('118') || !$(this).hasClass('155') )
            {

                $('.menuBox_Categories .menu li a').removeClass('over');
          
    
                $('.menuBox_Categories .menu li ul').css('display','none');
                $('.menuBox_Categories .menu li a span').removeClass('over');

                    $('li.118 a').addClass('over').addClass('118');
    $('li.118 span').addClass('over').addClass('118');

    $('li.155 a').addClass('over').addClass('155');
    $('li.155 span').addClass('over').addClass('155');
    
                $(this).addClass('over');
                if( $(this).next().length != 0 ) {
                    $(this).next().css('display','block');
                } else {
                    $($(this).children()[0]).addClass('over');
                }
            }
        catMenuActive = true;
    });

    $('.menuBox_Categories .menu li ul').mouseover(function() {
        $(this).prev().addClass('over');
        $(this).css('display','block');
        catMenuActive = true;
    });



    $('.menuBox_Categories .menu li ul').mouseout(function() {
        setTimeout("if(catMenuActive == false) {$('.menuBox_Categories .menu li a').removeClass('over'); $('.menuBox_Categories .menu li a span').removeClass('over'); $('.menuBox_Categories .menu li ul').css('display','none'); }", 500);

        catMenuActive = false;
    });


    $('.menuBox_Categories .menu li a').mouseout(function() {
        setTimeout("if(catMenuActive == false) {$('.menuBox_Categories .menu li a').removeClass('over');$('.menuBox_Categories .menu li a span').removeClass('over');$('.menuBox_Categories .menu li ul').css('display','none'); }", 500);
        setTimeout("if(catMenuActive == false) {$('li.118 a').addClass('over').addClass('118');$('li.118 span').addClass('over').addClass('118');  $('li.155 a').addClass('over').addClass('155');    $('li.155 span').addClass('over').addClass('155'); }", 501);

 
        catMenuActive = false;
    });


    //--

    //-- menu rozwijane gorne

    //-- podswietlenia gornego menu


    $(".header.menu li").mouseover(function() {
        if(!$(this).hasClass('hover2')) {
            $(this).addClass('hover2');

        }
    });

    $(".header.menu li").mouseout(function() {
        if($(this).hasClass('hover2')) {
            $(this).removeClass('hover2');



        }
    });

   $(".header.menu li").mouseover(function() {
       if($(this).hasClass('help')) {

        if(!$(this).hasClass('hover3')) {
             $(this).removeClass('hover2');
             $(this).removeClass('hover');
             $(this).addClass('hover3');
             var len = $('#header ul.header.menu li.help.hasChildren ul li').width() -95;

             $('#header ul.header.menu li.help.hasChildren ul').css('left','-' + len  + 'px');
             var wid = len+95;
             $('#header ul.header.menu li.help.hasChildren ul').css('width',wid  + 'px');

                }
    }
});

    $(".header.menu li").mouseout(function() {
         if($(this).hasClass('help')) {
        if($(this).hasClass('hover3')) {
             $(this).removeClass('hover2');
            $(this).removeClass('hover3');
        }
    }}
);

    $(".header.menu li.hasChildren").mouseover(function() {
        if(!$(this).hasClass('hover')) {
            $(this).removeClass('hover2');
            $(this).addClass('hover');
$(this).find("span.mb_h123").css('color','white');
    Cufon.refresh("#header ul.header.menu li .mb_h123");

        }
    });

    $(".header.menu li.hasChildren").mouseout(function() {
        if($(this).hasClass('hover')) {
            $(this).removeClass('hover2');
            $(this).removeClass('hover');
$(this).find("span.mb_h123").css('color','black');
    Cufon.refresh("#header ul.header.menu li .mb_h123");


        }
    });

    $('.header.menu li ul').mouseout(function() {
           // $(this).hide('slow');

    });



    //--

    //-- sortowania

    $('#sort_box_title').click(function() {
        if($(this).next().hasClass('sort_open')) {
            $(this).next().removeClass('sort_open');
        } else {
            $(this).next().addClass('sort_open');
        }
    });

    //--

    //-- koszyk

    $('#open_basket_top').click(function() {
        $(this).parent().css('display', 'none');
        $('#closed_basket').css('display', 'block');
    });

    $('#closed_basket').click(function(){
        $(this).css('display', 'none');
        $('#open_basket').css('display', 'block');
    });

    //--

    //-- Dodaj do koszyka

    $('.dokoszyka1').click(function(e) {
        e.preventDefault();

        var id = $(this).attr('id');
        var count = $(this).siblings('input').attr('value');
        $.ajax({
            dataType: 'text',
            type: 'post',
            url: '/shopcart',
            data: 'dodaj=' + id + '&ilosc=' + count,
            success: function(data) {
                $product = $.parseJSON(data);

                var product = $.parseJSON(data);

                if(product.redirect != undefined && product.redirect != '') {
                    document.location = product.redirect;
                } else {

                    if($('input#p-'+product.id).length == 0) {

                        var product_brutto = product.brutto.toFixed(2);
                        product_brutto = String(product_brutto);
                        product_brutto = product_brutto.replace('.',',');

                        var product_brutto_total = product.brutto.toFixed(2);
                        product_brutto_total = String(product_brutto_total);
                        product_brutto_total = product_brutto_total.replace('.',',');

                        $('.mini_controlls').before('<div class="mini_basket_product">' +
                            '<input type=hidden id=p-'+product.id+' name=pozycja['+product.id+'] value=1>' +
                            '<div class="prod_data">' +
                            'ilość <span>'+product.count+'</span> ' +
                            'cena jednostkowa <span>'+product_brutto+' zł</span> ' +
                            'wartość <span>'+product_brutto_total+' zł</span>' +
                            '</div>' +
                            '<div class="prod_name">'+ product.name +'</div>' +
                            '</div>' +
                            '<div class="separator"></div>');

                        var price = $('.mini_price').html();
                        price = price.substr(0, price.length - 3);
                        price = price.replace(',', '.');

                        price = parseFloat(price) + product.total_brutto;
                        price = price.toFixed(2);
                        price = String(price);
                        price = price.replace('.',',');

                        $('.mini_price').html(price +' zł');

                        var count = $('.mini_count').html();
                        count = parseInt(count) + product.count;
                        $('.mini_count').html(count);

                            //alert('Dodano produkt do koszyka');
                           //alert('Dodano produkt do koszyka');//ilość produktów w koszyku: <b>"+count+"</b><br />łączna wartość: <b>"+price+" zł</b>
                        $("#ajax_cart_sum").html("<span class=\"alignLeft\"><b>PRODUKT ZOSTAŁ DODANY DO KOSZYKA!<br /><br />Zachęcamy do dalszych zakupów!</b><br><span style='float:left'><a style=\"cursor:hand ;cursor:pointer; float:left;\" href=\"/shopcart\"><br><img src='themes/new_red/jogaimg/make_order.jpg' alt='Złóż zamówienie'/></a><span style='padding:28px 0 0 5px;float:left'><a href='/shopcart' style='color:black'> Przejdź do koszyka</span></a></span></span><div class='ajax_cart_sum_info'><span style='color:black;margin:10px'>Aby zamknąć to okienko</span> <span style='color:white'>kliknij tu</span></div>");
                        $("#ajax_cart_sum").css("display","block");
                    } else {
                        $("#ajax_cart_sum").html("<span class=\"alignLeft\"><b>PRODUKT JUŻ ZNAJDUJE SIĘ W KOSZYKU!</b><br /><br />Kliknij <a href=\"/shopcart\">tutaj</a>, aby zmienić ilość zamówionego towaru.</b></span><div class='ajax_cart_sum_info' style='margin:22px 0 0 80px'><span style='color:black;margin:10px'>Aby zamknąć to okienko</span> <span style='color:white'>kliknij tu</span></div>");
                        $("#ajax_cart_sum").css("display","block");
                    }
                }
            },
            error: function(result) {
                alert("ERROR: " + result.status + ' ' + result.statusText);
            }
        });
    });

    //--







    /**
	 * IEFix < 8
	 *
	 * dodaje clear div'a(<div class="clearFix"> </div>) po elemencie z clasa "clear"
	 */
    if( $.browser.msie == true && parseInt(jQuery.browser.version) < 8 )
    {
        $('.clear').after('<div class="clearFix"> </div>');
    }

    /**
	 * 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;
        });
    }
    else
    {
        $('a[rel^=gallery]').each(function()
        {
            var i = 0;

            $(this).click(function() {

                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;
            });

            i++;
        });
    }



    /**
	 * Cech wpywajace na modyfikacje ceny
	 */
    if( jQuery('.show_product_options').length > 0 ) {
        change_prices();
        jQuery('.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 toolTipp'a
	 */


    toolTipp.init();

    if($('.good_to_known').length > 0){
		var r1=$('.good_to_known').html();
	    $('.good_to_known').html(r1.replace("<p>",""));
	    var r1=$('.good_to_known').html();
	    $('.good_to_known').html(r1.replace("</p>",""));
    }

    if($('.learn_this').length > 0){
	    var r1=$('.learn_this').html();
	    $('.learn_this').html(r1.replace("<p>",""));
	    var r1=$('.learn_this').html();
	    $('.learn_this').html(r1.replace("</p>",""));
	}

	if($('.learn_more').length > 0){
	    $('.learn_more li').each( function(){
	        $(this).html($(this).html()+' &raquo;');
	    });
	}

    $('.cart').hover(function(){
	    $(this).parent('.btns').parent('.product_bottom').css('background-position','bottom left');
    },function(){
	    $(this).parent('.btns').parent('.product_bottom').css('background-position','top left');
    });

    jQuery.each(lightboxArr,function(){
        $('a[rel^='+this+']').lightBox();
    });


});

var toolTipp = {
    text: '',
    toolTippOver: false,

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

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

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

    init: function() {
        $('.tt_rollover').hover(function(e) {
            var handle = $(this);
            $(this).css('cursor', 'default');
            toolTipp.show(handle, e);
        }, function() {
            toolTipp.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('#price').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').html((tmp_price_set+tmp_price_add).toString().replace(/\./g,','));

		  jQuery('#price').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');
            });
        }
    });



	$("#myController-upper").jFlow({
		slides: "#slides-upper",
		controller: ".jFlowControl-upper", // must be class, use . sign
		slideWrapper : "#jFlowSlide-upper", // must be id, use # sign
		selectedWrapper: "jFlowSelected-upper",  // just pure text, no sign
		width: "681px",
		height: "188px",
		duration: 800,
		auto: true,
		direction: 'left',
		prev: ".jFlowPrev-upper", // must be class, use . sign
		next: ".jFlowNext-upper" // must be class, use . sign
	});

}
