// /////////////////////////////////////////////////////////////////////////
// JobBasketManager wraps up cookie handling logic.
// Dependencies: jquery.js, jquery.cookie.js
// /////////////////////////////////////////////////////////////////////////
(function($) {

    if (!String.format) {
        // TK: If MicrosoftAjaxLibrary is not included, declare our own String.format method.
        // http://www.geekdaily.net/2007/06/21/cs-stringformat-for-javascript/
        String.format = function() {
            var i, exp;
	        for (i=1; i<arguments.length; i++) {
		        exp = new RegExp("\\{" + (i-1) + "\\}", 'gm');
		        arguments[0] = arguments[0].replace(exp,arguments[i]);
	        }
	        return arguments[0];
        }
    }

    function parseQueryString(qs) {
        var a, i, dict, pair;
        a = qs.split('&');
        dict = {};
        for (i in a) {
            pair = a[i].split('=');
            dict[pair[0]] = pair[1];
        }
        return dict;
    }

    // Property indexes
    var JobBasketManagerProperties = {
	    CookieName: 0,
	    CookieDisabled: 1,
	    DeclineCookieName: 2,
	    MaxItems: 3,
	    AddText: 4,
	    RemoveText: 5,
	    ViewText: 6,
	    BasketEmptyText: 7,
	    BasketFillText: 8,
	    BasketFullText: 9,
        JobBasketPage: 10
    };

    $(document).ready(function() {

        var _properties	= window.JobBasketManager_Properties;

        function init() {

            // private members
            var _jobIds = [];
            var cookieName = _properties[JobBasketManagerProperties.CookieName];

	        function _saveData() {
                // take data from array and store in cookie
                var cookieData = _jobIds.join(',');
                $.cookie(cookieName, cookieData, { path: "/" });
                // update status controls
                $(".jb-status").trigger("update");
	        }

		    function _empty() {
			    _jobIds = [];
			    _saveData();
		    }

	        function _getData() {
                // get data from cookie and store locally as arrays
                var cookieData = $.cookie(cookieName);
                if (cookieData) {
                    var arrData = cookieData.split('|');
				    if (arrData.length > 0) {
                        if (arrData[0]) {
					        _jobIds = arrData[0].split(',');
                        }
					    return;
				    }
                }
	        }

            function _getJobIndex(jobId) {
                var i;
			    for (i=0; i<_jobIds.length; i++) {
				    if (parseInt(_jobIds[i], 10) === jobId) {
                        return i;
                    }
                }
                return -1;
            }

            function _isInBasket(jobId) {
                return _getJobIndex(jobId) > -1;
            }

		    function _checkAcceptsCookies(){
                var cookieName = _properties[JobBasketManagerProperties.DeclineCookieName];
		        if ($.cookie(cookieName) !== "decline") {
			        $.cookie("cookietester", "cookietesterdata");
			        if ($.cookie("cookietester") === "cookietesterdata" || $.cookie(cookieName) !== "decline") {
				        $.cookie("cookietester", null); // delete tester cookie
				        return true;
			        }
			    }
			    return false;
		    }

            function _add(jobId) {
                var maxItems = _properties[JobBasketManagerProperties.MaxItems];
                _getData();
        	    var i = _getJobIndex(jobId);
                if (i === -1) {
                    var len = _jobIds.length;
				    if (len >= maxItems) {
					    if (confirm(_properties[JobBasketManagerProperties.BasketFullText])) {
                            window.location = _properties[JobBasketManagerProperties.JobBasketPage];
                        }
    				    return;
				    }
                    _jobIds.push(jobId);
    			    _saveData();
                }
	        }

		    function _remove(jobId) {
                _getData();
                var i = _getJobIndex(jobId);
                if (i > -1) {
                    _jobIds.splice(i, 1);
    			    _saveData();
                }
		    }

            function _getCount() {
                _getData();
                return _jobIds.length;
            }

            // initialise
            if (_checkAcceptsCookies()) {
                _getData();
            }

            // public methods
            return {
                add: _add,
                remove:_remove,
                getCount: _getCount,
                isInBasket: _isInBasket
            };
        }

        window.JobBasketManager = init();

        $(".jb-toggle").each(function(index) {
            var $link = $(this).show();
            var $item = $link.closest("li,span,td,dd");
            // create view link
            var $viewLink = $(".jb-view", $item.parent());
            var $viewItem = $viewLink.closest("li,span");
            // get job id
            var href = $link.attr("href");
            var qs = href.substring(href.indexOf('?') + 1);
            var nvc = parseQueryString(qs);
            var jobId = parseInt(nvc["jobId"], 10);
            // update event handler
            $link.bind("update", function() {
                if (!JobBasketManager.isInBasket(jobId)) {
                    $link.text(_properties[JobBasketManagerProperties.AddText]).removeClass("jb-toggle-remove");
                    $viewLink.hide();
                    $viewItem.hide();
                } else {
                    $link.text(_properties[JobBasketManagerProperties.RemoveText]).addClass("jb-toggle-remove");
                    $viewLink.show();
                    $viewItem.show();
                }
            });
            // attach events
            $link.click(function(ev) {
                if (JobBasketManager.isInBasket(jobId)) {
                    JobBasketManager.remove(jobId);
                } else {
                    JobBasketManager.add(jobId);
                }
                $link.trigger("update");
                return false;
            });
            // initialise display
            $link.trigger("update");
        });

        $(".jb-status").each(function() {
            var $this = $(this);
            // update event handler
            $this.bind("update", function() {
                var count = JobBasketManager.getCount();
                if (count > 0) {
                    $this.removeClass("jb-status-empty").html(String.format(_properties[JobBasketManagerProperties.BasketFillText], count));
                } else {
                    $this.addClass("jb-status-empty").html(String.format(_properties[JobBasketManagerProperties.BasketEmptyText], count));
                }
            });
            // initialise display
            $this.trigger("update");
        });
    });

})(jQuery);