WP.$(function ($) {

	// ukrycie list w lewej kolumnie
	//$('#stgCol300 .bx .roll').hide();

	// rozwiniecie list po kliku
	$('#stgCol300 .bx h2').click(function() {
		var roll = $(this).parent().find('.roll');

		if (roll.css('display') == 'none') {
			$(this).addClass('open');
		} else {
			$(this).removeClass('open');
		}

		roll.slideToggle();
	})
/*
	$('#stgCol300 .bx .subRoll .upDown').click(function() {
		var subRoll = $(this).parent().parent().parent().find('.subRoll');
		var cols = subRoll.find('.cols');

		if (cols.css('display') == 'none') {
			$(this).addClass('open');
		} else {
			$(this).removeClass('open');
		}

		cols.slideToggle();
	})
*/        
        $('#showBrand').bind('click', function(e) {

            $.ajax({
                  url: 'all-brand.html',
                  success: function(data) {

                    var compare = $('.tel').parent().find('#bxPorowTel').html();
                    $('.tel').parent().html(data);
                    $('.tel').parent().append('<div id="bxPorowTel" class="bx">'+compare+'</div>');

                    for (x in brand)
                    {
                        console.debug(x);
                        console.log($('input[name="'+x+'"]').prev().html());
                        $('input[name="'+x+'"]').prev().addClass('on');
                        $('input[name="'+x+'"]').val(brand[x]);
                    }

                    // producenci telefonow
                    $('.lsTelProd li').click(function() {
                        var span = $(this).find('span');
                        var hid = $(this).find('input');
                        
                        if (!hid.val() || hid.val() == "") {
                            hid.val(span.html());
                            span.addClass('on');
                            brand[hid.attr('name')] = hid.val();
                            
                        } else {
                            hid.val('');
                            span.removeClass('on');
                            delete brand[hid.attr('name')];
                        }
                    }) 
                    
                    $('.fldLnk .btn').click(function() {
                        runFilter();
                        return false;
                    }) 

                  },
                  error: function(jqXHR, textStatus, errorThrown) {
                      alert('Blad: '+textStatus);
                  },
                  complete: function() {

                  }
            });
        })

	$('.lsSys .inChk, .roll .inBtn2').click(function() {
		var type = $('#type').attr('value');

		var osId1 = 0, osId2 = 0, osId3 = 0;

		var sys_win = $('#sys_win');
		if (true == sys_win.attr('checked')) {
			osId1 = 1;
		}
		var sys_lin = $('#sys_lin');
		if (true == sys_lin.attr('checked')) {
			osId2 = 1;
		}
		var sys_mac = $('#sys_mac');
		if (true == sys_mac.attr('checked')) {
			osId3 = 1;
		}

		var subCatsId = '';
		var subplatforms = $('.roll input:checkbox[class^=inChk]:checked');
		subplatforms.each(function() {
			subCatsId += '&' + this.name + '=' + this.value;
		})

		if ('' != subCatsId) {
			window.location = '/programy.html?windows=' + osId1 + '&linux=' + osId2 + '&macOs=' + osId3 + '&type=' + type + subCatsId;
		} else {
			window.location = 'windows,' + osId1 + ',linux,' + osId2 + ',macOs,' + osId3 + ',type,' + type + ',programy.html';
		}
	})
        
	$('#bxKatProg li h3').click(function() {
		var roll = $(this).parent().find('.roll');

		if (roll.css('display') == 'none') {
			$(this).addClass('open');
		} else {
			$(this).removeClass('open');
		}

		roll.slideToggle();
	})

        $('.bxLayer .x').click(function() {
		$('.layer').fadeOut();
	})

	/*************** chmura ***************************/
        $('.lsTel .cloud').hide();
	
	$('.lsTel li .pic').mouseover(function() {
		var cloud = $(this).parent().parent().parent().find('.cloud');
		var liInd = $(this).parent().parent().parent().index();
		
		if (!(liInd % 4 - 3) || WP.isIE7) {
			cloud.addClass('left');
		}
		
		cloud.show();
		cloud.css('opacity', '0');
		cloud.animate({opacity: 1}, {queue: false});
	});
	
	$('.lsTel li .pic').mouseout(function() {
		var cloud = $(this).parent().parent().parent().find('.cloud');
		cloud.css('opacity', '1');
		cloud.animate({opacity: 0}, {queue: false});
		cloud.hide();
	});
        /*************************************************/
        
        /*************** galeria telefonu ****************/
        $('.lsPic .btnPic').click(function() {
            
            var image = $('.bigPic').find('img'),
                src = $(this).find('img').attr('alt'),
                title = $(this).find('img').attr('title');
            
            
            $('.lsPic').children().each(function(){
                $(this).removeAttr('class');
            });
            
            $(this).parent().attr('class', 'on');
            
           // image.css('opacity', '1');
          //  image.animate({opacity: 0}, {queue: false});
            image.fadeOut("slow");
            
            image.fadeOut(1000, function () {
              image.attr('src', src);
              image.attr('title', title);
              image.fadeIn("slow");
            });
            
	})
        /*************************************************/
        
        /**************** porownywarka *******************/
        
        // uruchomienie prezentacji porownania
	$('#bxPorowTel .btn').live('click', function(e) {
	
            var count = 0;
        
            // sprawdzamy ilosc telefonow do porownania
            $('.lsComp').children().each(function(){
                if('empty' != $(this).attr('class')) {
                    count++;
                }
            });
            
            // jezeli mniej niz 2 wychodzimy
            if(2 > count) {
                return false;
            }
            runCompare();
	})

        // zamkniecie porownywarki
        $('.bxLayer .x').click(function() {
		$('.layer').fadeOut();
                // wyczyszczenie htmla z wynikami porownywania
                $('.layer').html('');
	})
        
        // dodawanie w widoku pojedynczego telefonu
        $('#telPor').click(function() {
            
            // skok do boxu z porownywanymi telefonami
            var new_position = $('#bxPorowTel').offset();
            window.scrollTo(new_position.left,new_position.top);
            
            var urlTxt = getHref();
            var options = {};
            var button = $(this);

            options["_action"] = "AddMobileCompare";
            options["id"] = $(this).parent().find('.id').val();
            options["img"] = $(this).parent().find('.img').val();
            options["nazwa"] = $(this).parent().find('.nazwa').val();
                
            $('.lsComp').css({opacity: 0.5});
            $('.lsComp').prepend('<img id="imgProg" style="position: relative; right: 170px; top: 40px;" src="http://i.wp.pl/a/i/stg/opinie_1/ladowanie.gif" />');
                
            WP.$.post(urlTxt, options,
                   function(data) {
                       
                       var isSucces = '1';
                        if (isSucces == data) {

                            button.attr("disabled","disabled");

                            $('.lsComp').children().each(function() {
                    
                                if('empty' == $(this).attr('class'))  {
                                    $(this).removeAttr('class');
                                    $(this).html('<span class="x" title="usuń" id="del'+options["id"]+'"></span><br/>\n<img src="'+options["img"]+'" alt="" style="height: 75px;" class="pic">\n<h3>'+options["nazwa"]+'</h3>').fadeIn();
                                    return false;
                                }

                              });
                            
                        } else {
                            alert(data);
                        }
                   })
                   .success(function() {})
                   .error(function() {
                       
                      alert("Wystapil blad. Prosimy sprobowac ponownie za chwile.");

                    })
                   .complete(function() {
                       $('.lsComp').css({opacity: 1});
                       $('#imgProg').remove();
                   });

                return true;
            
	})
        
        // dodawanie w widoku z lista telefonow
        $('.compare .inChk2').live('click', function(e) {

            // skok do boxu z porownywanymi telefonami
            var new_position = $('#bxPorowTel').offset();
            window.scrollTo(new_position.left,new_position.top);

            if($(this).is(':checked')) {

                var urlTxt = getHref();
                var options = {};
                var check = $(this);

                options["_action"] = "AddMobileCompare";
                options["id"] = $(this).parent().attr('id');
                options["img"] = $(this).parent().parent().find('.content .pic').attr('src');
                options["nazwa"] = $(this).parent().parent().find('.content a').attr('title');

                $('.lsComp').css({opacity: 0.5});
                $('.lsComp').prepend('<img id="imgProg" style="position: relative; right: 170px; top: 40px;" src="http://i.wp.pl/a/i/stg/opinie_1/ladowanie.gif" />');

                WP.$.post(urlTxt, options,
                       function(data) {

                           var isSucces = '1';
                            if (isSucces == data) {

                                check.parent().parent().attr('class', 'blue');
                                //check.attr("disabled","disabled");
                                check.parent().find('label').text('usuń');

                                $('.lsComp').children().each(function() {

                                    if('empty' == $(this).attr('class'))  {
                                        $(this).removeAttr('class');
                                        $(this).html('<span class="x" title="usuń" id="del'+options["id"]+'"></span><br/>\n<img src="'+options["img"]+'" alt="" style="height: 75px;" class="pic">\n<h3>'+options["nazwa"]+'</h3>').fadeIn();
                                        return false;
                                    }

                                  });

                            } else {
                                alert(data);
                                return false;
                            }
                       })
                       .success(function() {})
                       .error(function() {

                            alert("Wystapil blad. Prosimy sprobowac ponownie za chwile.");

                        })
                       .complete(function() {
                           $('.lsComp').css({opacity: 1});
                           $('#imgProg').remove();
                       });

                    return true;
            } else {
                
                var el = $('#del'+$(this).parent().attr('id'));
                
                removeCompare($(this).parent().attr('id'), el);
            }
         
         });
         
         // usuwanie
         $('.lsComp .x').live('click', function(e) {
                
            var id = $(this).attr("id").substr(3,$(this).attr("id").length);
            removeCompare(id, $(this));
            
	})
        /*******************************************************************/
        
        /**************** Obsluga filtrowania telefonow *******************/
        
        // inicjujemy brand dla filtrowania
        var brand = {};
        // inicjujemy os dla filtrowania
        var os = new Array();
        // inicjujemy typ dla filtrowania
        var type = new Array();
        // inicjujemy query dla filtrowania
        var query = new Array();
        
        if(null !== $('#mobile')) {
            
            $('#bxProducentTel .inChk').each(function() {
                if($(this).is(':checked')) {
                    brand[$(this).attr('id')] = $(this).parent().find('label a').text();
                } 
            });
            
            $('#bxObudowaTel .inChk').each(function() {
                if($(this).is(':checked')) {
                    type[$(this).attr('id')] = $(this).parent().find('label a').text();
                } 
            });
            
            $('#bxSystemTel .inChk').each(function() {
                if($(this).is(':checked')) {
                    os[$(this).attr('id')] = $(this).parent().find('label a').text();
                } 
            });
            
            $('#bxMMediaTel .inChk').each(function() {
                if($(this).is(':checked')) {
                    query[$(this).attr('id')] = $(this).parent().find('label a').text();
                } 
            });
            
            $('#bxFDodatTel .inChk').each(function() {
                if($(this).is(':checked')) {
                    query[$(this).attr('id')] = $(this).parent().find('label a').text();
                } 
            });
        }
        
        // uruchamianie po checkboxie
        $('#bxProducentTel .content .inChk').bind('click', function(e) {
            if($(this).is(':checked')) {
                brand[$(this).attr('id')] = $(this).parent().find('label a').text();
                runFilter();
            } else {
                delete brand[$(this).attr('id')];
                runFilter();
            }
        });
        
        $('#bxObudowaTel .content .inChk').bind('click', function(e) {
            if($(this).is(':checked')) {
                type[$(this).attr('id')] = $(this).parent().find('label a').text();
                runFilter();
            } else {
                delete type[$(this).attr('id')];
                runFilter();
            }
        });
        
        $('#bxSystemTel .content .inChk').bind('click', function(e) {
            if($(this).is(':checked')) {
                os[$(this).attr('id')] = $(this).parent().find('label a').text();
                runFilter();
            } else {
                delete os[$(this).attr('id')];
                runFilter();
            }
        });
        
        $('#bxMMediaTel .content .inChk').bind('click', function(e) {
            if($(this).is(':checked')) {
                query[$(this).attr('id')] = $(this).parent().find('label a').text();
                runFilter();
            } else {
                delete query[$(this).attr('id')];
                runFilter();
            }
        });
        
        $('#bxFDodatTel .content .inChk').bind('click', function(e) {
            if($(this).is(':checked')) {
                query[$(this).attr('id')] = $(this).parent().find('label a').text();
                runFilter();
            } else {
                delete query[$(this).attr('id')];
                runFilter();
            }
        });
        
        // uruchamianie po href
        $('#bxProducentTel .content label a ').bind('click', function(e) {
 
            var check = $(this).parent().parent().find('.inChk');

            if(!check.is(':checked')) {
                check.attr('checked', true);
                brand[check.attr('id')] = check.parent().find('label a').text();
                runFilter();
            } else {
                check.attr('checked', false);
                delete brand[check.attr('id')];
                runFilter();
            }
            return false;
        });
        
        $('#bxObudowaTel .content label a ').bind('click', function(e) {
 
            var check = $(this).parent().parent().find('.inChk');

            if(!check.is(':checked')) {
                check.attr('checked', true);
                type[check.attr('id')] = check.parent().find('label a').text();
                runFilter();
            } else {
                check.attr('checked', false);
                delete type[check.attr('id')];
                runFilter();
            }
            return false;
        });
        
        $('#bxSystemTel .content label a ').bind('click', function(e) {
 
            var check = $(this).parent().parent().find('.inChk');

            if(!check.is(':checked')) {
                check.attr('checked', true);
                os[check.attr('id')] = check.parent().find('label a').text();
                runFilter();
            } else {
                check.attr('checked', false);
                delete os[check.attr('id')];
                runFilter();
            }
            return false;
        });
        
        $('#bxMMediaTel .content label a ').bind('click', function(e) {
 
            var check = $(this).parent().parent().find('.inChk');

            if(!check.is(':checked')) {
                check.attr('checked', true);
                query[check.attr('id')] = check.parent().find('label a').text();
                runFilter();
            } else {
                check.attr('checked', false);
                delete query[check.attr('id')];
                runFilter();
            }
            return false;
        });
        
        $('#bxFDodatTel .content label a ').bind('click', function(e) {
 
            var check = $(this).parent().parent().find('.inChk');

            if(!check.is(':checked')) {
                check.attr('checked', true);
                query[check.attr('id')] = check.parent().find('label a').text();
                runFilter();
            } else {
                check.attr('checked', false);
                delete query[check.attr('id')];
                runFilter();
            }
            return false;
        });
        /*********** koniec filtrowania telefonow ****************/
        
        /****************** Ocena internautow ********************/
        
        // box z selectami
        $('#bxOcenTel #marka').change(function() {
                
            var model = $('#bxOcenTel #marka option:selected').val();    
                
            $.getJSON('/modelbybrand.json', {brandId: model}, function(data) {
              var items = [];

              $.each(data, function(key, val) {
                items.push('<option value="' + key + '">' + val + '</option>');
              });

              $('#bxOcenTel #model').html(items.join(''));
              
              $('.fldLnk .inBtn2').attr('disabled', false)

            });
        });
        
	// pozycja na gwiazdkach w procentach
	var cXPPos = function(e) {
		
		var x = e.pageX - WP.$(e.target).offset().left;
		var imgX = WP.$(e.target).width();
		var pX = Math.floor(x / imgX * 100);
		
		return pX;
	}

	// nad gwiazdkami
	$('#bxOcena .stars').mousemove(function(e) {
		
            // jesli glosowano wczesniej
            var voted = parseInt($(this).parent().find('.voted').val());
            if (voted == 1) {
                    $(this).unbind();
                    return;
            }

            // procentowa wartosc kursora
            var pX = cXPPos(e);

            // gwiazdki
            var gN = 0;
            // ktore zapalamy
            if (10 > pX) {gN = 1;}
            else if (10 <= pX && pX < 20 ) {gN = 2;}
            else if (20 <= pX && pX < 30 ) {gN = 3;}
            else if (30 <= pX && pX < 40 ) {gN = 4;}
            else if (40 <= pX && pX < 50 ) {gN = 5;}
            else if (50 <= pX && pX < 60 ) {gN = 6;}
            else if (60 <= pX && pX < 70 ) {gN = 7;}
            else if (70 <= pX && pX < 80 ) {gN = 8;}
            else if (80 <= pX && pX < 90 ) {gN = 9;}
            else if (90 <= pX) {gN = 10;}

            $(this).attr('class', 'stars g'+ gN);

            window.gN = gN;
	});
	
	// po zjechaniu
	$('#bxOcena .stars').bind('mouseout', function(e) {
            var aktOcena = $(this).parent().find('.aktOcena').val();
            $(this).attr('class', 'stars g'+ aktOcena);
	});
	
	// na klika
	$('#bxOcena .stars').bind('click', function(e) {
		
            $(this).attr('class', 'stars g'+ gN); // zostawiamy gwiazdki
            $(this).unbind(); // wylaczomy glosowanie akcje na gwiazdkach
            $(this).parent().find('.ocena').val(gN); // zapisujemy w inpucie wartosc

            //var ind = $(this).parent().index();
            //$.post('test.php', {num: ind, val: gN});

            var urlTxt = getHref();

            var options = {};

            options["_action"] = "RatePhone";
            options["rate"] = gN;
            options["phoneId"] = $(this).parent().find('.phoneId').val();
            options["code"] = $(this).parent().find('.code').val();

            WP.$.post(urlTxt, options,
               function(data) {

                   var isSucces = '1';
                    if (isSucces == data) {

                        //alert('Glosowanie zakonczone powodzeniem.');

                    } else {

                        alert('Pojawily sie bledy: ' + data);
                        return false;
                    }
               })
               .success(function() {})
               .error(function() {
                    alert("Wystapil blad.");
                    return false;
                })
               .complete(function() {});


            // wyliczenie oceny ogolnej
            var res = $(this).parent().parent().parent();
            var liczbaUserow = parseInt(res.find('.liczbaUserow').val());
            var liczbaAtr = 7;
            var sredniaOcena = parseFloat(res.find('.sredniaOcena').val());

            var liczbaOcen = parseInt(res.find('input.liczbaOcen').val());
            if (liczbaOcen == 0) {
                    liczbaOcen = liczbaUserow * liczbaAtr;
            }

            var sumaOcen = parseInt(res.find('.sumaOcen').val());
            if (sumaOcen == 0) {
                    sumaOcen = sredniaOcena * liczbaOcen;
            }

            // nowe wartosci
            sumaOcen += gN;
            liczbaOcen += 1;
            // wstawiamy
            res.find('.sumaOcen').val(sumaOcen);
            res.find('.liczbaOcen').val(liczbaOcen);

            var nSrOcena = Math.floor(sumaOcen / liczbaOcen);

            res.find('.starsSum').attr('class', 'starsSum g'+ nSrOcena);
	});
        
        /**********************************************************************/

        // producenci telefonow
        $('.lsTelProd li').click(function() {
            var span = $(this).find('span');
            var hid = $(this).find('input');
            if (!hid.val() || hid.val() == "") {
                hid.val(span.html());
                span.addClass('on');
            } else {
                hid.val('');
                span.removeClass('on');
            }
        }) 

	/** glosowanie na program **/
	// nad gwiazdkami
	/*$('.lsProg .stars').mousemove(function(e) {

            // jesli glosowano wczesniej
            var voted = parseInt($(this).parent().find('.voted').val());
            if (voted == 1) {
                    $(this).unbind();
                    return;
            }

            // procentowa wartosc kursora
            var pX = cXPPos(e);

            // gwiazdki
            var gN = 0;
            // ktore zapalamy
            if (10 > pX) { gN = 1; }
            else if (10 <= pX && pX < 20 ) { gN = 1; }
            else if (20 <= pX && pX < 30 ) { gN = 2; }
            else if (30 <= pX && pX < 40 ) { gN = 2; }
            else if (40 <= pX && pX < 50 ) { gN = 3; }
            else if (50 <= pX && pX < 60 ) { gN = 3; }
            else if (60 <= pX && pX < 70 ) { gN = 4; }
            else if (70 <= pX && pX < 80 ) { gN = 4; }
            else if (80 <= pX && pX < 90 ) { gN = 5; }
            else if (90 <= pX) { gN = 5; }

            $(this).attr('class', 'stars g'+ gN);

            window.gN2 = gN;
	});

	// po zjechaniu
	$('.lsProg .stars').bind('mouseout', function(e) {
            var note = $(this).parent().find('.aktOcena').attr("id");
			var tab = note.split('_');
			var aktOcena = tab[1];
            $(this).attr('class', 'stars g'+ aktOcena);
	});

	// na klika
	$('.lsProg .stars').bind('click', function(e) {

		$(this).attr('class', 'stars g'+ gN2); // zostawiamy gwiazdki
		$(this).unbind(); // wylaczomy glosowanie akcje na gwiazdkach
		$(this).parent().find('.ocena').val(gN2); // zapisujemy w inpucie wartosc

		var str = this.id;
		var tab = str.split('_');
		//alert(tab[1]);
		var fileId = tab[1];

		var options = {};
		options["_action"] = "stampRateProgram";
		options["rate"] = gN2;
		options["entry"] = fileId;

		WP.$.post('programy.html', options,
			function(data) {}
		);

		// wyliczenie oceny ogolnej
		var res = $(this).parent().parent().parent();
		var liczbaUserow = parseInt(res.find('.liczbaUserow').val());
		var liczbaAtr = 7;
		var sredniaOcena = parseFloat(res.find('.sredniaOcena').val());

		var liczbaOcen = parseInt(res.find('input.liczbaOcen').val());
		if (liczbaOcen == 0) {
			liczbaOcen = liczbaUserow * liczbaAtr;
		}

		var sumaOcen = parseInt(res.find('.sumaOcen').val());
		if (sumaOcen == 0) {
			sumaOcen = sredniaOcena * liczbaOcen;
		}

		// nowe wartosci
		sumaOcen += gN2;
		liczbaOcen += 1;
		// wstawiamy
		res.find('.sumaOcen').val(sumaOcen);
		res.find('.liczbaOcen').val(liczbaOcen);

		var nSrOcena = Math.floor(sumaOcen / liczbaOcen);

		res.find('.starsSum').attr('class', 'starsSum g'+ nSrOcena);

	});*/
        
   /************* pojedynek *************/
   
    $('.pojedBar').hide();

    $('.pojedDsc .btn').click(function() {
        var id_image =  $(this).attr('id');
        runDuel(id_image);
    });

    $('.picLft a').click(function() {
        if (window.voted) {
            return false;
        }
        var id_image = $(this).attr('id').slice(3);
        runDuel(id_image);
        window.voted = true;
    });
    
    $('.picRgh a').click(function() {
        if (window.voted) {
            return false;
        }
        var id_image = $(this).attr('id').slice(3);
        runDuel(id_image);
        window.voted = true;
    });

    duelRank = function(lim, inBar) {

        lim = parseInt(lim);

        if (lim < 0) {
            lim = 0;
        }

        if (lim > 100) {
            lim = 100;
        }

        // ktory pasek animujemy
        var barBright;
        var barDark;

        if (inBar) {
            barBright = '.pojedBar .valLft';
            barDark = '.pojedBar .valInLft';
        } else {
            barBright = '.pojedBar .valRgh';
            barDark = '.pojedBar .valInRgh';
        }

        // wartosc domyslna/startowa
        var htmlVal = parseInt($(barBright).html());
        /*if (!htmlVal) {
                htmlVal = 50;
        }*/

        if (lim > 50) {
            // koniec
            if (htmlVal >= lim) {
                    return;
            }

            htmlVal += 1;
        } else {
            // koniec
            if (htmlVal <= lim) {
                    return;
            }

            htmlVal -= 1;
        }

        $(barBright).html(htmlVal +'%');
        $(barDark).html(htmlVal +'%');

        setTimeout('duelRank('+ lim +', '+ inBar +')', 25);
    };

    if (window.voted) {

            $('.pojedBar').show();
            $('.pojedDsc .btn').hide();
    }
    
    function runDuel(id_image) {
        $('.pojedBar').slideDown();
        $('.pojedDsc .btn').slideUp();

        var urlTxt = getHref();
        var needle = '/';
        var pos = urlTxt.lastIndexOf(needle);
        var newUrlTxt = urlTxt.substr(0, pos + 1) + '_action,inccount,idImage,'+id_image +','+ urlTxt.substr(pos + 1);

        $.ajax({
            type: 'GET',
            url: newUrlTxt,
            cache: false,
            error: function(jqXHR, textStatus, errorThrown){
                console.log('ajax error: '+errorThrown);
            },
            timeout: function(){
                console.log('ajax: timeout');
            },
            success: function(val){

                console.log(val);

                val = parseInt($.trim(val));

                if(val > 0) {

                    var dif = 100 - val;
                    console.log(dif);
                    $('.pojedBar .in').animate({width: val +'%'}, 1000);

                    duelRank(val, true);
                    duelRank(dif, false);
                } else {
                    console.log(val);
                    return false;
                }
            }
        });
    }
    
    /****************************************/

    function removeCompare(id, check) {
        
        var urlTxt = getHref();
        var needle = '/';
        var pos = urlTxt.lastIndexOf(needle);
        var newUrlTxt = urlTxt.substr(0, pos + 1) + '_action,RemoveMobileCompare,id,' + id + ',' + urlTxt.substr(pos + 1);
       // var check = $(this);

        // rozpoczyna rzadanie ajaxowe
        $('.lsComp').css({opacity: 0.5});
        $('.lsComp').prepend('<img id="imgProg" style="position: relative; right: 170px; top: 40px;" src="http://i.wp.pl/a/i/stg/opinie_1/ladowanie.gif" />');

        WP.$.get(newUrlTxt, function(data) {
            var isSucces = '1';
            if (isSucces == data) {

                    check.parent().attr('class','empty');
                    check.parent().html('<img class="pic" alt="" src="i/empty.gif">\n<h3>Dodaj produkt</h3>');

                    $('#'+id).parent().removeAttr("class");
                    $('#'+id).find('label').text('porównaj');
                    $('#'+id).find('.inChk2').removeAttr("checked");

                    var nextObj;
                    $('.lsComp li').each(function() {

                            if('empty' == $(this).attr('class') && '' == $(this).next().attr('class'))  {
                                nextObj = $(this).next();
                                $(this).removeAttr('class');
                                $(this).html(nextObj.html());
                                nextObj.attr('class','empty');
                                nextObj.html('<img class="pic" alt="" src="i/empty.gif">\n<h3>Dodaj produkt</h3>');
                            }                                
                    });

            } else {
                    alert('Pojawily sie bledy: ' + data);
            }
        })
        .success(function(){ })
        .error(function(){alert('Wystapil blad. Prosimy sprobowac ponownie za chwile.');})
        .complete(function(){
            $('.lsComp').css({opacity: 1});
            $('#imgProg').remove();
        });

        e.preventDefault();
        return false;
        
    }

    function runFilter() {
        
        if(null == brand && null == type & null == os & null == query) {
            return false;
        }
                
        var brandAll = '';
        var typeAll = '';
        var osAll = '';
        var queryAll = '';

        var options = {};

        if(null !== brand) {
            i=0;
            for (var word in brand) {
                if(i>0)
                    brandAll += ", ";

                brandAll += brand[word];
                i++;
            }
            options["brand"] = brandAll;
        }
        
        if(null !== type) {
            i=0;
            for (var word in type) {
                if(i>0)
                    typeAll += ", ";
                
                // zamiana whitespace na -
                var typeStr = type[word].replace(" ", "-");
                
                typeAll += typeStr;
                i++;
            }
            options["type"] = typeAll;
        }
        
        if(null !== os) {
            i=0;
            for (var word in os) {
                if(i>0)
                    osAll += ", ";
                
                osAll += os[word];
                i++;
            }
            options["os"] = osAll;
        }
        
        if(null !== query) {
            i=0;
            for (var word in query) {
                if(i>0)
                    queryAll += ", ";
                
                // zamiana whitespace na -
                var queryStr = query[word].replace(" ", "-");
                
                queryAll += queryStr;
                i++;
            }
            options["other"] = queryAll;
        }

        $(".tel").ajaxStart(function() {
            $(".tel").css({opacity: 0.5});
            $(".tel").prepend('<img id="imgProg" style="position: relative; right: -310px; top: 370px;" src="http://i.wp.pl/a/i/stg/opinie_1/ladowanie.gif" />');
        }).ajaxStop(function() {
            $(".tel").css({opacity: 1});
            $('#imgProg').remove();
        });

        $.ajax({
          url: 'filter-mobile.html',
          data: options,
          success: function(data) {

            var compare = $('.tel').parent().find('#bxPorowTel').html();
            $('.tel').parent().html(data);
            $('.tel').parent().append('<div id="bxPorowTel" class="bx">'+compare+'</div>');

            /*************** chmura ***************************/
            $('.lsTel .cloud').hide();
	
            $('.lsTel li .pic').mouseover(function() {
                    var cloud = $(this).parent().parent().parent().find('.cloud');
                    var liInd = $(this).parent().parent().parent().index();

                    if (!(liInd % 4 - 3) || WP.isIE7) {
                            cloud.addClass('left');
                    }

                    cloud.show();
                    cloud.css('opacity', '0');
                    cloud.animate({opacity: 1}, {queue: false});
            });

            $('.lsTel li .pic').mouseout(function() {
                    var cloud = $(this).parent().parent().parent().find('.cloud');
                    cloud.css('opacity', '1');
                    cloud.animate({opacity: 0}, {queue: false});
                    cloud.hide();
            });
            /*************************************************/

          },
          error: function(jqXHR, textStatus, errorThrown) {
              alert('Blad: '+textStatus);
          },
          complete: function() {
              
          }
        });
        
        return false;
    }
    
    function runCompare() {

        $.ajax({
          url: 'compare-mobile.html',
          success: function(data) {

            $('.layer').html(data);

            // przygotowanie tla
            var bodyHeight = document.body.offsetHeight;
           // $('.layer').css('height', bodyHeight);
            $('.layer').fadeIn();

            // przygotowanie boxa do prezentacji
            var winWidth = WP.window.width();
            var bxWidth = $('.bxLayer').width();

            var wDif = winWidth - bxWidth;

            if (wDif > 10) {
                    var mLeft = Math.floor(wDif / 2);
            } else {
                    var mLeft = 5;
            }

            $('.bxLayer').css('margin-left', mLeft + 'px');

            var winHeight = WP.window.height();
            var bxHeight = $('.bxLayer').height();

            // rozmiar layerka
            if (bodyHeight > bxHeight) {
                    $('.layer').css('height', bodyHeight);
            }

            var hDif = winHeight - bxHeight;

            if (hDif > 10) {
                    var mTop = Math.floor(hDif / 2);
            } else {
                    var mTop = 5;
                    $('.bxLayer').css('position', 'relative');			
            }

            $('.bxLayer').css('margin-top', mTop + 'px');

            //do wyzucenia po zrobieniu ruznic
            $('.bxLayer .x').click(function() {
                $('.layer').fadeOut();
            })
            
            var history = $('.tablComp').html();
            
            // pokaz tylko roznice
            $('.fldPTR .inChk').click(function() {

                var next = '';
                
                if($(this).is(':checked')) {
                    
                    $('.tablComp tr').each(function() {
                    
                    var i = 0;
                    var elem = [];
                    
                    $(this).children('.data').each(function() {
                        
                        if($(this).text() != '') {
                            elem[i] = $(this).text();
                        }
                        
                        i++;
                    });
                    
                    if (elem.length > 1) {
                        var filtr = $.unique(elem);
                        if(1 == filtr.length) {
                            $(this).remove();
                        }
                    }
                  });
                    
                } else {
                    $('.tablComp').html(history);
                }
                
            })
            
          },
          error: function(jqXHR, textStatus, errorThrown) {
              alert('Blad: '+textStatus);
          },
          complete: function() {
              
          }
        });
    }
});
	
function increaseDownCount(id) {

	var str = 'pobierz.html?_action=increaseDownCount&id=' + id;

	WP.$.ajax({
		url: str,       
		async: false,
		success: function(data) {
		}
	});
}	

function getHref() {
     if (0 < document.location.href.lastIndexOf('#')) {
     return document.location.href.substr(0,document.location.href.lastIndexOf('#'));
     }
     return document.location.href;
}

function search() {
	var divInfo = $('hint');
	var query = $('query').value;
	divInfo.style.display = 'block';

	if (0 < query.length) {
		var str = 'szukaj_ajax.html?query=' + query;

		WP.$.get(str, function(data) {
			divInfo.innerHTML = data;
		});
	}
}

function changeClass(id, className) {
	if (!id || !className) return false;
	$(id).className = className;
	return true;
}

licz=0;
function otworz(nazwa,szer,wys) {
	config='left=100,top=100,width='+szer+',height='+wys+',innerheight='+wys+',innerwidth='+szer+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no';
	kitekSC='okno' + licz;
	stadion=window.open('',kitekSC,config)
	stadion.document.write('<HTML><HEAD>');
	stadion.document.write('<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2">');
	stadion.document.write('<TITLE>Wirtualna Polska - Foto-Galeria</title>');
	stadion.document.write('<script language="javascript">');
	stadion.document.write('setTimeout(');
	stadion.document.write('"self.close()');
	stadion.document.write(';",70000)');stadion.document.write('</');
	stadion.document.write('script>');
	stadion.document.write('</HEAD>');
	stadion.document.write('<body bgcolor=white leftmargin=0 topmargin=0 marginheight=0 marginwidth=0>');
	stadion.document.write('<DIV align=center><a href=# onclick="javascript:self.close();"><img src='+nazwa+' border=0></A></DIV>');
	stadion.document.write('</body></html>');
	stadion.focus();
	licz+=1;
}

