function checkSirenField () {
    var sirenField = $("#corpo-last-siren"); 
    var lastSiren = sirenField.val();
    if (! (($("#corpo-siren-" + lastSiren).length) || $(".corpo-siren-" + lastSiren).length)) {
        sirenField.val("");
    }
}

var updateLatestHistory=function() {
    if ($("#corpo-legal-not-logged").length===0) {
        var url= to_Ajax_URL("/search_history/latest");
        var datas=$('#search_form').serializeArray();
        $.ajax({
            type: 'POST',
            url: url,
            data: datas
        });
    }
};

corpo.functions.tracking = function(key, value1, value2, value3) {
    var data = {key: key, value1:value1, value2:value2, value3:value3};
    jQuery.get("/ajax/tracking", data);
};

function paginate (id, items_per_page, fetch_callback, error_callback) {
    var div_no_js = id + " div.pagination_no_js";
    var $div_no_js = $(div_no_js);
    
    if(!$div_no_js.length) {
        return false;
    }
    corpo.pages[id] = {
        begin: 0,
        end: 0,
        total: 0,
        next_link: '',
        fetch_callback: fetch_callback,
        error_callback: error_callback,
        web_link: undefined,
        source: undefined,
        list: [],
        items_per_page: items_per_page
    };
    var page =  corpo.pages[id];
    var no_js_next_link = $(div_no_js + " > a.next").attr('href');
    page.total =  parseInt ($(id + " span.total_no_js").text(), 10);
    
    page.web_link = $(div_no_js + " .source_link").attr ('href');
    page.source = $(div_no_js + " .source").html ();
    
    $(div_no_js).remove();
    page.list = $(id+" li");
    if (no_js_next_link) {
        page.next_link = to_Ajax_URL (no_js_next_link);
    } else {
        page.next_link = '';
    }
    $(id + " ul").empty ();
    $(id).append ($('<div/>').addClass("pagination"));
    create_links (id);
    paginate_forward (0, id);
    set_numbering (id);
    return true;
}

function create_links (id) {
    var count;
    var div =  $(id + " div.pagination");
    var moduleId = div.parents('.rub_content').attr('id');
    $('<a/>').appendTo(div).text ("<").attr ("href", "#" + moduleId).attr ("rel", "nofollow").click(function (e) {previous_page (e, id); });
    div.append (" ");
    $("<span/>").addClass ("numbering").appendTo (div);
    div.append (" ");
    $('<a/>').appendTo(div).text (">").attr ("href", "#" + moduleId).attr ("rel", "nofollow").click(function (e) {next_page (e, id);});
}

function set_numbering (id) {
    var page = corpo.pages[id];
    var total;
    var numbering;
    var tab_id = id.replace("_content","");
    var tab_title;
    var regexp = new RegExp ("\\(.+?\\)");
    var $numbering = $(id + " span.numbering");
    var formatted_total = format_number (page.total);

    if (page.begin + 1 === page.end) {
        numbering = page.end + "<span class='text-orange numbering_sep'> / </span>";
    } else {
        numbering = (page.begin + 1) + "-" + (page.end) + "<span class='numbering_sep'> / </span>";
    }
    $numbering.html(numbering);
    
    if (page.web_link) {
        total = $('<span><a class="source" href="' + page.web_link +
                  '" target="_blank">' +
                  formatted_total + '</a> ' + '</span>');
    } else {
        total = $('<span>' + formatted_total + '</span>');
    }
    
    $numbering.append (total);
    
    if(page.source) {
        var $source = $numbering.parent().children(".corpo-source-info");
        var source = '<span class="corpo-source-info">' + page.source + '</span>';
        	
        if($source.length) {
            $source.replaceWith(source);
        } else {
            $numbering.parent().append(source);
        }
    }
    
    if ($(tab_id)) {
        var $tabLink = $(tab_id + " > h2 > a");
        if (! $tabLink.has(".corpo-link-only").length) {
            tab_title = $tabLink.html();
            if(tab_title) {
                $tabLink.html(tab_title.replace(regexp, "(" + formatted_total + ")"));
            }
        }
    }
}

function next_page (event, id) {
    var page = corpo.pages[id];
    if (page.total > page.end) {
        paginate_forward (page.end, id);
        set_numbering (id);
    }
}

function previous_page (event, id) {
    var page = corpo.pages[id];
    if (page.begin > 0) {
        paginate_backward (page.begin - 1, id);
        set_numbering (id);
    }
}

function paginate_forward (i, id) {
    var page = corpo.pages[id];
    var ul = $(id + " ul.pagination-list");
    var overflowed = false;
    var items_left = page.items_per_page;
    var pagination = $(id + " > div.pagination");
    pagination.css ("visibility", "hidden");
    ul.empty();
    page.begin = i;
    do {
        fetch_from_server (i, page, id);
        if (! page.list[i]) {
            handle_error (id);
            break;
        }
        ul.append(page.list[i]);
        i++;
        items_left--;
    } while (items_left > 0 && i < page.total);
    if ((items_left === 0) && (page.begin + 1 < i)) {
        page.end = i;
    } else {
        page.end = page.list.length;
    }
    change_link_status($(id + " div.pagination a"), page);
    pagination.css ("visibility", "visible");
}

function paginate_backward (i, id) {
    var page = corpo.pages[id];
    var length = page.list.length;
    var ul = $(id + " ul.compact");
    var items_left = page.items_per_page;
    var pagination = $(id + " > div.pagination");
    pagination.css ("visibility", "hidden");
    ul.empty();  
    page.end = i + 1;
    do {
        ul.prepend(page.list[i]);
        i--;
        items_left--;
    } while (items_left > 0 && i >= 0);

    if (i >= 0) {
        page.begin = i + 1;
        change_link_status($(id + " div.pagination a"), page);
        pagination.css ("visibility", "visible");
    } else {
        paginate_forward (0, id); 
    }
}

function handle_error (id) {
    var error_callback = corpo.pages[id].error_callback;
    if (error_callback) {
        error_callback(id);
    }
}

function fetch_from_server (from, page, id) {
    var items;
    if ((from >= page.list.length) && (page.next_link !== '')) {
        if (page.fetch_callback) {
            items = page.fetch_callback (id);
            $(items).each(function(i, object) {
                page.list.push (object);
            });
            if (page.list.length > page.total) {
                page.total = page.list.length;
                page.next_link = '';
            }
            if ((page.next_link === '') && (page.total > page.list.length)) {
                page.total = page.list.length;
            }  
        }
    }
}

function change_link_status (links, page) {
    if (page.begin === 0) {
        links.first().attr("class", "page_link_unused");
    } else {
        links.first().attr("class", "page_link page_link_prev");
    }
    if ((page.end === page.list.length) && (page.next_link === '')) {
        links.last().attr("class", "page_link_unused");
    } else {
        links.last().attr("class", "page_link");
    }
}

function to_Ajax_URL (URL) {
    // IE does return relative links as absolute
    return ("/ajax" + URL.replace(/&amp;/g, "&").replace(/http:\/\/.*?\//, '/'));
}

function enable_tabs (id) {
    $(id + " > div.hidden_tab_content").each (function (i) {
        $(this).width($(this).parent().width());
    });
    $(id + " > ul > li > h2 > a").each (function (i) {
        $(this).bind ('click', function () {
            show_tab ('#' + $(this).parent().parent().attr("id")); 
        });
    });
}

function show_tab (li) {
    $(li).siblings().each(function (i) {
        $(this).attr("class", "hidden_tab");
        // IE reformats as absolute links
        var content = $(this).find("a").attr("href").replace(/^.*?#/, '#');
        $(content).attr("class", "hidden_tab_content");   
    });
    $(li).attr("class", "visible_tab");
    var visible_content = $(li).find("a").attr("href").replace(/^.*?#/, '#');
    $(visible_content).attr("class", "visible_tab_content compact");
}

function fetch_callback (id) {
    var page = corpo.pages[id];
    var result = '';
    var success_callback = function (json) {
        result = $(json.HTML).children("li");
        page.next_link = json.next_link;
        page.total = json.total;
    };
    $.ajax({url: page.next_link, dataType: 'json', success: success_callback,
            async: false});
    return result;
}

function format_number (number) {
    var string = number.toString ();
    var i = string.length;
    var j;
    while (i > 3) {
        i -= 3;
        j = string.charAt (i - 1);
        string = string.substr (0, i) + " " + string.substr (i);
    }
    return string;
}

function async_loading (unixmtime, dispatcher) {
    var Ajax;

    function periodicXHReqCheck() {
        try {
            if (! parse_async_content (Ajax.responseText)) {
                setTimeout(periodicXHReqCheck, 2000);
            }
        }
        // catch for TCP fragmentation and IE parsing
        catch (error) {
            setTimeout(periodicXHReqCheck, 1000);
        }
        return true;
    }
    
    if (corpo.async_loading) {
        return false;
    } else {
        corpo.async_loading = {};
        corpo.async_loading.offset = 0;
        var url = '/ajax/async_loading/' + unixmtime + '/' + dispatcher;
        Ajax = $.ajax({
            url: url,
            cache: true,
            ifModified: true,
            complete: function(data){
                corpo.async_loading.complete = true;
            }
        });
        setTimeout(periodicXHReqCheck, 2000);
        return true;
    }
}

function parse_async_content (body) {
    // cannot use JQuery: http://bugs.jquery.com/ticket/6516
    var tempdiv = document.createElement("div");
    tempdiv.innerHTML = body;
    var i = corpo.async_loading.offset;
    while (update_async_content (tempdiv.childNodes[i])) {
        i++;
        corpo.async_loading.offset = i;
    }
    if (corpo.async_loading.complete) {
        return true;
    } else {
        return false;
    }
}

function update_async_content (object) {
    if (object) {
        module = $(">span", $(object)).text();
        content = $("#" + module, $(object));
        $("#" + module).replaceWith(content);
        return true;
    } else {
        return false;
    }
}

function openModalBox ($a, width, height) {
    var url = $a.attr('href');
    $.get(url, function(data) {
        var $data = $(data);
        $data.find("#dialog_content").dialog({
            modal: true,
            width: width,
            height: height,
            title: $data.find("#dialog_title"),
            resizable: false,
            close: function(e, ui) {
            	$(e.target).remove();
            }
        });
    });
}

(function($){
	var circle = {
			options:{
				selectors: {
					bubble: ".corpo-circle-item"
				}
			},
			_create: function() {
				var self = this;
				self._delegate();
				self._rotate();
			},
			_delegate: function() {
				var self = this;
				self.element.delegate(".corpo-circle-item", "click", function(){
					var $link = ($(this).is("a")) ? $(this) : $(this).find("a");
					openModalBox ($link, 640, 360);
					return false;
				});
				self.element.delegate(".corpo-circle-item", "hover", function(e) {
					var $play = $(this).find(".corpo-circle-play");
					if(e.type === "mouseenter") {
						$play.fadeTo(500, 0.5);
					} else {
						$play.fadeTo(500, 0);
					}
				});
			},
			_rotate: function() {
				var self = this;
				self.$links = self.element.find(self.options.selectors.bubble);
				self.currentIndex = 0;
				self.rotate();
			},
			rotate: function() {
				var self = this;
				var $play;
				var callback = function() {
                    var hide_ie = function () {$play.hide();};
				    self.currentIndex = (self.currentIndex == self.$links.length -2) ? 0 : self.currentIndex+ 1;
				    setTimeout(function(){
					$play.fadeTo(700, 0, hide_ie);
				    },1700);
				    self.rotate();
				};
			    clearTimeout(self.timeout);
			    self.timeout = setTimeout(function(){
					$play = $(self.$links[self.currentIndex]).find(".corpo-circle-play");
					$play.fadeTo(700, 0.7,callback);
				},3500);
				
			}
	};
	$.widget("corpo.circle", circle);
})(jQuery);


(function($){
    var module_jobs = {
        options: {
            selectors: {
                form: "#corpo-module-filters-form-jobs"
            }
        },
        _create: function() {
            var self = this;
            self._initSearch();
        },
        _initSearch: function() {
	    var self = this;
	    var $form = $(self.options.selectors.form);
	    
            $form.submit(function() {
            var $tabs = $form.parent().next().find("li");
		$.each($tabs, function(i, tab) {
                var $tab = $(tab);
                var pageName = $tab.attr("id") + "_content";
                var page_id = "#" + pageName;

                var $searchForm = $("#search_form");
                var searchParams = $searchForm.serializeObject();

                //add filter value
                var filterParams = $form.serializeObject();
                var filterValue1 = $.trim(filterParams.jobs_keywords);
                var filterValue2 = $.trim(filterParams.jobs_location);

                //filter default value in fields
                var $include = $("#corpo-search-include");
                var $exclude = $("#corpo-search-exclude");

                if($include.attr("title") === $include.attr("value")) {
                    searchParams.include = "";
                }
                if($exclude.attr("title") === $exclude.attr("value")) {
                    searchParams.exclude = "";
                }

                if(filterValue1) {
                    searchParams.jobs_keywords = filterValue1;
                }
                if(filterValue2) {
                    searchParams.jobs_location = filterValue2;
                }

                //reset cursor
                var cursor = pageName + "_cursor";
                var page = corpo.pages[page_id];

                //change cursor??
                searchParams[pageName + "_cursor"] = "0";

                var ajaxURL = to_Ajax_URL("/search");

                var newURL = ajaxURL + "?" + $.param(searchParams);

                corpo.pages[page_id].next_link = newURL;
                corpo.pages[page_id].list = [];
                corpo.pages[page_id].total = 0;

                paginate_forward (0, page_id);
                set_numbering (page_id);
		});
		return false;
            });
        }
    };
    $.widget("corpo.module_jobs", module_jobs);

})(jQuery);

(function($){
    var salesConditionsDialog = {
        options: {
            selectors: {
                salesConditionsContent: "#corpo-sales-conditions-content",
                salesConditionsButton: "#corpo-sales-conditions-btn"
            }
        },
        _create: function() {
            var self = this;
            self.$content = $(self.options.selectors.salesConditionsContent);
            self.$button = $(self.options.selectors.salesConditionsButton);
            self._bindButton();
        },
        _bindButton: function() {
            var self = this;
            self.$button.click(function() {
                self.$content.dialog({
                    height: 530,
                    width: 650,
                    title: self.$button.attr('title'),
                    buttons: {
                        "Fermer": function() { $(this).dialog("close"); }
                    }
                });
                return false;
            });
        }
    };
    $.widget("corpo.salesConditionsDialog", salesConditionsDialog);
})(jQuery);

(function($){
    var cloud = {
        options: {
            selectors: {
                tag: "li",
                tagValue: "a.tag",
                searchForm: "#search_form",
                searchButton: "#search_button",
                action: "span.ui-icon",
                addInclude: "addInclude",
                addExclude: "addExclude",
                tagAction: ".tagAction",
                tagName: ".tagName"
            }
        },
        _create: function() {
            var self = this;
            self._bindTags();
            self._triggerExternalWidget();
        },
        _triggerExternalWidget: function() {
            var self = this;
            $(self.options.selectors.searchForm).trigger("cloud.load");
        },
        _bindTags: function() {
            var self = this;
            this.$items = this.element.children(this.options.selectors.tag);
            this.element.delegate(this.options.selectors.tag, "hover", function(e){
                $(this).toggleClass("corpo-state-active");
            });
            this.element.delegate(this.options.selectors.action, "click",function(e) {
                self._handleClick(e);
            });
        },
        _handleClick: function (e) {
            $target = $(e.target);
            if($target.hasClass(this.options.selectors.addExclude)) {
                this.addTagExclude(e);
            } else if ($target.hasClass(this.options.selectors.addInclude)) {
                this.addTagInclude(e);
            }
        },
        addTag: function (e, $input) {
            var self = this;
            $value = $(e.target).parents(this.options.selectors.tag).find(this.options.selectors.tagName).text();
            if($input.attr("value") == $input.attr("title"))
                $input.attr("value", "");
            $input.attr('value', $input.attr('value') + ' ' + $value);
            $form = $(this.options.selectors.searchForm);
            $form.find("input[name='include_policy']").attr('checked', true);
            this._reloadPage();
        },
        addTagInclude:function (e) {
            $input = $(this.options.selectors.searchForm).find("input[name='include']");
            this.addTag(e, $input);
        },
        addTagExclude: function (e) {
            $input = $(this.options.selectors.searchForm).find("input[name='exclude']");
            this.addTag(e, $input);
        },
        _reloadPage: function() {
            var self = this;
            $(document.body).core("overlay");
            $(self.options.selectors.searchButton).trigger("click");
        }
    };
    $.widget("corpo.cloud", cloud);
})(jQuery);

(function($){
    $.widget("corpo.corpochart", {
        options: {
            chartType: undefined,
            charts: {
                engine:{
                }
            }
        },
        _create: function() {
            var self = this;
            if(typeof self.options.chartType == "undefined") {
                return;
            }
        },
        load: function() {
            var self = this;
            var call = self.options.chartType;
            self[call]();
        },
        _setRowsSize: function(rows, data) {
            data.addRows(rows);
        },
        _addColumns: function(columns, data) {
            $.each(columns, function(i, val){
                data.addColumn(val.type, val.name);
            });
        },
        _addrows: function(rows, data) {
            $.each(rows, function(i, val) {
                data.addRow(val);
            });
        },
        engine: function() {
            alert("engine: N/A");
        },
        news: function() {
            var self = this;
            var data = new google.visualization.DataTable();
            var json = {
                rowsSize: 4,
                columns: [
                    {name: "News", type: "string"},
                    {name:"Volume", type: "number"}],
                rows:[
                    ['Tv/Radio', {v:17550, f:"17550 liens"}],
                    ['PQR', {v:1800, f:"450 liens"}],
                    ['PQN', {v:450, f:"450 liens"}],
                    ['Total', {v:20000, f:"450 liens"}]]
            };
            var rowsSize = json.rows.length;
            self._setRowsSize(rowsSize, data);

            var columns = json.columns;
            self._addColumns(columns, data);

            var rows = json.rows;
            self._addrows(json.rows, data);

            var inner = document.getElementById(self.element.attr('id'));
            var chart = new google.visualization.BarChart(inner);
            chart.draw(data, {
                width: 400, 
                height: 240, 
                title: 'Company Performance',
                vAxis: {
                    title: 'Year',
                    titleTextStyle: {color: 'red'}
                },
                hAxis: {
                    logScale: true
                }

            });
        }
    });
})(jQuery);

(function($){
    corpo.portlet = {};
    corpo.portlet.modules = ["cloud","news","videos","blogs","twitter","legal","jobs","wikipedia","images","slides","advertisement","social_pro","mails","links","documents","facebook", "pickanews"];
    corpo.portlet.positions = {};
    corpo.cookie = {
        path: '/',
        expires: 1 
    };
    corpo.funz = {
        addThis: function() {
            var script = 'http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4bf551fc0ac74dd1';
            if (window.addthis) {
                window.addthis = null;
            }
            $.getScript( script );

        },
        showModuleDetail: function($module) {
            var $content = $module.children('div.rub_content');
            
            //open the box if closed
            if($module.hasClass('corpo-state-collapse'))
                $module.removeClass('corpo-state-collapse');
            
            //hide or display detailed
            $module.toggleClass('corpo-state-detail-none');
            $module.parents('div.connected-sortable').sortable('savePositions');
            
            return false;
        },
        collapseModule: function(target) {
            var $target = $(target);
            var $module = $target.parents('div.rub');
            
            $module.toggleClass('corpo-state-collapse');
            $module.parents('div.connected-sortable').sortable('savePositions');
            
            return false;
        },
        bindResetClick: function() {
            $('#action-reset').bind('click', function(e) {
                corpo.funz.resetModulePositions();
            });
        },
        bindDetailClick: function() {
            $('a.action-detail').live('click', function(e) {
                var $target = $(e.target);
                var $module = $target.parents('div.rub');
                corpo.funz.showModuleDetail($module);
            });
        },
        bindToggleClick: function() {
            // DELEGATE SOME PORTLET CLICK ACTION
            $('a.action-toggle').live('click', function(e) {
                corpo.funz.collapseModule(e.target);
            });
        },
        bindTitleMouseOverOut: function() {
            $('.rubtitle').live('mouseover mouseout', function(e) {
                if (e.type == 'mouseover') {
                    $(e.target).parents('.rubtitle').addClass('corpo-state-hover-actions');
                } else {
                    $(e.target).parents('.rubtitle').removeClass('corpo-state-hover-actions');
                }
            });
        }
    };
})(jQuery);

(function($) {
    $.widget("corpo.subscribeForm", {
        _create: function () {
            this._bindSubscribeForm();
            if (typeof(_gaq) != "undefined") {_gaq.push(['_setCustomVar', 1, 'freemium', 'form']);}
        },
        _bindSubscribeForm: function () {
            var trackSubmit = function () {
                if (typeof(_gaq) != "undefined") {
                    _gaq.push(['_setCustomVar', 1, 'freemium', 'submited']);
                }
            };
            this.element.delegate("#subscribe_form", "submit", trackSubmit);

            /* Display ui dialog for conditions page */
            $('#condition_button').click(function() {
                $('#condition_dialog').dialog({
                    height: 530,
                    width: 650,
                    title: $(this).attr('title'),
                    buttons: {
                        "Fermer": function() {
                            $( this ).dialog( "close" );
                        }
                    }
                });
                return false;
            });
        }
    });
})(jQuery);

(function($) {
    $.widget("corpo.loginForm", {
        _create: function () {
            this._bindLoginForm();
        },
        _bindLoginForm: function () {
            /* Improve forgot password link if mail field filled */
            $('#forgot_password').click(function(){
                var login = $("#login").val();
                if(login !== '') {
                    $(this).attr('href', $(this).attr('href')+'?mail='+login);
                }
                return true;
            });
        }
    });
})(jQuery);

/* MODULES */
var notificationTooltip = (function(){
    var init = function(options) {
        var $tooltip = $(document.body).data("tooltip");
        if(typeof $tooltip === "undefined") {
            $tooltip = $('<div></div>');
            $tooltip.addClass("corpo-notify-tooltip rounded-5");
            $tooltip.appendTo(document.body);
            $(document.body).data("tooltip", $tooltip);
            $tooltip.delegate("*", "click",{$tooltip:$tooltip} ,delegateClick);
        }
        $tooltip.html("");
        $tooltip.append(closeButton());
        
        return $tooltip;
    },
    delegateClick = function(e) {
        if($(this).hasClass("ui-icon-close")) {
            var $tooltip = e.data.$tooltip;
            $tooltip.hide();
        }
    },
    closeButton = function() {
        return '<span class="corpo-notify-tooltip-close ui-icon ui-icon-close"></span>';
    },
    hide = function() {
        $(document.body).data("tooltip").hide();
        return false;
    },
    show = function(fcn) {
        var $tooltip = this.init({});
        return fcn($tooltip);
    };
    
    return {
        init:init,
        show: show,
        hide: hide
    };
    
})();

/* PLUGIN */
/**
 * Copyright (c) 2010 Conrad Irwin <conrad@rapportive.com> MIT license.
 * Based loosely on original: Copyright (c) 2008 mkmanning MIT license.
 *
 * Parses CGI query strings into javascript objects.
 * https://github.com/rapportive-oss/jquery-parsequery
 * See the README for details.
 **/
(function ($) {
    $.parseQuery = function (options) {

        var config = {query: window.location.search || ""},
        params = {};

        if (typeof options === 'string') {
            options = {query: options};
        }
        $.extend(config, $.parseQuery, options);
        config.query = config.query.replace(/^\?/, '');

        $.each(config.query.split(config.separator), function (i, param) {
            var pair = param.split('='),
            key = config.decode(pair.shift(), null).toString(),
            value = config.decode(pair ? pair.join('=') : null, key);

            if (config.array_keys.test(key)) {
                params[key] = params[key] || [];
                params[key].push(value);
            } else {
                params[key] = value;
            }
        });
        return params;
    };
    $.parseQuery.decode = $.parseQuery.default_decode = function (string) {
        return decodeURIComponent((string || "").replace('+', ' '));
    };
    $.parseQuery.array_keys = {test: function () {
        return false;
    }};
    $.parseQuery.separator = "&";
}(jQuery));

/*!
 * jQuery serializeObject - v0.2 - 1/20/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.

(function($,undefined){
    '$:nomunge'; // Used by YUI compressor.
    
    $.fn.serializeObject = function(){
	var obj = {};
	
	$.each( this.serializeArray(), function(i,o){
	    var n = o.name,
            v = o.value;
            
            obj[n] = (obj[n] === undefined) ? 
                v : ($.isArray( obj[n] )) ?
                obj[n].concat( v ) : [ obj[n], v ];
	});
	
	return obj;
    };
    
})(jQuery);

(function($){
    $.extend( $.ui.tabs.prototype, {
        rotation: null,
        rotationDelay: null,
        continuing: null,
        rotate: function( ms, continuing ) {
            var self = this,
            o = this.options;

            if((ms > 1 || self.rotationDelay === null) && ms !== undefined){//only set rotationDelay if this is the first time through or if not immediately moving on from an unpause
                self.rotationDelay = ms;
            }

            if(continuing !== undefined){
                self.continuing = continuing;
            }

            var rotate = self._rotate || ( self._rotate = function( e ) {
                clearTimeout( self.rotation );
                self.rotation = setTimeout(function() {
                    var t = o.selected;
                    var t2 = ++t;
                    self.select( t2 < self.anchors.length ? t : 0 );
                }, ms );

                if ( e ) {
                    e.stopPropagation();
                }
            });

            var stop = self._unrotate || ( self._unrotate = !continuing ? function(e) {
                if (e.clientX) { // in case of a true click
                    self.rotate(null);
                }
            }
					   : function( e ) {
                                               t = o.selected;
                                               rotate();
					   });

            // start rotation
            if ( ms ) {
                this.element.bind( "tabsshow", rotate );
                this.anchors.bind( o.event + ".tabs", stop );
                rotate();
                // stop rotation
            } else {
                clearTimeout( self.rotation );
                this.element.unbind( "tabsshow", rotate );
                this.anchors.unbind( o.event + ".tabs", stop );
                delete this._rotate;
                delete this._unrotate;
            }

            //rotate immediately and then have normal rotation delay
            if(ms === 1){
                //set ms back to what it was originally set to
                ms = self.rotationDelay;
            }

            return this;
        },
        pause: function() {
            var self = this,
            o = this.options;

            self.rotate(0);
        },
        unpause: function(){
            var self = this,
            o = this.options;

            self.rotate(1, self.continuing);
        }
    });
})(jQuery);

