function getUserId() {
    var x = $.cookie("userID");
    if (x == null) {
        x = Math.random() * 1000000000000000000;
        $.cookie("userID", Math.round(x), {path : "/", expires : 30});
    }
    return x;
}

(function($) {
    $.fn.extend({
        updateMySelection : function() {
            this.each(function() {
                var $span = $(this);
                mySelection.getSize(getUserId(), function(result) {
                    $span.empty().append(result);
                }, {
                    errorHandler: function() {
                    }
                });
            });
        }
    })
})(jQuery);

(function($) {
    $.fn.extend({
        updateMyDealers : function() {
            this.each(function() {
                var $span = $(this);
                myDealers.getSize(function(result) {
                    $span.empty().append(result);
                }, {
                    errorHandler: function() {
                    }
                });
            });
        }
    })
})(jQuery);


function updateMySelection() {
    $("a.tyre span").updateMySelection();
}

function updateMyDealers() {
    $("a.dealer span").updateMyDealers();
}

function addToMySelection(tcm) {
    mySelection.addMySelectionByTcm(getUserId(), tcm, function() {
        updateMySelection();
    }, {
        errorHandler: function() {
        }
    });
}

function addToMyDealer(id) {
    myDealers.addMyDealer(id, function() {
        updateMyDealers();
    }, {
        errorHandler: function() {
        }
    });
}

function addToMySelectionByID(pubID, compID) {
    mySelection.addMySelection(getUserId(), pubID, compID, function() {
        updateMySelection();
    }, {
        errorHandler: function() {
        }
    });
}

function TyreSelection(conf) {
    if (conf.loadListeners) {
        this.loadedList = conf.loadListeners;
    }
}

TyreSelection.prototype = {

    _size : null,

    loadedList : [],

    tyres : [],

    add : function(publicationId, itemId) {

        var _this = this;

        mySelection.addMySelection(getUserId(), publicationId, itemId, function() {
            _this.load();
        }, {
            errorHandler: function() {
            }
        });
    },

    addByTcm : function(tyre_tcm) {
        mySelection.addMySelectionByTcm(getUserId(), tyre_tcm, {
            errorHandler: function() {
            }
        });
    },

    fireLoadEvent : function() {
        var _this = this;

        $.each(this.loadedList, function() {
            this.call(this, _this.tyres, _this.size);
        });
    },

    load : function(fn) {
        if (fn) {
            this.loadedList.push(fn);
        } else {

            var _this = this;

            mySelection.getMySelections(getUserId(), function(result) {
                _this.tyres = result[0];
                _this.size = result[1];

                _this.fireLoadEvent();

            }, {
                errorHandler: function() {
                }
            });
        }
    },

    remove : function(publicationId, itemId) {

        var _this = this;

        mySelection.removeMySelection(getUserId(), publicationId, itemId, function () {

            for (var i in _this.tyres) {
                if (_this.tyres[i].userId == getUserId()
                        && _this.tyres[i].publicationId == publicationId
                        && _this.tyres[i].itemId == itemId) {
                    _this.tyres.splice(i, 1);
                }
            }

            _this.fireLoadEvent();
        }, {
            errorHandler : function () {
            }
        });

    },

    removeAll : function() {

        var _this = this;

        mySelection.removeAll(getUserId(), function() {
            _this.tyres = [];
            _this.size = null;

            _this.fireLoadEvent();
        }, {
            errorHandler: function() {
            }
        });
    },

    size : function(value) {
        if (value != "undefined") {
            this._size = value;

            this.fireLoadEvent();
        }

        return this._size;
    }
};

/**
 *
 * @param table {String}
 * @param rendIds {String[]}
 */
function Table(table, rendIds, ps) {
    this.root = table;

    if (rendIds != "undefined") {
        this.renders = rendIds;
    }

    if (ps != "undefined") {
        this.params = ps;
    }
}

Table.prototype = {

    $tableSorter : null,

    params : {},

    root : null,

    entities : [],

    renders : [],

    filter : function(entry){
    	return true;
    },

    addRenderer : function(fn) {
        this.renders.push(fn);
    },

    update : function(en) {

        if (en) {
            this.entities = en;
        }

        $(this.root).children("tbody:first").empty();
        this.render();

        if (!this.$tableSorter) {
            this.$tableSorter = $(this.root).tablesorter(this.params);
        } else {
            $(this.root).trigger("update");
        }

    },

    render : function() {
        for (var row = 0; row < this.entities.length; row++) {

            var entry = this.entities[row];
            if(!this.filter(entry)) continue;
            var trAttr = this.params.trAttr ? this.params.trAttr(entry, row) : "";

            var $tBody = $(this.root).children("tbody:first");

            $tBody.append("<tr " + trAttr + " ></tr>");
            var $tr = $tBody.children("tr:last");
            for (var column = 0; column < this.renders.length; column++) {

                var tdAttr = this.params.tdAttr ? this.params.tdAttr(entry, row, column) : "";

                $tr.append("<td " + tdAttr + " ></td>");
                var $td = $tr.children("td:last");

                $td.setTemplate(jQuery.isFunction(this.renders[column]) ? $(this.renders[column].call(this, entry, row, column)).html() : $(this.renders[column]).html());
                $td.setParam("row", row);
                $td.setParam("column", column);

                $td.processTemplate(entry);

            }
        }
        if (this.entities.length == 0 && this.params.emptyRender) {
            var trAttrEmpty = this.params.trAttrEmpty ? this.params.trAttrEmpty(entry, row) : "";
            var tdAttrEmpty = this.params.tdAttrEmpty ? this.params.tdAttrEmpty(entry, row, column) : "";

            var $tBody = $(this.root).children("tbody:first");

            $tBody.append("<tr " + trAttrEmpty + " ></tr>");
            var $tr = $tBody.children("tr:last");

            $tr.append("<td class='compare' >&nbsp;</td>");
            $tr.append("<td " + tdAttrEmpty + " ></td>");
            var $td = $tr.children("td:last");

            $td.setTemplate($(this.params.emptyRender).html());
            $td.processTemplate(entry);
        }
        $(this.root).find('td .showtooltip').tooltip();
    }

};

function addOptions(selector, result) {

    var argCount = arguments.length;

    var arg3, arg4;
    if (argCount >= 3) arg3 = arguments[2];
    if (argCount >= 4) arg4 = arguments[3];

    $.each(result, function(index, item) {
        if (item) {
            var option = "<option value='" + (arg3 ? item[arg3] : item) + "'>" + (arg4 ? item[arg4] : item) + "</option>";
            $(selector).append(option);
        }
    });
}

function removeAllOptions(selector) {
    $(selector).empty();
}

var popupHooks = {};

function showLoadingPopup(id) {
    if (!popupHooks[id] || popupHooks[id] == 0) {
        var boxy = new Boxy($(id), {title:'', modal:true});
        $.data($(id)[0], 'boxy-popup', boxy);
        popupHooks[id] = 1;
    } else {
        popupHooks[id] += 1;
    }
}

function hideLoadingPopup(id) {
    popupHooks[id] -= 1;

    if (popupHooks[id] < 0) {
        popupHooks[id] = 0;
    }

    if (popupHooks[id] == 0) {
        var boxy = $.data($(id)[0], 'boxy-popup');
        if (boxy) {
            boxy.hide();
        }
    }
}
