window.addEvent("load", function(){
    
    $ES("fieldset[rel=expandable]", $$("body")).each(function(el){
    
        hide( el );
        
        var expandHeader = new Element( "div", { 
            "class" : "expandHeader",
            "id" : "displaygroupexpand_" + el.id
        } );
        expandHeader.injectBefore( el );
        expandHeader.addEvent( "click", function(e){
            if ( showhide( el.id ) == "shown" ) {
                expandHeader.addClass("expanded");
            } else {
                expandHeader.removeClass("expanded");
            }
        });
        if (el.hasClass("expanded")){
        	show(el);
        	expandHeader.addClass("expanded");
        }
        var expandHeaderContents = new Element( "div", {
            "class" : "contents"
        });
        
        expandHeaderContents.injectInside( expandHeader );
        
        var legend = el.getChildren()[0];
        
        if (legend.getTag() == "legend"){
        	expandHeaderContents.setHTML( legend.getText() );
        }
        
    });
    
    $$("input.textfieldcolourpicker").each(function(el){
        new MooRainbow('sxColourPicker_' + el.id, {
            'startColor': [255, 255, 255],
            'onChange': function(color) {
                el.value = color.hex;
            }
        });
    });
    
    $$("form .fieldwrapper").each(function(el){
        initializeField(el.id.substr( el.id.indexOf( '_' ) + 1, el.id.length - 1 ));
    });
    
    $$('.sxVolatile').each(function(el){
        el.addEvent("focus", function(){
            if (el.value == el.getProperty("title")){
                el.value='';
            }
        });
    });
    
    $$(".checklistinput").each(function(el){
        
        var fieldID = el.id.substr( 15 );

        $("additem_" + fieldID).addEvent("click", function(e){
            new Event(e).stop();
            addToCheckList($( "addvalue_" + fieldID ).value, $( "addvalue_" + fieldID ).value, fieldID);
            $( "addvalue_" + fieldID ).value = $( "addvalue_" + fieldID ).getProperty("title");
        });
        
        $("checklist_" + fieldID).getElements("input.removeIcon").each(function(el){
            initializeCheckListRemove(el);
        });
        
    });
    
    new Tips($$(".iCal, .resetCal"), {
		"tipcontents":"span",
		"maxTitleChars": 100,
		"offsets":{ "x":20, "y":0 }
	});
    
    $$(".iCal").each(function(el){
    
        var fieldID = el.id.substr( 5 );
        var myCal = new MooCal(fieldID);
        
        el.setStyle("cursor", "pointer");
        
    	el.addEvent("click", function(e){
    		var event = new Event(e).stop();
    		var x = event.page.x;
    		var y = event.page.y;
    		myCal.show(x,y);
    	});
    	
    });
    
    $$(".resetCal").each(function(el){
    
        var fieldID = el.id.substr( 9 );
        
        el.setStyle("cursor", "pointer");
        
    	el.addEvent("click", function(e){
    	
    		var event = new Event(e).stop();
    		
    		if ($(fieldID + "-day")) {$(fieldID + "-day").setProperty("value", "")};
    		if ($(fieldID + "-month")) {$(fieldID + "-month").setProperty("value", "")};
    		if ($(fieldID + "-year")) {$(fieldID + "-year").setProperty("value", "")};
    		if ($(fieldID + "_hour")) {$(fieldID + "_hour").setProperty("value", "")};
    		if ($(fieldID + "_minute")) {$(fieldID + "_minute").setProperty("value", "")};
    		if ($(fieldID + "_second")) {$(fieldID + "_second").setProperty("value", "")};
    		
    	});
    });
    
    $$('.checklistautocomplete').each(function(el){
        var checklistID = el.id.substr(el.id.indexOf("_") + 1);
        new MysticMeg("autocomplete_" + checklistID, { topOffset: 20, leftOffset: -8, onSelect: checklistAutoCompleteSelect, onSuccess: checklistAutoCompleteSuccess });
        $("checklist_" + checklistID).getElements("input.removeIcon").each(function(el){
            initializeCheckListRemove(el);
        });
    });
	
});

function initializeField( strFieldName ) {

    showhide( 'helpfield_' + strFieldName );
        
    var helpButton = 'helpbutton_' + strFieldName;
    if ( $(helpButton) ) {
        $(helpButton).setStyle("display", "block");
        $(helpButton).removeEvents();
        $(helpButton).addEvent("click", function(){ showhide('helpfield_' + strFieldName) });
        $(helpButton).addEvent("keypress", function(){ showhide('helpfield_' + strFieldName) });
    }
    
    $$( '#fieldwrapper_' + strFieldName + ' .removelibraryasset' ).each(function(el){
		el.addEvent("click", clRemoveAsset);
    });
    
    $$( '#fieldwrapper_' + strFieldName + ' .selectlibraryasset' ).each(function(el){
		el.addEvent("click", clSelectAsset);
    });
    
    $$( '#fieldwrapper_' + strFieldName + ' .expandlibrary' ).each(function(el){
		el.addEvent("click", clExpand);
    });
    
    $$( '#fieldwrapper_' + strFieldName + ' .contractlibrary' ).each(function(el){
		el.addEvent("click", clContract);
    });
    
    $$( '#fieldwrapper_' + strFieldName + ' .addlibraryasset' ).each(function(el){
		el.addEvent("click", clAddLibraryAsset);
    });

    Lightbox.init();
    
}

function clRefresh(strFieldID, strValue, strOpenIDs) {
	
	new Ajax( 
        window.location.pathname + window.location.search, 
        {
            method: "post", 
            data: { 
                "requestType" : "ajax", 
                "action" : "reloadLibraryControl",
                "fieldName" : strFieldID,
                "fieldValue" : strValue,
                "openIDs" : strOpenIDs
            }, 
            onComplete: function( oXMLHttp, oHeader ) {
            	
            	// Replace the library control with an updated version
            	$("ColonyLibrary_" + strFieldID).setHTML(oXMLHttp);
            	
            	$$( '#fieldwrapper_' + strFieldID + ' .hierarchy' ).each(function(el){
					initializeHierarchy(el);
			    });
            	
            	// Initialize the new set of HTML that was returned
                initializeField( strFieldID );
                
            }
        }
    ).request();
	
}

// Function for removing a particular asset from a colony library control
function clRemoveAsset( e ) {
	
	// Stop the click event so the page doesnt move to the top
    new Event(e).stop();
    
    // Get the clicked element
    var removalElement = new Event(e).target;
    
    removalElement = $(removalElement);
    
    // Check if the clicked element was an image, if it is then set it to its parent (the link)
    if (removalElement.getTag() == "img") {var removalElement = removalElement.getParent()}
    
    // Hide the link
    hide( removalElement );
    
    // Insert a loading indicator
    removalElement.getParent().insertBefore( new Element( "img", { "src" : "/edit/_images/icons/spinner.gif" } ), removalElement );
    
    // Get the ID of the clicked element
    var strID = removalElement.id;
    var arrID = strID.split( '_' );
    
    // Get the ID of the field and asset to remove
    var strFieldID = arrID[1];
    var strAssetID = arrID[2];
    
    // Get the field values and openIDs
    var strValue = $("Value_" + strFieldID).value.replace(' ', '');
    var strOpenIDs = $("OpenIDs_" + strFieldID).value;
    
    // Remove the asset from the values
    var arrValues = strValue.split(",");
    arrValues.remove(strAssetID);
    strValue = arrValues.join(",");
    
    // Make an AJAX request with the updated data
    clRefresh(strFieldID, strValue, strOpenIDs);
    
}

// Function for selecting a particular asset from a colony library control
function clSelectAsset( e ) {
	
	// Stop the click event so the page doesnt move to the top
    new Event(e).stop();
    
    // Get the clicked element
    var el = new Event(e).target;
    
    el = $(el);
    
    // Check if the clicked element was an image, if it is then set it to its parent (the link)
    if (el.getTag() == "img") {var el = el.getParent()}
    
    // Hide the link
    hide( el );
    
    // Insert a loading indicator
    el.getParent().insertBefore( new Element( "img", { "src" : "/edit/_images/icons/spinner.gif", "style" : "margin-top: 10px;" } ), el );
    
    // Get the ID of the clicked element
    var strID = el.id;
    var arrID = strID.split( '_' );
    
    // Get the ID of the field and asset to remove
    var strFieldID = arrID[1];
    var strAssetID = arrID[2];
    
    // Get the field values and openIDs
    var strValue = $("Value_" + strFieldID).value;
    var strOpenIDs = $("OpenIDs_" + strFieldID).value;
    
    // Add the new asset to the field value
    if (strValue.length == 0){
    	strValue = strAssetID;
    } else {
    	strValue = strValue + "," + strAssetID
    }
    
    clRefresh(strFieldID, strValue, strOpenIDs);
    
}

function clExpand(e) {
	
	// Stop the click event so the page doesnt move to the top
    new Event(e).stop();
    
    // Get the clicked element
    var el = new Event(e).target;
    
    el = $(el);
    
    // Check if the clicked element was an image, if it is then set it to its parent (the link)
    if (el.getTag() == "img") {var el = el.getParent()}
    
    // Get the ID of the clicked element
    var strID = el.id;
    var arrID = strID.split( '_' );
    
    // Get the ID of the field and asset to remove
    var strFieldID = arrID[1];
    var strCategoryID = arrID[2];
    
    // Get the field values and openIDs
    var strValue = $("Value_" + strFieldID).value;
    var strOpenIDs = $("OpenIDs_" + strFieldID).value;
    
    // Add the new asset to the field value
    if (strOpenIDs.length == 0){
    	strOpenIDs = strCategoryID;
    } else {
    	strOpenIDs = strOpenIDs + "," + strCategoryID;
    }
    
    var oSubCategories = $("SubCategories_" + strFieldID + "_" + strCategoryID);
    
    if (oSubCategories) {
    
    	show(oSubCategories);
    	
    	el.addClass("expanded");
	    el.addClass("contractlibrary");
	    
	    el.removeClass("expandable");
	    el.removeClass("expandlibrary");
	    
	    el.removeEvent("click", clExpand);
	    el.addEvent("click", clContract);
    	
    } else {
    	
    	clRefresh(strFieldID, strValue, strOpenIDs);
    	
    }
    
}

function clContract(e) {
	
	// Stop the click event so the page doesnt move to the top
    new Event(e).stop();
    
    // Get the clicked element
    var el = new Event(e).target;
    
    el = $(el);
    
    // Check if the clicked element was an image, if it is then set it to its parent (the link)
    if (el.getTag() == "img") {var el = el.getParent()}
    
    // Get the ID of the clicked element
    var strID = el.id;
    var arrID = strID.split( '_' );
    
    // Get the ID of the field and asset to remove
    var strFieldID = arrID[1];
    var strCategoryID = arrID[2];
    
    // Get the field values and openIDs
    var strValue = $("Value_" + strFieldID).value.replace(" ", "");
    var strOpenIDs = $("OpenIDs_" + strFieldID).value.replace(" ", "");
    
    // Remove the category from the openIDs
    var arrOpenIDs = strOpenIDs.split(",");
    arrOpenIDs.remove(strCategoryID);
    strOpenIDs = arrOpenIDs.join(",");
    
    $("OpenIDs_" + strFieldID).value = strOpenIDs;
    
    var oSubCategories = $("SubCategories_" + strFieldID + "_" + strCategoryID);
    
    if (oSubCategories) {
    	hide(oSubCategories);
    }
    
    el.removeClass("expanded");
    el.removeClass("contractlibrary");
    
    el.addClass("expandable");
    el.addClass("expandlibrary");
    
    el.removeEvent("click", clContract);
    el.addEvent("click", clExpand);
	
}

function clAddLibraryAsset( e ) {

    new Event(e).stop();
    
    var el = new Event(e).target;
    
    el = $(el);
    
    if (el.getTag() == "img") {var el = el.getParent()}
    
    var arrID = el.id.split( '_' );
    
    var strType = arrID[1];
    var strFieldID = arrID[2];
    var strCategoryID = arrID[3];
    
    var strFieldValue = $("Value_" + strFieldID).value;
    var strOpenIDs = $("OpenIDs_" + strFieldID).value;
    
    var strCallback = URLEncode(window.location.pathname + window.location.search)
    
    if (strType == "Image"){
    	var strPopupUrl = "/_colony/core/asset-library/images/sxforms-add.asp"
    } else {
    	var strPopupUrl = "/_colony/core/asset-library/files/sxforms-add.asp"
    }
    
    var myWindow = window.open(strPopupUrl + "?FieldValue=" + strFieldValue + "&OpenIDs=" + strOpenIDs + "&AssetCategoryID=" + strCategoryID + "&FieldID=" + strFieldID + "&ajax-callback=" + strCallback, "AddLibraryAsset", "height=600, width=600, location=no, menubar=no, resizable=no, scrollbars=yes, status=no, toolbar=no");
    
}

/* Check List Functions */
function addToCheckList( addValue, addText, fieldID ) {
	var newOptionID = ( $("checklist_" + fieldID).getChildren().length + 1 );
	var newOption = new Element("div", {"class" : "option", "id" : fieldID + "_" + newOptionID});
	var newInput = new Element("input", {
        "type" : "hidden", 
        "id" : fieldID + "_" + newOptionID, 
        "name" : fieldID,
        "value" : addValue
    });
	newOption.appendChild( newInput );
	var newRemoveIcon = new Element("input", {
        "type" : "image", 
        "id" : "removeitem_" + fieldID + "_" + newOptionID, 
        "src" : "/edit/_images/icons/famfam/bin.png",
        "alt" : "Remove",
        "class" : "removeIcon"
    });
	newOption.appendChild( newRemoveIcon );
	var newLabel = new Element("label", {'for' : fieldID + '_' + newOptionID});
	newLabel.setHTML(addText);
	newOption.appendChild(newLabel);
	$("checklist_" + fieldID).appendChild(newOption);
	initializeCheckListRemove(newRemoveIcon);
}

function checklistAutoCompleteSuccess( oResults, inputElement ){
	oResults.each(function(oResult){
        
        var fieldID = $(inputElement).id.substr($(inputElement).id.indexOf("_") + 1);
        var resultItem = $('autocompleteresult_' + inputElement + '_' + oResult.id);
        if ( !$('checklistautocomplete_' + fieldID).hasClass("acMultiSelect") ) {
            
            $$('input[name="' + fieldID + '"]').each(function(el){
                if ( el.value == oResult.id ) {
                    resultItem.addClass('disabled');
                } 
            });
        }
    });	
}

function checklistAutoCompleteSelect(oSelected, inputElement){
    var fieldID = $(inputElement).id.substr($(inputElement).id.indexOf("_") + 1);
    var resultItem = $('autocompleteresult_' + inputElement + '_' + oSelected.id);
    var boolAllowedToAdd = true;
    if ( !$('checklistautocomplete_' + fieldID).hasClass("acMultiSelect") ) {
        resultItem.addClass('disabled');
        $$('input[name="' + fieldID + '"]').each(function(el){
            if ( el.value == oSelected.id ) {
                boolAllowedToAdd  = false;
            } 
        });
    }
    if( boolAllowedToAdd ) { addToCheckList( oSelected.id, oSelected.value, inputElement.substr(inputElement.indexOf('_') + 1))};
}

function initializeCheckListRemove(el){
    el.addEvent("click", function(e){
        var fieldID = el.id.substr(11).substr(0, el.id.substr(11).indexOf("_"));
        new Event(e).stop();
        $(fieldID + "_" + el.id.substr(11).substr(fieldID.length + 1)).remove();
    });
}

