/**
 * jQuery Initial input value replacer
 * 
 * Sets input value attribute to a starting value  
 * @author Marco "DWJ" Solazzi - hello@dwightjack.com
 * @license  Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * @copyright Copyright (c) 2008 Marco Solazzi
 * @version 0.1
 * @requires jQuery 1.2.x
 */


// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
	{
	    hash = hashes[i].split('=');
	    vars.push(hash[0]);
	    vars[hash[0]] = hash[1];
	}
    return vars;
}

(function (jQuery) {
    /**
     * Setting input initialization
     *  
     * @param {String|Object|Bool} text Initial value of the field. Can be either a string, a jQuery reference (example: $("#element")), or boolean false (default) to search for related label
     * @param {Object} [opts] An object containing options: 
     *                             color (initial text color, default : "#666"), 
     *                             e (event which triggers initial text clearing, default: "focus"), 
     *                             force (execute this script even if input value is not empty, default: false)
     *                             keep (if value of field is empty on blur, re-apply initial text, default: true)  
     */
    jQuery.fn.inputLabel = function(text,opts) {
        o = jQuery.extend({ color: "#666", e:"focus", force : false, keep : true}, opts || {});
        var clearInput = function (e) {
            var target = jQuery(e.target);
            var value = jQuery.trim(target.val());
            if (e.type == e.data.obj.e && value == e.data.obj.innerText) {
                jQuery(target).css("color", "").val("");
                if (!e.data.obj.keep) {
                    jQuery(target).unbind(e.data.obj.e+" blur",clearInput);
                }
            } else if (e.type == "blur" && value == "" && e.data.obj.keep) {
                jQuery(this).css("color", e.data.obj.color).val(e.data.obj.innerText);
            }
        };
        return this.each(function () {
                    o.innerText = (text || false);
                    if (!o.innerText) {
                        var id = jQuery(this).attr("id");
                        o.innerText = jQuery(this).parents("form").find("label[for=" + id + "]").hide().text();
                    }
                    else 
                        if (typeof o.innerText != "string") {
                            o.innerText = jQuery(o.innerText).text();
                        }
            o.innerText = jQuery.trim(o.innerText);
            if (o.force || jQuery(this).val() == "") {
                jQuery(this).css("color", o.color).val(o.innerText);
            }
                jQuery(this).bind(o.e+" blur",{obj:o},clearInput);
            
        });
    };
})(jQuery);


PROGRAMME = {
    blockUI : function(loadingmsg) {
        if( !loadingmsg ) {
            loadingmsg = '';
            //loadingmsg = '<div>Loading...</div>';
        }
        $.blockUI({ 
        message: loadingmsg
      , css: { border: 'none',
               cursor: 'default'
             }
      , overlayCSS: {backgroundColor: '#fff',
                     cursor: 'default'
                     }
      });
    }
    
    
    , unblockUI : function() {
        $.unblockUI();
    }
    
    , initProgramme : function() {
        var submitThemeFormOnSelect = true;
        
        $("form#themefilterform input[type=submit]").hide();
        
        $("form.sessionfilterform input[type=submit]").hide();
        
        $("select#themeselector").change( function(event){
            var selectElement = $(event.target);
            var optionElement = $("option:selected",selectElement);
            var themeID = optionElement.val();
            var themeForm = $("form#themefilterform");

            var currentSelectionElement = $("select.sessionselector",themeForm);
            if(submitThemeFormOnSelect) {
                /*Deselect any currently selected sessions; it look better.*/
                $("option",currentSelectionElement).removeAttr("selected");
                var loadingimg = $(".loadingimg").first();
                loadingimg.show()            
                PROGRAMME.blockUI();
                themeForm.submit();
            } else {
                var sessionSelectionToUse = $("form.session_selector_holder select.sessions_for_theme_" + themeID);                        
                /* Replace the current session-selector */
                currentSelectionElement.replaceWith(sessionSelectionToUse);
            }
        });
        var temp = submitThemeFormOnSelect;
        submitThemeFormOnSelect = false;
        $("select#themeselector").change(); /*fake a changeevent to update session-selector*/
        submitThemeFormOnSelect = temp;
        
        $("select.sessionselector").change( function(event){
            var selectElement = $(event.target);
            var themeForm = selectElement.parents("form");
            var loadingimg = $(".loadingimg").first();
            loadingimg.show()            
            PROGRAMME.blockUI();
            themeForm.submit();        
        });
        
        
        /* Expand and collapse events */
        $("li.event > p").click(function(event) {
            var eventdetails = $(".eventdetails", this.parentNode);
            if( !eventdetails.is(':visible') ) {
                /*close any other visible eventdetails*/
                $('.eventdetails:visible').slideUp('normal', function() {
                    $(this).prev().removeClass('active');
                });
            }
                    
            eventdetails.slideToggle();
            event.preventDefault();
            
            var abstractsLink = $("a.abstracts",eventdetails);
            if( abstractsLink.length > 0 ) {
                PROGRAMME.blockUI();
                var abstractsURL = abstractsLink.attr("href");
                var conferenceURL = $(".conferenceurllink").attr("href");
                abstractsLink.replaceWith('<div class="loadingimg"><img src="OSC_images/loading.gif"> Loading abstracts...</div>');
                var loadingImg = $(".loadingimg",eventdetails);
		var vars = getUrlVars();

		var param = "";
		if (vars['sessions%3Alist']){
		    param = "?sessions%3Alist=" + vars['sessions%3Alist'];		    
		}else if (vars['sessions:list']){
		    param = "?sessions%3Alist=" + vars['sessions:list'];
		};

                $.ajax({ url:abstractsURL + param
                        ,timeout:3600000
                        ,cache:true			    
                        ,success:function(abstractsList) {
                            if( abstractsList == "" ) {
                                abstractsList = '<p class="errormsg">Failed to load the list of abstracts</p>';
                            }
                            abstractsList = $(abstractsList);
                            abstractsList.hide();
                            loadingImg.before(abstractsList);
                            abstractsList.slideDown(1000);
                            loadingImg.slideUp(500,function(){$(this).remove();});
                            
                            
                            $("ul.abstracts",abstractsList).click(function(event){
                                event.stopPropagation();
                            });
                            
                            $(".abstract-link",abstractsList).fancybox({
                                'hideOnContentClick': false
                                ,'autoDimensions': false
                                ,'width': 600
                                ,'height': 400
                                ,'onComplete' : PERSONALCALENDAR.onAbstractLightBoxComplete
                            });
                            
                            PERSONALCALENDAR.updateAddAndRemoveButtons(abstractsList.parent());
                            PROGRAMME.unblockUI();
                            
                        }
                       ,dataType:"html"
                       ,error:function(request, error) {
                            loadingImg.replaceWith('<p class="errormsg">Failed to load the list of abstracts: " + error + "</p>');
                            PROGRAMME.unblockUI();
                       }
                      });
            }
            
            return false;
        });
        
        $(".abstract-link").fancybox({
            'hideOnContentClick': false
            ,'autoDimensions': false
            ,'width': 600
            ,'height': 400
            ,'onComplete' : PERSONALCALENDAR.onAbstractLightBoxComplete
        });

        
        $("#programmeSearchInput").inputLabel();
    }

};

$(document).ready(function () {
    PROGRAMME.initProgramme();
});

