

$(document).ready(function() {
    // Creates  accordion UI for the worklists on the webdesk page
	// see http://docs.jquery.com/UI/Accordion/accordion#options for options
    $('#contributor-lists').accordion({
		header: 'h3',
		selectedClass: 'selected',
		autoHeight: false,
		active: false,
		alwaysOpen: false
	});

	$('#editor-lists').accordion({
		header: 'h3',
		selectedClass: 'selected',
		autoHeight: false,
		active: false,
		alwaysOpen: false
	});

   
    //temavelger - toggle mulige tema å velge
    $(".open").click(function (event) {
    	var thisclass = $(this).attr('class');
		var thisparent = $(this).parent().attr('class');
		var elem = $("." + thisparent + " > ul");
		if (thisclass == 'open'){			
			$(elem).slideDown("fast");		
   			$(this).removeClass('open');
   			$(this).addClass('close');
		} else {
			$(elem).slideUp("fast");		
			$(this).removeClass('close');
   			$(this).addClass('open');
		}
		
   	});

    //temavelger -> velg tema
    $(".notselected").click(function (event) {
    	$(this).addClass('selected');
    	$(".noneselected").removeClass('noneselected');
    	var thisparent = $(this).parent().attr('class');
    	var elem = $(".selectedContainer2 > ul > li." + thisparent).get(0)
    	$(elem).slideDown("fast");
    	//lagrer verdien av serial i en hiddenattributt
    	var storage = $(".storage").val();
    	storage = storage + " " + thisparent.substring(3);
    	$(".storage").val(storage);
   	});   	

    //temavelger - slett valg
    $(".delete").click(function (event) {
    	$(this).parent().removeClass('selected');
    	var thisparent = $(this).parent().attr('class');
    	var elem = $(".selectedContainer2 > ul > li." + thisparent)
    	$(elem).slideUp("fast");
    	//setter det valgte temaet tilbake slik at det kan velges på nytt
    	var elem2 = $("li." + thisparent + " > a");
    	$(elem2).removeClass('selected');
    	var elem3 = $("li." + thisparent);
    	$(elem3).removeClass('selected');    	
    	//fjerner verdien av serial i en hiddenattributt
    	var storage = $(".storage").val();
    	var serial = " " + thisparent.substring(3);
    	storage = storage.replace(serial, "");
    	$(".storage").val(storage);
    	//viser "Ingen valgt" igjen hvis det ikke er noen lagrede elementer i storage
    	//alert(storage);
    	if (storage.length < 1){
    		$(".first").addClass('noneselected');
    	}
   	});
    
    
    $("div.uibhideonfrontpagewidget").each(function(index,element) {
        element = $(element);
        $("input.checkbox",element).click(function(event) {
            var checkbox = $(event.target);
            var textCtrl = $("input.text",element);
            var textCtrlValue = textCtrl.val();
            var areaserial = checkbox.attr("id").split("_")[2]; // the id is on the form "w_<widgetid>.<occurrenceserial>_<areaid>"
            if( checkbox.attr('checked') ){
                textCtrlValue = textCtrlValue + " " + areaserial;
            } else {
                textCtrlValue = textCtrlValue.replace(areaserial,"");
            }
            textCtrlValue = textCtrlValue.replace("  "," ");
            textCtrl.val(textCtrlValue);
        });
    });





    /*Handlers for the @@/calendaritemconfig view. (see JEW-39 for more info) */
    $("#calendaritemconfig input.sharedonareacheckbox").click(function(event) {
        var checkbox = $(event.target);
        var liParents = checkbox.parents("li");
        var liParentCount = liParents.length;
        
        liParents.each(function(index,liElement) {                
            if(  (index < (liParentCount-1)) // skip the checkbox for the frontpage
               ){
                liElement = $(liElement);
                
                var activeShares  = $("input.sharedonareacheckbox:checked",liElement).length;
                var originalAreas = $("span.sharedonareacheckbox",liElement).length;
                
                if(checkbox.attr("checked")) {
                    // subtract the area that was just selected for sharing.
                    activeShares -= 1;
                }
                
                if(   (activeShares == 0)  // no active shared left in the parent-area or
                                                  // any of its sub-areas.
                   && (originalAreas == 0) // the topic isn't an OFS-descendant of the parent-area
                                                  // or any of its sub-areas.
                    ) {                    
                    var divElement = liElement.children("div");
                    
                    if(checkbox.attr("checked")) {
                        // We must check the "hide on frontpage" checkboxes on all the 
                        // ancestor areas, unless the topic is OFS-placed in the ancestor area
                        // or one of its sub-areas.
                        $("input.hideonareacheckbox",divElement).attr('checked','checked');
                    } else {
                        // We must uncheck the "hide on frontpage" checkboxes on all the 
                        // ancestor areas, unless one of the following is true:
                        //  * the topic is shared on the ancestor or on of the ancestors sub-areas
                        //  * the topic is OFS-placed in the ancestor or one of its sub-areas.
                        $("input.hideonareacheckbox",divElement).removeAttr('checked');
                    }
                    
                }
            }
        });
        
        if(checkbox.attr("checked")) {
            // unhide the topic on the area that was just selected (if needed)
            checkbox.siblings("input.hideonareacheckbox").removeAttr('checked');
            checkbox.siblings("input.hideonareacheckbox").removeAttr('disabled');
        } else {
            // disable the "hideonarea"-checkbox on the area (it doesn't make sense
            // to hide the topic, when the topic hasn't been shared on the area).
            checkbox.siblings("input.hideonareacheckbox").attr('disabled','disabled');
        }
        
    });
    
    $("#calendaritemconfig input.hideonareacheckbox").click(function(event) {
        var checkbox = $(event.target);
        if(checkbox.attr("checked")) {
        } else {
        }
    });


    // we must enable all the checkboxes in the form before submitting, since otherwise
    // they wouldn't be included in the form-data.
    var calendaritemconfigForm = $("#calendaritemconfig form");
    calendaritemconfigForm.submit(function () 
        { 
            $("input[type='checkbox']",calendaritemconfigForm).each(function(index,checkbox) {
                checkbox = $(checkbox);
                checkbox.removeAttr("disabled");
            
            });
        });


});



UIB_PUBLISH = {
    initialize : function() {
        // register the uib-specific widgets with the handler-code defined
        // in ztm.contenteditor
        LanguageAssociationWidget.prototype = new AssociationWidget;                // Define sub-class
        LanguageAssociationWidget.prototype.constructor = LanguageAssociationWidget;
        function LanguageAssociationWidget(widgetelement)
        {
            AssociationWidget.call(this,widgetelement); // Call super-class constructor
        }
        LanguageAssociationWidget.prototype.afterRebuildList = function (widget) 
        {
            var widgetobj = LanguageAssociationWidget.prototype.getWidgetObj(widget);
            var openSearchButton = $('.associationscontrols input', widget);
            if( $("span.deleter",widget).length == 0 ) {
                // no topics have been selected, so we can display the "Find"-button.
                openSearchButton.removeAttr("disabled");            
            } else {
                // A topic has already been selected, so we must hide the "Find"-button.
                // (Since it is only legal to select one single topic)
                openSearchButton.attr("disabled","disabled");
            }
        }
        

        function languageassociationwidget(element) {
            // Call the standard handler in ztm.contenteditor
            associationwidget(element);
            // replace the AssociationWidget widgetobj with a LanguageAssociationWidget object.
            var widgetobj = new LanguageAssociationWidget(element);    
            
            // Call the afterRebuildList()-function to hide the associationcontrols if needed.
            var widgetobj = element.get(0).widgetobj;
            widgetobj.afterRebuildList(element);
        }

        WIDGETHANDLERS['languageassociationwidget'] = languageassociationwidget;
        
        
        
        

        
        MultimediaWidget.prototype = new ImageWidget;                // Define sub-class
        MultimediaWidget.prototype.constructor = MultimediaWidget;
        function MultimediaWidget(widgetelement)
        {
            ImageWidget.call(this,widgetelement); // Call super-class constructor
        }
        MultimediaWidget.prototype.afterRebuildList = function (widget) 
        {
            
            var widgetobj = MultimediaWidget.prototype.getWidgetObj(widget);
            //ImageWidget.prototype.afterRebuildList(widget);

            var imagedetailslist = $(".imagedetails",widget);

            imagedetailslist.each(function(index,imagedetails)  {
                imagedetails = $(imagedetails);
                var image = imagedetails.siblings("img");
                var imgsrc = image.attr("src");
                if( imgsrc.indexOf("vimeocdn.com/") != -1 ) {
                    // This is a vimeovideo, so we must disable description-editing
                    imagedetails.find("textarea.imgdesc").attr('disabled','disabled');
                    // we must also tweak the width of the image a bit, since the vimeo
                    // thumbnail is a different size than the image-thumbnails.
                    image.attr("width","150");
                }
            });
            var cardinality_element = $("span.cardinality", widget);
            var cardinality = cardinality_element.text();
            var imageCount = $("span.deleter",widget).length;
            var associationscontrols = widget.find("p.associationscontrols");
            var associationscontrolsButtons = $("input",associationscontrols);
            if( (cardinality==0) || (imageCount < cardinality)) {
                // We are below the max number of images, so we can display the "Find"-button.
                associationscontrolsButtons.removeAttr("disabled");            
            } else {
                // We have all the images that we are allowed to, so we must hide the "Find"-button.
                associationscontrolsButtons.attr("disabled","disabled");
            }
            
            widgetobj.setupSortable(widget);

        }

        
        function vimeoSelectSucceded(result, status) {
            //$('.imagesearch', widget).hide();
            for (name in result) {
                var data = result[name];
                var widget = $('#' + name);
                //widget.find('.results').slideUp(200);
                widget.find('p.associationscontrols', widget).show();
                vimeotextbox = $('input.vimeoadd_textbox', widget),
                vimeotextbox.val("");
                var loadingimg = widget.find("#loading");
                loadingimg.hide();
            }
            rebuildList(result);
        }
                
        function onVimeoAddButtonClicked(event, page, url) {
            var hit = $(this),
            widget = hit.parents('.widget'),
            form = hit.parents('form'),
            vimeotextbox = $('input.vimeoadd_textbox', widget),
            data = {},
            operation = { 'operation' : 'addvimeoid'
                        , 'vimeoid': [vimeotextbox.val()]
                        };
            data[widget.attr('ztm:marker')] = operation
            
            // If this widget is being used by the wizard, we must also make sure that we transfer the wizard-specific
            // context. This is stored in two hidden input-fields: "serial" and "step"    
            //addWizardInfoIfNeeded(data,widget);
            data['serial'] = $('.topicserial').val();   
            var loadingimg = widget.find("#loading");
            loadingimg.show();
            
            jQuery.postJSON({ url : form.attr('action')
                            , data: data
                            , timeout: 50000
                            , success: vimeoSelectSucceded
                            , error: function(event) { loadingimg.hide();humanMsg.displayMsg('Adding vimeo video failed');}
                            });
            event.stopPropagation();
            event.preventDefault();

        }


        function multimediawidget(element) {
            // Call the standard handler in ztm.contenteditor
            imagewidget(element);
            // replace the ImageWidget widgetobj with a MultimediaWidget object.
            var widgetobj = new MultimediaWidget(element);    
            
            // Call the afterRebuildList()-function to disable the descritption-textfield if needed.
            //var widgetobj = element.get(0).widgetobj;
            widgetobj.afterRebuildList(element);
            
            $('li', element).each(associationline);
            $('input.vimeoadd_button', element).click(onVimeoAddButtonClicked);
            
        }

        WIDGETHANDLERS['multimediawidget'] = multimediawidget;
        
        
                
        
        
        
    }
};

UIB_PUBLISH.initialize();



