
/* Jquery Translations for datepicker widget*/

/* German initialisation for the jQuery UI date picker plugin. */
/* Written by Milian Wolff (mail@milianw.de). */
jQuery(function($){
	$.datepicker.regional['de'] = {
		closeText: 'schließen',
		prevText: '&#x3c;zurück',
		nextText: 'Vor&#x3e;',
		currentText: 'heute',
        fromText: 'von',
        toText:'bis',
		monthNames: ['Januar','Februar','März','April','Mai','Juni',
		'Juli','August','September','Oktober','November','Dezember'],
		monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
		'Jul','Aug','Sep','Okt','Nov','Dez'],
		dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
		dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
		dateFormat: 'dd.mm.yy', firstDay: 1,
		isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['de']);
});

/* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood@virginbroadband.com.au) and Stéphane Nahmani (sholby@sholby.net). */
jQuery(function($){
	$.datepicker.regional['fr'] = {
		closeText: 'Fermer',
		prevText: '&#x3c;Préc',
		nextText: 'Suiv&#x3e;',
		currentText: 'Courant',
        fromText: 'de',
        toText:'jusque',
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
		'Jul','Aoû','Sep','Oct','Nov','Déc'],
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		dateFormat: 'dd/mm/yy', firstDay: 1,
		isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
});

/* Italian initialisation for the jQuery UI date picker plugin. */
/* Written by Apaella (apaella@gmail.com). */
jQuery(function($){
	$.datepicker.regional['it'] = {
		closeText: 'Chiudi',
		prevText: '&#x3c;Prec',
		nextText: 'Succ&#x3e;',
		currentText: 'Oggi',
        fromText: 'di',
        toText:'fino a',
		monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno',
		'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
		monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu',
		'Lug','Ago','Set','Ott','Nov','Dic'],
		dayNames: ['Domenica','Luned&#236','Marted&#236','Mercoled&#236','Gioved&#236','Venerd&#236','Sabato'],
		dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'],
		dayNamesMin: ['Do','Lu','Ma','Me','Gio','Ve','Sa'],
		dateFormat: 'dd/mm/yy', firstDay: 1,
		isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['it']);
});






// create a namespace using a hashmap
cstree = {
    selectedIds: [],
    xmlHttp: null,
    pagesize: 5,
    pagenumber: 1,
    from_date:'',
    to_date:'',
    lang:'en',
    
    initialize: function() {
        //initialize tabs and make columns
        var tabs = jq('ul.tabs').tabs('> div.pane', {
            onClick: function() {
                // "this" is a reference to the Tabs API
               this.getTabs().removeClass('tab_clicked');
            }
        });
        var api = jq("ul.tabs").data("tabs");
        api.getCurrentTab().addClass('tab_clicked');
        
        //make tabs collapsible
        jq('ul.tabs li a').bind('click',function(e){
            if(api.getCurrentTab().attr('href') == jq(this).attr('href') && jq(this).hasClass('tab_clicked')){
                if(api.getCurrentPane().css('display') == 'none'){
                    api.getCurrentPane().show();
                }
                else{
                    api.getCurrentPane().hide();
                }
            }
            else{
                api.getCurrentTab().addClass('tab_clicked');
            }
        });

        //make nice columns
        jq('#content .tabbedSection > div.pane > ul').makeacolumnlists({cols:4,colWidth:200});
        
        //count every ticked box on click event
        jq("#content INPUT[type='checkbox']").live('click',function(e){
            cstree.countSelectedTopics();
        });

        //read out language cookie
        var language_cookie = document.cookie.match ( '(^|;) ?' + 'I18N_LANGUAGE' + '=([^;]*)(;|$)' );
        if (language_cookie != null) 
            var language = language_cookie[2].substring(1,3);
        if (language_cookie == null) 
            var language = 'de';
        
        //initialize datepicker widget for date search
        cstree.datepicker_lang = jq.datepicker.regional[language];
        jq.datepicker.setDefaults(jq.extend({showMonthAfterYear: true}, cstree.datepicker_lang));
        jq("[name=from_date]").datepicker({changeMonth: true,changeYear: true, onSelect:cstree.pickedDate});
        jq("[name=to_date]").datepicker({changeMonth: true,changeYear: true, onSelect:cstree.pickedDate});

        
        var all_inputs = jq('#cs_tabbed_section').find("INPUT[type='checkbox']:not([name=toggleall])");
        all_inputs.bind('click', function(e){
            cstree.toggleSelection(e,jq(this));
        });
        
        //provide a reset function
        jq('#date_reset_link').bind('click',function(e){
            e.stopPropagation();
            e.preventDefault();
            var $date_from = jq('#datetimesearch [name=from_date]');
            var $date_to = jq('#datetimesearch [name=to_date]');
            $date_from.attr('value','');
            $date_to.attr('value','');
            cstree.from_date = $date_from.attr('value');
            cstree.to_date = $date_to.attr('value');
            //also remove date show up in the tab
            jq('[href=#datetimesearch] .showUpDateForm').remove();
            cstree.submitSelection();
        });
        
        
        //"select all" function per tabbed section
        var toggleAll = jq("#content INPUT[name=toggleall]");
        toggleAll.parent().css('position','relative');
        toggleAll.bind('click',function(e){
            var all_selected_boxes = jq(this).parent().parent().find("INPUT[type='checkbox']");
            all_selected_boxes.attr('checked',jq(this).attr('checked'));
            
            //we have to reset selectedIds, means allready selected elements must be deselected
            all_selected_boxes.each(function(i,o){
                var $targetNode = jq(o);
                var idx = cstree.selectedIds.indexOf($targetNode.attr('id').substring(4));
                cstree.selectedIds.splice(idx, 1);
            });
            
            cstree.toggleSelection(e,all_selected_boxes);
        });
        
        cstree.preselectItems();
        cstree.submitSelection();
    },

    countSelectedTopics: function() {
        //counter     
        jq('.classificationTab').each(function(i,o){
            var $this = jq(o);
            var a_el = jq('a', $this);
            var search_id = a_el.attr('href').substring(1);
            var search_container = $this.closest('.tabbedSection').find('#'+search_id);
            var count_checkedboxes = jq(search_container).find("INPUT[type='checkbox']:not([name=toggleall]):checked").length;
            var counter_el = jq('span.counter',a_el);
            if (!counter_el.length){
                a_el.append(' <span class="counter"></span>');
                var counter_el = jq('span.counter',a_el);
            }
            if (count_checkedboxes){
                counter_el.html('(' + String(count_checkedboxes) + ')');
            }else{
                counter_el.html('');
            }
        });
    },

    
    preselectItems: function() {
        uids = [];        
        
        // get uids from query string
        var query = location.search.substring(1);
        var pairs = query.split("&");
        for(var i=0; i<pairs.length; i++) { 
            pair = pairs[i].split("=");
            if (pair.length>1) {
                // get uids
                if (pair[0]=='cs_uids:list') {
                    uids.push(pair[1]);
                }
            }
        }
        
        // get uids from session if we got nothing from query string
        // (keep selection if user navigates back)
        if (uids.length<1) {
            var cookie_uids = document.cookie.match ('(^|;)cs_uids=([^;]*)');
            if (cookie_uids) {
                uids = cookie_uids[2].split(',');
            }
        }
        
        cstree.selectedIds = uids;
        // assign selected class to selected items
        var all_inputs = jq('#cs_tabbed_section').find("INPUT[type='checkbox']")
        all_inputs.each(function(i,o){
            var $input = jq(o);
            var input_uid = $input.attr('id').substring(4);
            if (uids.indexOf(input_uid) > -1){
                $input.attr('checked','checked');
            }
        });
        
        cstree.countSelectedTopics();
        
    },

    toggleSelection: function(e,objects) {
        //append or remove uid from selectedIds list
        objects.each(function(i,o){
            var $targetNode = jq(o);
            if ($targetNode.attr('checked')==false) {
                var idx = cstree.selectedIds.indexOf($targetNode.attr('id').substring(4));
                cstree.selectedIds.splice(idx, 1);


            } else {
                
                cstree.selectedIds.push($targetNode.attr('id').substring(4));
            }
        });
        
        cstree.pagenumber = 1;
        cstree.submitSelection();
        
    },
    
/* helper methods */
	cancelClick:function(e){
		if (window.event){
			window.event.cancelBubble = true;
			window.event.returnValue = false;
			return;
		}
		if (e){
			e.stopPropagation();
			e.preventDefault();
		}
	},

/* ajax stuff */
    submitSelection:function() {
        var url = window.location.pathname +  "";
        parameters = 'pagenumber=' + cstree.pagenumber;
        for (var i=0; i<cstree.selectedIds.length; i++) {
            var id = cstree.selectedIds[i];
            var tab_panel = jq('#uid_'+id).parents('.pane');
            var last_id;
            do {
                last_id = tab_panel.attr('id');
                tab_panel = tab_panel.parents('.pane');
            } while(tab_panel.length != 0);
            
            if (last_id){
                parameters += "&cs_uids_"+last_id+":list=" + cstree.selectedIds[i];
            }
        }
        parameters += "&from_date=" + cstree.from_date;
        parameters += "&to_date=" + cstree.to_date;
        jq.post(url+'/xml_cs_result',parameters,function(data){
            jq('#cs_result_section').html(data);
        });
        
        cstree.saveSelection();
    },

    showPage:function(event) {
        cstree.submitSelection();
        cstree.cancelClick(event);
    },
    
    saveSelection: function() {
        // delete cookie if nothing is selected
        if (cstree.selectedIds.length<1) {
            expires = new Date(new Date().getTime()-1);
            document.cookie = 'cs_uids=;expires=' + expires.toGMTString();
            return;
        }
        // store current selection in cookie for 5 minutes
        expires = new Date(new Date().getTime() + 300000);
        document.cookie = 'cs_uids=' + cstree.selectedIds.join(',');
    },
    
    clearSelection: function(event) {
        for (var i=0; i<cstree.selectedIds.length; i++) {
            removeClassName(document.getElementById(cstree.selectedIds[i]), cstree.selectedClass);
        }
        cstree.selectedIds = [];
        cstree.saveSelection();
        cstree.showPage(event);
    }, 
    
    pickedDate: function(dateText, obj){
        //puts the into bracked after the tab
        var $datetab = jq('[href=#datetimesearch]');
        if (jq('.showUpDateForm', $datetab).length == 0 ){
            var $date_el = jq("<span class='showUpDateForm'>(<span class='fromDate'></span><span class='toDate'></span>)</span>");
            $datetab.append($date_el);
        }else{
            var $date_el = jq('.showUpDateForm', $datetab);
        }

        var $el = jq(obj.input);
        if ($el.attr('name')=='from_date'){
            var from_date = $date_el.contents('.fromDate');
            var from_text = cstree.datepicker_lang['fromText'];
            from_date.html(' '+from_text+' '+dateText);
            //add date to query
            cstree.from_date = dateText;
        }else{
            var to_date = $date_el.contents('.toDate');
            var to_text = cstree.datepicker_lang['toText'];
            to_date.html(' '+to_text+' ' + dateText);
            //add date to query
            cstree.to_date = dateText;
        }
        
        cstree.submitSelection();
        
    }
}

// if indexOf is not implemented by the browser
// note: this is not an js 1.6 conform implementation!
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function array_indexOf() {
		if (arguments.length>0) {
		    for (var i=0; i<this.length; i++) {
		        if (this[i] == arguments[0]) {
		            return i;
		        }
		    }
		}
		return -1;
	}
};

//initialize
jq(function(){
    cstree.initialize();
});

