﻿/*global $*/
/*global gapi,window*/
/*jQuery*/

//http://stackoverflow.com/questions/8746882/jquery-contain-uppercase-and-lower-case-issue
$.expr[':'].icontains = function(obj, index, meta, stack) {
    return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
};

// ???
$.fn.slideShow = function(timeOut) {
    var $elem = this;

    if($elem.children().length > 1) {
        this.children(':gt(0)').hide();
        $.data($elem, 'slide', true);
        this.hover(function() {
            $.data($elem, 'slide', false);
        }, function() {
            $.data($elem, 'slide', true);
        });
        setInterval(function() {
            if($.data($elem, 'slide') === true) {
                $elem.children().eq(0).stop(true, true).fadeOut().next().fadeIn().end().appendTo($elem);
            }

        }, timeOut || 5000);
    }
};

//http://www.wduffy.co.uk/jScroll/
(function ($) {
      function location(d) {
      this.min = d.offset().top;
      this.originalMargin = parseInt(d.css("margin-top"), 10) || 0;
      this.getMargin = function (a) {
        var b = d.parent().height() - d.outerHeight();
        var c = this.originalMargin;
        if (a.scrollTop() >= this.min) 
            {c = c + f.top + a.scrollTop() - this.min;}
        if (c > b) {c = b;}
        return ({
          "marginTop": c + 'px'
        });
      };
    }
    
  $.fn.jScroll = function (e) {
    var f = $.extend({}, $.fn.jScroll.defaults, e);
    return this.each(function () {
      var a = $(this);
      var b = $(window);
      var c = new location(a);
      b.scroll(function () {
        a.stop().animate(c.getMargin(b), f.speed);
      });
    });

  };
  $.fn.jScroll.defaults = {
    speed: "slow",
    top: 10
  };
})(jQuery);

function CancelEnter(evt) {
    if(!$(evt.target).attr('allow_enter')) {
        var c = document.layers ? evt.which : document.all ? evt.keyCode : evt.keyCode;
        if(c == 13) {
            evt.returnValue = false;
            evt.cancel = true;
            if(!document.all) {
                evt.preventDefault();
                evt.stopPropagation();
            }
        }
    }
}

function AllowEnter(evt) {
    $(evt.target).attr('allow_enter', true);
}

function fnTrapKD(btn, evt) {
    var c = document.layers ? evt.which : document.all ? event.keyCode : evt.keyCode;
    if(c == 13) {
        $("#" + btn).focus().click();
        return false;
    }
    return true;
}

function ShowMoreRows(table, numShown, text) {
    var numRows = $('#' + table).find('tr').length;
    if(numRows > numShown) {
        $('#' + table).find('tr:gt(' + (numShown - 1) + ')').hide().end().after('<div id="' + table + 'more" style="margin:auto;padding:1em;text-align:center;background-color:rgb(229, 114, 23);color:#fff;cursor:pointer;font-weight:bold;border:1px solid silver;border-top:none;">' + text + '</div>');
        $('#' + table + 'more').click(function() {
            $('#' + table).find('tr').slideDown('slow');
            $('#' + table + 'more').remove();
        });
    }

}

function ScrollToTop() {
    var scrollElement = 'html, body';
    $('html, body').each(function() {
        var initScrollTop = $(this).attr('scrollTop');
        $(this).attr('scrollTop', initScrollTop + 1);
        if($(this).attr('scrollTop') == initScrollTop + 1) {
            scrollElement = this.nodeName.toLowerCase();
            $(this).attr('scrollTop', initScrollTop);
            return false;
        }
    });
    $(scrollElement).animate({
        scrollTop : '0px'
    }, 'slow');
    return false;
}

function objectToString(o) {
    var parse = function(_o) {
        var a = [], t;
        for(var p in _o) {
            if(_o.hasOwnProperty(p)) {
                t = _o[p];
                if(t && typeof t == "object") {
                    a[a.length] = p + ":{ " + arguments.callee(t).join(", ") + "}";
                } else {
                    if( typeof t == "string" && t !== null) {

                        a[a.length] = [p + ": \"" + t.toString() + "\""];
                    } else {
                        if(t !== null)
                            {a[a.length] = [p + ": " + t.toString()];}
                    }
                }
            }
        }
        return a;
    };
    return "{" + parse(o).join(", ") + "}";
}

/*
 function __ic_add_script(d, s, id, src) {
 var js, fjs = d.getElementsByTagName(s)[0];
 if(d.getElementById(id)) {
 return;
 }
 js = d.createElement(s);
 if(id != '')
 js.id = id;
 js.src = src;
 js.async = true;
 fjs.parentNode.insertBefore(js, fjs);
 }

 //webpanel
 function __ic_reg_wp() {
 $(document).ready(function() {

 });
 }*/

var __ic = {
    lang : 'pl-PL',
    social_media : false,
    init : function() {

        $.facebox.settings.closeImage2 = '/img/facebox/closelabel.png';
        if(__ic.lang == 'pl-PL') {
            $.facebox.settings.close_image = '/img/buttons/pl/zamknij.png';
        } else {
            $.facebox.settings.close_image = '/img/buttons/eng/close.png';
        }
        $.facebox.settings.loading_image = '/img/facebox/loading.gif';
        //trzeba zrobic hook na eventa
        //$("body").attr("onkeydown","CancelEnter(event)").attr("onkeypress","CancelEnter(event)")
        $(window).load(function() {
            // cancel enter  onkeydown="CancelEnter(event)" onkeypress="CancelEnter(event)"
            // $("body").bind('onkeydown',function(event) {CancelEnter(event)});
          //   $("body").bind('onkeypress',function(event) {CancelEnter(event)});
            // menu
            __ic.menu.init();
            // panele
            __ic.webpanels.init();
/*$(document).ready(function($){$('#ctl00_Search_Search').tooltip({bodyHandler: function(){return $("#TT").html();},showURL: false,autohide: 6000});});*/            $('.pnlCnt input.SearchTextBox').tooltip({bodyHandler: function(){return $("#TT").html();},showURL: false,autohide: 6000});
            // social media
            var social = true;
            if($.browser.msie && $.browser.version < 8) {
                social = false;
            }
            if(__ic.social_media && social) {

                window.___gcfg = {
                    lang : __ic.lang
                };
                $('.g-plusone').attr('size', 'tall').attr('href', 'http://www.infocredit-online.pl').attr('annotation', 'inline').attr('width', '120');
                $.getScript('https://apis.google.com/js/plusone.js', function() {
                    gapi.plusone.render('plusone-div', {
                        "size" : "tall",
                        "href" : "http://www.infocredit-online.pl",
                        "annotation" : "inline",
                        "width" : "120"
                    });
                });

                $('.fb-like').attr('data-href', 'http://www.facebook.com/pages/InfoCredit/183153935035825').attr('data-send', 'false').attr('data-layout', 'button_count').attr('data-width', '120').attr('data-show-faces', 'false').attr('data-action', 'recommend').attr('data-font', 'verdana');
                //__ic_add_script(document, 'script', 'facebook-jssdk', '//connect.facebook.net/' + __ic.lang.replace('-', '_') + '/all.js#xfbml=1');
                ( function(d, s, id) {
                    var js, fjs = d.getElementsByTagName(s)[0];
                    if(d.getElementById(id))
                        {return;}
                    js = d.createElement(s);
                    js.id = id;
                    if(__ic.lang == 'pl-PL') {
                        js.src = "//connect.facebook.net/pl_PL/all.js#xfbml=1";
                    } else {
                        js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
                    }
                    fjs.parentNode.insertBefore(js, fjs);
                }(document, 'script', 'facebook-jssdk'));
            }
            //zakonczenie window load
        });
    },
    webpanels : {
        init : function() {
            $('#sidebar > .pnl').find('div:first').each(function(i, o) {
                $(o).click(function() {
                    var $pnl = $(this).parent();

                    var isVisible = $pnl.children("div + div").is(":visible");
                    $pnl.children("div + div:visible").slideUp("fast").prev().children("img").attr("src", "/img/downarrows.gif");
                    $pnl.children("div + div:hidden").slideDown("fast").prev().children("img").attr("src", "/img/uparrows.gif");
                    var value = "";
                    if(!isVisible) {
                        value = "expanded";
                    } else {
                        value = "collapsed";
                    }
                    var today = new Date();
                    today.setTime(today.getTime());
                    var expires = 2592000000/*30 * 1000 * 60 * 60 * 24*/;
                    var expires_date = new Date(today.getTime() + (expires));
                    document.cookie = $pnl.attr("id") + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "" );
                });
            });
        }
    },
    menu : {
        init : function() {
            $("#menu>ul>li>ul>li a:not(.ItemDisabled)").hover(function() {
                $(this).css('background-color', '#9ebef5');
            }, function() {
                $(this).css('background-color', '');
            });

            $("#menu>ul>li>ul>li>ul").prev().addClass('submenu').end().parent().hover(function() {
                $(this).children('ul').css('left', $(this).parent().width()).css('margin-top', -($(this).parent().height() / $(this).parent().children('li').length)).show().children('a:not(.ItemDisabled)').css('width', $(this).children('ul').width() - 50);
            }, function() {
                $(this).children('ul').hide();
            });

            $("#menu>ul>li>a").hover(function() {
                $(this).addClass('hl')
                //.attr('src', $(this).attr('src').replace("_1", "").replace(".png", "_1.png"))
                //.parent()
                .next().css('left', $(this).offset().left).css('top', $(this).offset().top + $(this).height()).show();
            }, function() {
                $(this).removeClass('hl')
                //.attr('src', $(this).parent().find('img').attr('src').replace("_1.png", ".png"))
                //.parent()
                .next().hide().hover(function() {
                    $(this).show().parent().children('a').addClass('hl');
                }, function() {
                    $(this).hide().parent().children('a').removeClass('hl');
                });
            });
            if($.fn.bgiframe)
               { $('#menu>ul>li ul').bgiframe();}

        }
    },
    tabs: {
    init: function()
    {
      var _cur_tab = $('input[id$=cur_tab]');
    var _tabs = [];
    var _tabContainers = [];
    $('ul.tabNavigation a').each(function () {
        // problemy w ie :/
        
        var path = this.pathname;
        if(path[0]!=='/')
            {path='/'+path;}
        if (window.location.pathname==path) {
            _tabs.push(this);
            _tabContainers.push($(this.hash).get(0));
        }
    });
    
    $(_tabs).click(function () {
        $(_tabContainers).hide().filter(this.hash).show();
        $(_tabs).removeClass('selected');
        $(this).addClass('selected');
        return false;
    })
    .filter(':first').click()
    ;
    
    
    $(window).bind('hashchange', function(e){
        if(location.hash!=='' && location.hash!=='#Form' )
        {
            if($('ul.tabNavigation a.selected').attr('href')!=location.hash)
            {
                
                $(_tabs).filter(function(i){ return $(this).attr('href')===location.hash;}).click();
               
            }
            location.hash='#Form';
        }
    });
    
    if(location.hash!=='' && location.hash!=='#Form')
        {
            $(window).trigger('hashchange');
        }
    else{
        var s = _cur_tab.val();
        if(s!=='')
        {
            $(_tabs).filter(function(i){ return $(this).attr('href')===s;}).click();
        }
        }
    }
    },
    companies_list : {
        gridId : '',
        maxRows : 10,
        active_till : '',
        infolink : true,
        show_page : function(i) {
            //alert('das');
            $('#' + __ic.companies_list.gridId + ' tr.Pages a').removeAttr("disabled");
            $('#' + __ic.companies_list.gridId).find('tbody tr:not(.DGHeader,.Pages,.hide)').hide().slice(((i - 1) * __ic.companies_list.maxRows), __ic.companies_list.maxRows * i).show();
            $('#' + __ic.companies_list.gridId + ' tr.Pages').children('#p' + i).attr("disabled", true);
        },
        pager : function() {
            if((__ic.companies_list.maxRows > 0) && __ic.companies_list.gridId.length > 0) {
                var count = $('#' + __ic.companies_list.gridId).find('tbody tr:not(.hide)').length;
                $('#' + __ic.companies_list.gridId + ' thead').find('tr.Pages').remove();
                $('#' + __ic.companies_list.gridId + ' tfoot').find('tr.Pages').remove();
                if(__ic.companies_list.maxRows > 0 && count > __ic.companies_list.maxRows) {
                    var linki = '';
                    for(var z = 1; z <= Math.ceil(count / __ic.companies_list.maxRows); z++) {
                        linki += '<a id="p' + z + '" href="javascript:__ic.companies_list.show_page(' + z + ');">' + z + '</a> ';
                    }
                    if(linki !== '') {
                        linki = '<tr class="Pages"><td colspan="2">' + linki + '</td></tr>';
                        $('#' + __ic.companies_list.gridId + ' thead').prepend(linki);
                        $('#' + __ic.companies_list.gridId + ' tfoot').append(linki);
                    }
                }
                __ic.companies_list.show_page(1);
            }

        },
        init : function() {
            //setTimeout(ui,10);

             function createinfolinks() {
                if(__ic.companies_list.infolink) {
                    $('.compGrid tr').each(function() {
                        if($(this).find('.quick_int').length === 0) 
                        {
                            var val = $(this).find('td input[type=checkbox]').val();
                            if(val !== undefined) {
                                var c = '';
                                if($(this).find('.quick_report').hasClass('warning')) {
                                    $(this).find('.quick_report').removeClass('warning');
                                    c = ' class="warning"';
                                }
                                $(this).find('td:last').prepend('<div' + c + '><a class="il" rel="nofollow facebox" href="details.html?' + val + '"/></div>');
                            }
                        }
                    });
                }
                $('a[rel*=facebox]').facebox();
            }

            function ui() {
                $('.compGrid tbody tr td').has('input').click(function(evt) {
                    if(evt.target == this) {
                        $(this).find('input').trigger('click');
                    }
                });
                $('.compGrid div.active_till').each(function() {
                    $(this).prepend(__ic.companies_list.active_till);
                });
                $('.compGrid #select').hover(function() {
                    $(this).children('ul').show();
                }, function() {
                    $(this).children('ul').hide();
                });
                $('#select #all').click(function() {
                    $('.compGrid tbody tr:not(.hide) input[type=checkbox]').attr('checked', true);
                });
                $('#select #none').click(function() {
                    $('.compGrid tbody tr:not(.hide) input[type=checkbox]').attr('checked', false);
                });
                $('#select #invert').click(function() {
                    $('.compGrid tbody tr:not(.hide) input[type=checkbox]').each(function() {
                        $(this).trigger('click');
                    });
                });
                $('#filterbox #box').keyup(function() {
                    var val = $(this).val();
                    if(val.length > 0) {

                        $('.compGrid tbody tr').each(function() {
                            $(this).addClass('hide');
                        });
                        $('.compGrid tbody tr:icontains(\'' + val + '\')').each(function() {
                            $(this).removeClass('hide');

                        });
                        $('#filterbox #box').addClass('active');
                    } else {
                        $('.compGrid tbody tr').each(function() {
                            $(this).removeClass('hide');
                        });
                        $('#filterbox #box').removeClass('active');
                    }
                    __ic.companies_list.pager();
                });
                /*
                 diff = maxRows -( $('#'+gridId+' tbody tr').length % maxRows);
                 if(diff>0)
                 {
                 for (var i=0; i<diff; i++){

                 $('#'+gridId+' tbody').append('<tr class=\'empty\'><td/><td/></tr>')
                 }
                 }
                 */
                __ic.companies_list.pager();
                createinfolinks();
                if(labels) {
                    createlabels();
                }

            }
            
            $(window).load(ui);
        }
    }
};

