
// This is for non-site specific javascript!
$('document').ready(function()
{
	DatePicker(".dateInput");
});

function DatePicker(field) 
{

        $(field).datepicker({dateFormat: "mm/dd/yy", showOn: "button", buttonImage: "/images/calendar-icon.png", buttonImageOnly: true, changeMonth: true, changeYear: true});
        $("#ui-datepicker-div").addClass("promoteZ");
}

/* TODO: Deprecate use of this function. Use jQuery.ajax() instead.
 * [ Better browser support, more intuitive interface ]
 */
function AjaxRequest(location,url,post) {
    var http_request = false;

    if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) {
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    if (!http_request) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
    http_request.onreadystatechange = function() {changeStatus(http_request);};
    http_request.open('POST',url, true);
    http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http_request.send(post);
    return function changeStatus(http_request) {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                if(location != null)
                    document.getElementById(location).innerHTML = http_request.responseText;
            }
        }
    }
}


function SetSubSel(mainSel,subsel,DataItem,subkey,mainId) {

		$.getJSON
		(
			'/json',
                        'ServiceId=EnumDataService&Action=Enumerate&Type='+DataItem
                              +'&'+subkey+'='+mainId,
			function (j) {
				var options = "";
				$.each(j.Details,function(value,name) {
                                        options += '<option value="' + value + '">' + name + '</option>';
				});
                                        $("#"+subsel).html(options);
                                        $('#'+subsel+' option:first').attr('selected', 'selected');
			}
		);
}

function validatePW(form) {
	document.getElementById("validated").innerHTML = "";
	if(form.elements["pw1"].value != "" && form.elements["pw2"].value != "") {
		if(form.elements["pw1"].value == form.elements["pw2"].value)
			return true;
		else {
			document.getElementById("validated").innerHTML = "Passwords must match exactly";
			return false;
		}
	}
	else {
		document.getElementById("validated").innerHTML = "Passwords must not be blank";
		return false;
	}
}

function AddTreeItem() 
{
	$.ajax({
		url : '/json?ServiceId=AbstractTableService&action=createNode&nodeType=HRGrouptoComplexForm'
	});
}

function MakeCKE(divId) {
    var config = {
	resize_enabled: false,
	width: 600,
	bodyId: "ckeContent",
	toolbar:
	[
            ['Source', '-', 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Image', 'Link', 'Unlink', 'Anchor'] //Anchor appears to be broken
	]
    };
    //$("#"+divId).ckeditor(config);
    CKEDITOR.replace(divId, config);
}

function MakeEditable(divId) {
	var config = {
	resize_enabled: false,
	width: 725,
	bodyId: "ckeContent",
	toolbar:
	[
            ['Source'],
	    ['Bold','Italic','Underline','Strike','-','Subscript','Superscript', 'HorizontalRule'],
	    ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
	    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
	    ['SpellChecker', 'Image', 'Link', 'Unlink'],
	    ['Styles','Format','Font','FontSize']
	]
    };
    //$("#"+divId).ckeditor(config);
    CKEDITOR.replace(divId, config);
}

function closeEditable(instance, wrapper) {
	instance = eval(instance);
	instance.destroy();
	$("#"+wrapper).dialog("destroy");
	$("#"+wrapper).remove();
}

function destroyCKEs() {
	for(inst in CKEDITOR.instances) {
	    instant = eval("CKEDITOR.instances." + inst);
	    instant.destroy();
	}
}

function destroySWFUploaders() {
	for(inst in SWFUpload.instances) {
		instant = eval("SWFUpload.instances['" + inst + "']");
		instant.cancelUpload();
		instant.destroy();
	}
}

function updatePage(viewName) {
	$('#FormResponse').html("");
	vName = viewName.replace('DBView_', "");
				//newNodeName = "";
	dataString = $("#PageData").serialize();
	$.ajax({
					url: "/json",
					type : 'POST',
					dataType: 'html',
					async : 'false',
					data : "ServiceId=CMSPersistentObjectService&Action=AssignTopLevel&viewName=" + vName + "&pageName=Page__" + newNodeName + "_" + new Date().getTime() + "&id=" + nid+ "&"+dataString,
					success : function(data) { 
						$('#FormResponse').html("<b>Update Complete</b>");
						//$('#EditForm').html(data);
					}
	});
	
}

$(function()
{
	function collapsableClick(e)
	{
			var me = $(this);
			me.unbind('click', collapsableClick);
			me.next().toggle('blind', {}, 100, function(e) {me.bind('click', collapsableClick);} );

			var icons = me.children('span.vlab-icon');

			if (icons.length > 0)
			{
					$(icons).toggleClass('vlab-icon-arrow-down').toggleClass('vlab-icon-arrow-normal');
			}

			me.width(me.data('originalWidth'));
	}

        $('.vlab-container').each(function(i)
        {
                var jqObj = $(this);
				var width = jqObj.width();
                var isCollapsed = jqObj.hasClass('vlab-container-collapsed');
                
                jqObj.removeClass('vlab-container');
                jqObj.before('<div class="vlab-container-title"><span style="float: left; margin-top: 2px">' + this.title + '</span></div>');
                jqObj.wrapAll('<div class="vlab-container-content"></div>');

                var title = jqObj.parent().prev();
                var container = title.andSelf().wrapAll('<div class="vlab-container"></div>');

                if (jqObj.hasClass('vlab-container-collapsable'))
                {
                    title.data('originalWidth', title.width());
                    if (isCollapsed)
                    {
                        container.next().effect('blind', {}, 0);
                        title.prepend('<span class="vlab-icon vlab-icon-arrow-normal"></span>').bind('click', collapsableClick);
                    }
                    else
                    {
                        title.prepend('<span class="vlab-icon vlab-icon-arrow-down"></span>').bind('click', collapsableClick);
                    }
                }
                jqObj.children(':first').andSelf().css({'margin-top': '0', 'padding-top' : '0', 'display' : 'block'});
				jqObj.parent().width(width);
        });
});

