$(function () {

    updateFields();
    
    function updateFields() {
        var cal = $("#calendar").parent();
        cal.find("input:hidden").remove();

        var fields = [];
        cal.find("td.sel").each(function () {
            fields.push('<input type="hidden" name="daytime[]" value="' + this.id + '"/>');
        });

        cal.prepend(fields.join(''));
    }

    $("div.dropdown").each(function () {
        var ele = $(this);
        ele.find(".dashed").click(function () {
            ele.toggleClass("dropdown-collapsed");
        });
        //console.log(ele.find(".dashed").length);
    });



    /* -- выпадайка -- */
    $("#bd div.companies-list td.manage").hover(function () {
        $("ul", this).addClass("open");
    }, function () {
        $("ul", this).removeClass("open");
    });
    /* -- /выпадайка -- */


/*
    $("div.widget-combo").combo({
        change: function (e, ui) {
            if (window.console) {
                console.log("old: " + ui.previous + ", new: " + ui.selected);
            }
        }
    }).bind("combochange", function () {
      console.log("!!!");
    });
*/

    // подсветка строк
    $("table.table-hovered tbody tr").not(".total, > th").hover(function () {
        $(this).addClass("table-hover");
    }, function () {
        $(this).removeClass("table-hover");
    });


   // --- подсказки к словам ---
   // содержимое подсказки берется из title
   $("ins.help").each(function () {
       var msg = $(this).attr("title");

       function HelpMessage(msg) {
           this.message = msg;
       }

       $.extend(HelpMessage.prototype, {
           message: "",

           element: null,

           timer: null,

           show: function (offset) {
               var me = this;

               if (me.element) {
                   return;
               }

               me.element = $('<div class="help-popup">' +
                                '<div class="help-popup-w hidden">' +
                                '<div class="help-popup-m">' +
                                '<em class="help-popup-pointer"></em>' +
                                me.message +
                                '</div>' +
                                '</div>' +
                                '</div>')
                       .appendTo("body").css(offset);

               me.element.hover(function () {
                   var balloon = me.element.find("div.help-popup-w");
                   if (me.timer) {
                       clearTimeout(me.timer);
                   }

                   balloon.removeClass("hidden");

                   if (balloon.offset().top <= 0) {
                       balloon.addClass("help-popup-down");
                   }

                   if (balloon.offset().left + balloon.width() >=
$(window).width()) {

balloon.children().andSelf().addClass("help-popup-right");
                   }
               }, function () {
                   me.hide();
               });
           },

           hide: function () {
               var me = this;
               if (me.timer) {
                   clearTimeout(me.timer);
               }
               this.timer = setTimeout(function () {
                   if (me.element) {
                       me.element.remove();
                       me.element = null;
                   }
                   me.timer = null;
               }, 300);
           }
       });

       if (msg && msg.length > 0) {
           $(this).removeAttr("title").data("helpMessage", new
HelpMessage(msg))
               .hover(function () {
                   var offset = $(this).offset();
                   offset.top = parseInt(offset.top +
parseFloat($(this).css("paddingTop")), 10);
                   offset.left = parseInt(offset.left +
parseFloat($(this).css("paddingLeft")), 10);
                   $(this).data("helpMessage").show(offset);
               }, function () {
                   $(this).data("helpMessage").hide();
               });
       }
   });
   // --- подсказки к словам ---
   

    $("#calendar").bind("click", function (e) {
        var target = $(e.target), cells;

        function updateFields() {
            var cal = $("#calendar").parent();
            cal.find("input:hidden").remove();

            var fields = [];
            cal.find("td.sel").each(function () {
                fields.push('<input type="hidden" name="daytime[]" value="' + this.id + '"/>');
            });

            cal.prepend(fields.join(''));
        }

        if (target.is("td")) {
            target.toggleClass("sel");
            updateFields();
        } else if (target.is("span") && target.parent().is("th")) {
            target = target.parent();
            cells = target.siblings("td");
            if (cells.length == 0) {
                // column
                var index = target.parent().children().index(target);
                target.parent().siblings().each(function () {
                    cells = cells.add($(this).children().eq(index));
                });
            }

            if (cells.not(".sel").length > 0) {
                cells.addClass("sel");
            } else {
                cells.removeClass("sel");
            }
            updateFields();
        }
    });

    $("#calendar-controls span").bind("click", function () {
        function select (cells) {
            if (cells.not(".sel").length > 0) {
                cells.addClass("sel");
            } else {
                cells.removeClass("sel");
            }
        }
        function getRow(ele) {
            var index = $(ele).parent().children().index(ele);
            var cells = [];
            $(ele).parent().siblings().each(function () {
                cells = $(this).children().eq(index).add(cells);
            });
            return cells;
        }
        var helpers = {
            "work": function () {
                var cells = [];
                $("#calendar tr:first-child th.work").each(function () {
                    cells = getRow(this).add(cells);
                });
                select(cells);
            },
            "notwork": function () {
                var cells = [];
                $("#calendar tr:first-child th:not(.work)").each(function () {
                    cells = getRow(this).add(cells);
                });
                select(cells);
            },
            "wholeday": function () {
                var cells = [];
                $("#calendar tr:first-child th").each(function () {
                    cells = getRow(this).add(cells);
                });
                select(cells);
            },
            "notweekend": function () {
                select($("#calendar th:first-child:not(.weekend)").parent().find("td"));
            },
            "weekend": function () {
                select($("#calendar th:first-child.weekend").parent().find("td"));
            },
            "wholeweek": function () {
                select($("#calendar th:first-child").parent().find("td"));
            }
        };
        var ele = $(this);
        $.each(helpers, function (name, func) {
            if (ele.hasClass(name)) {
                func();
                updateFields();
                return false;
            }
        });
    });


    if ($.isFunction($.fn.sparkline)) {
        $(".inlinesparkline").each(function () {
            var v = $(this).text().split(","), i, sumValue = 0, n = 0;
            for (i = 0; i < v.length; i++) {
                if (!isNaN(parseFloat(v[i]))) {
                    sumValue = sumValue + parseFloat(v[i]);
                    n = n + 1;
                }
            }

            $(this).sparkline('html', {
                type: "line",
                width: 80,
                lineColor: "#7d7e81",
                fillColor: false,
                spotColor: "#000000",
                minSpotColor: "#0062a7",
                maxSpotColor: "#d2232a",
                normalRangeMin: 0,
                normalRangeMax: n > 0 ? sumValue / n : 0,
                normalRangeColor: "#dcddde"
            });
        });
    }


//    $("div.datepicker-range").datepickerrange({
//      callback: function (text) {
//        console.log(text);
//      }
//    });


});

// генерация нового урла без date_range (берется location.search часть урла)
function url_without_date_range(search) {
  var tmp = new Array();
  var keys = new Array();      // два вспомагательных
  var vals = new Array();      // массива
  var params = new Array();
  var search_new = '';

  if (search != '')
  {
      tmp = (search.substr(1)).split('&');   // разделяем переменные
      var k = 0;
      for(var i=0; i < tmp.length; i++)
      {
          var keyval = tmp[i].split('=');       // массив param будет содержать
          if (keyval[0] == 'date_range' || keyval[0] == 'date') {
            continue;
          }
          keys[k] = keyval[0]; // ключи (могут повторяться в случае передачи массива)
          vals[k] = keyval[1]; // значения
          k++;
      }
      // составляем строку заново
//      for (var key in params) {
//          search_new += key + "=" + params[key] + "&";
//      }
      for (var i=0; i < keys.length; i++) {
          search_new += keys[i] + "=" + vals[i] + "&";
      }
  }

  return '?' + search_new;
}


// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function ajaxLoaderTableShow(ele){
  $(ele).closest("tr").addClass("loading");
}

function ajaxLoaderTableHide(){
  $("tr.loading").removeClass("loading");
}

