/// <reference path="jquery-1.3.2-vsdoc.js" />
var isPageEditEnabled = false;

// Use this to trigger new box edit functionality
var useBoxEdit = true;


// This fixes a jquery bug in safari and chrome. Remove after incrementing beyond version 1.4.4
(function(){
    // remove layerX and layerY
    var all = $.event.props,
        len = all.length,
        res = [];
    while (len--) {
      var el = all[len];
      if (el != 'layerX' && el != 'layerY') res.push(el);
    }
    $.event.props = res;
}());


/** 
 * Toggle the visibility of a field
 * 
 * Note: css must contain the following selectors:
 *
 * .visible {
 *     display: block;
 * }
 * .invisible {
 *     display: none;
 * }
 *
 * Example:
 *
 * <a href="#" onclick="toggleVisibility('fieldId')">toggle</a>
 * <div id="fieldId" class="invisible">hello world</div>
 */
function toggleVisibility(myfieldname) 
{
    var myfield = document.getElementById(myfieldname);
    
    if (myfield.className == "invisible") 
	{
        // myfield.className = "visible"; 
        // NOTE: using class "visible" instead of empty quotes will cause table rows to grow horizontally
        myfield.className = "";
    } 
	else 
	{
        myfield.className = "invisible";
    }
    
    return false;
}

/** 
 * Make a hidden field visible
 * 
 * Example:
 *
 * <a href="#" onclick="makeVisible('fieldId')">show</a>
 * <div id="fieldId" class="invisible">hello world</div>
 */
function makeVisible(myfieldname) 
{
    var myfield = document.getElementById(myfieldname);
    
    if (myfield !== null) 
	{ 
        // NOTE: using class "visible" instead of empty quotes will cause table rows to grow horizontally
        myfield.className = "";
    }

    return false;
} 

/** 
 * Make a field invisible
 * 
 * Example:
 *
 * <a href="#" onclick="makeInvisible('fieldId')">hide</a>
 * <div id="fieldId" class="visible">hello world</div>
 */
function makeInvisible(myfieldname) 
{
    var myfield = document.getElementById(myfieldname);
    
    if (myfield !== null) 
	{ 
        myfield.className = "invisible";
    }
    
    return false;
} 

function deleteTag(tagId) 
{
    var myfield = document.getElementById('delete_tag_id');
    
    if (myfield !== null) 
	{ 
		myfield.value = tagId;
		document.delete_tag_form.submit();
    }
    return false;
} 

function selectTag(tagId) 
{
    var myfield = document.getElementById('search_tag_id');
    
    if (myfield !== null) 
	{ 
		myfield.value = tagId;
		document.search_tag_form.submit();
    }
    return false;
} 

function addProduct(id, qty, license)
{
    if (id == 0)
    {
        id = $('#productId').val();
    }
    $.getJSON('/index.php?q=cart&action=add&productId=' + id + '&productQty=' + qty + '&productLicense=' + license,
    function(data)
    {
        $('#cartContent').html(data.response);
        $("input:submit, button, input:button").button();
    });
}

function addProductSingleProduct(id, qty, license)
{
    $(".cartContent").html("");
    if (id == 0)
    {
        id = $('#productId').val();
    }
    $.getJSON('/index.php?q=cart&action=add&productId=' + id + '&productQty=' + qty + '&productLicense=' + license,
    function(data)
    {
        $('#cartContent_' + id).html(data.response);
        $('#cartSideNav').html(data.response);
        $("input:submit, button, input:button").button();
    });
}

function removeProduct(id)
{
    $.getJSON('/index.php?q=cart&action=remove&productId=' + id,
    function(data)
    {
        $('#cartContent').html(data.response);
    });
}

function removeProductWithReload(id)
{
    $.getJSON('/index.php?q=cart&action=remove&productId=' + id,
    function(data)
    {
        //$('#cartContent').html(data.response);
        window.location = window.location.href;
    });
}

function deleteCart()
{
    if (confirm('Are you sure you would like to empty your shopping cart?'))
    {
        $.getJSON('/index.php?q=cart&action=delete',
        function(data)
        {
            $('#cartContent').html(data.response);
        });
    }
}

function addToCart(id)
{
    if (id == 0)
    {
        id = $('#productId').val();
    }
    var qty = $('#qty').val();

    if (isNaN(qty))
    {
        qty = 1;
    }

    var license = $('#license_' + id).val();
    if (isNaN(license))
    {
        license = 0;
    }

    addProduct(id, qty, license);
}

function addToCartSingleProduct(id)
{
    if (id == 0)
    {
        id = $('#productId_' + id).val();
    }
    var qty = $('#qty_' + id).val();

    if (isNaN(qty))
    {
        qty = 1;
    }

    var license = $('#license_' + id).val();
    if (isNaN(license))
    {
        license = 0;
    }

    addProductSingleProduct(id, qty, license);
}

function deleteFromCart(id)
{
    deleteProduct(id);
}

/** 
 * Hide the peek section on page load
 */
$(document).ready(
function() 
{
	$('#config').hide();
	$('#config').css("height", "300px");

	$('a#slideout').click(function() 
	{
		$('#config').slideToggle("normal");
		return false;
	});
});

$(document).ready(function()
{
	$('#tabs').tabs();
	$('#tabs').show();
});

$(document).ready(function(){
	$("#contentAccessType").change(
		function () 
		{
			var contentType = $("#contentAccessType").val();
			
			if (contentType == 0)
			{
				// switching to single mode, check multiple editors before roundtripping.
				//var content_0_isDirty = CKEDITOR.instances.page_content.checkDirty();
				//if (content_0_isDirty)
				//{
					//console.log("Content 0 is dirty");
				//}
				
				$("#page_content_form_save").val("Edit");
				$("#page_content_form_save").click();
			}
			else 
			{
				// switching to multiple mode, check single editor before roundtripping.
				//var content_0_isDirty = CKEDITOR.instances.page_content.checkDirty();
				//if (content_0_isDirty)
				//{
					//console.log("Content is dirty");
				//}
				
				$("#page_content_form_save").val("Edit");
				$("#page_content_form_save").click();
			}
		}
	);
});

$(document).ready(function()
{
	$("#adminEditPageContentButton").click(function() 
	{
        // if using new non-form content editing functionality, set edit flag (enable content editing)
        if (isPageEditEnabled == false)
        {
            enablePageEdit();
        }
        else
        {
            disablePageEdit();
        }

        // Code out for new box edit functionality
        if (useBoxEdit == false)
        {
            $("#editPageContentButton").click();
        }
	});


    $("#pagePreferencesDialog").dialog(
    {
        autoOpen: false,
        height: 300,
        width: 700
    });
    
    $("#adminEditPagePropertiesButton").click(function()
	{
        $("#pagePreferencesDialog").dialog('open');

        fetchPagePreferences();
	});


	//$("#addProductForm #submitbutton").click(function() 
	//{
		//if ($("#addProductForm").validate().form())
		//{	
			//$("#addProductForm #submitbutton").attr('disabled', 'disabled');
			//$("#addProductForm").submit();
		//}
	//});
});

$(document).ready(function()
{
	$("#adminEditPageContentButton").hover(function()
	{
        makeVisible("editPageContentForm");
        makeInvisible("editPageContentButton");

        //$("#editPageContentForm").addclass("visible");
        $("#editPageContentForm").css(
            {
                "border": "2px dashed #D8CFC1"
            }
        );
	},
    function()
    {
        makeInvisible("editPageContentForm");

        //$("#editPageContentForm").addclass("visible");
        $("#editPageContentForm").css(
            {
                "border": "none"
            }
        );
	});

    // Toggle hidden spaces
    jQuery(".togglecontent").hide();
    jQuery(".toggleheading").click(function()
    {
        jQuery(this).next(".togglecontent").slideToggle(300);
    });
});

$(document).ready(function()
{
    //var editor = CKEDITOR.replace('page_content');
    
    // fetch data from the editor
    //alert(CKEDITOR.instances.page_content.getData());

    // update the data in the editor
    //CKEDITOR.instances.page_content.setData("Larry Was Here");

    $(".draggable").draggable({
        //	use a helper-clone that is append to 'body' so is not 'contained' by a pane
        helper: function() { return $(this).clone().appendTo('body').css('zIndex', 5).show(); },
        cursor: 'move'
    });
});

function indicateAjaxRequest(obj)
{
    obj.addClass("busy");
    obj.removeClass("neutral");
}
function indicateAjaxComplete(obj)
{
    obj.addClass("neutral");
    obj.removeClass("busy");
}

function indicateAjaxRequestDialog(obj)
{
    obj.addClass("busyDialog");
    obj.removeClass("neutral");
}
function indicateAjaxCompleteDialog(obj)
{
    obj.addClass("neutralDialog");
    obj.removeClass("busy");
}

function getBasicWysWithWidth(replaceVar, width)
{
    CKEDITOR.config.startupMode = 'wysiwyg';

    var editor = CKEDITOR.replace(replaceVar);

    CKEDITOR.editorConfig = function(config)
    {
        config.toolbarStartupExpanded = true;
        config.height = 400;
        config.FormatSource = false;
        config.FormatOutput = false;
        config.enterMode = 2;
        config.width = width;

        config.skin = 'v2';

        config.filebrowserBrowseUrl = '/ckfinder/ckfinder.html';
        config.filebrowserImageBrowseUrl = '/ckfinder/ckfinder.html?Type=Images';
        config.filebrowserFlashBrowseUrl = '/ckfinder/ckfinder.html?Type=Flash';
        config.filebrowserUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
        config.filebrowserImageUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
        config.filebrowserFlashUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';

        config.contentsCss = '/style/master_syntive.css';

        config.fullPage = false;

//        config.extraPlugins = 'imagewidget';

//        config.toolbar = 'Basic';
        CKEDITOR.config.toolbar = [
         //  ['Styles','Format','Font','FontSize'],
           ['Font','FontSize'],
           '/',
           ['Bold','Italic','Underline','StrikeThrough','-','Undo','Redo','-','Cut','Copy','Paste','Find','Replace','-','Outdent','Indent','-','Print'],
           '/',
           ['NumberedList','BulletedList','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
        //   ['Image','Table','-','Link','Flash','Smiley','TextColor','BGColor','Source']
           ['Image','Table','-','Link','Smiley','TextColor','BGColor','Source']
//           ,
//           '/',
//           ['imagewidget']
        ];
    };
}

function getBasicWys(replaceVar)
{
    CKEDITOR.config.startupMode = 'wysiwyg';

    var editor = CKEDITOR.replace(replaceVar);

    CKEDITOR.editorConfig = function(config)
    {
        config.toolbarStartupExpanded = true;
        config.height = 400;
        config.FormatSource = false;
        config.FormatOutput = false;
        config.enterMode = 2;

        config.skin = 'v2';

        config.filebrowserBrowseUrl = '/ckfinder/ckfinder.html';
        config.filebrowserImageBrowseUrl = '/ckfinder/ckfinder.html?Type=Images';
        config.filebrowserFlashBrowseUrl = '/ckfinder/ckfinder.html?Type=Flash';
        config.filebrowserUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
        config.filebrowserImageUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
        config.filebrowserFlashUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';

        config.contentsCss = '/style/master_syntive.css';

        config.fullPage = false;

//        config.extraPlugins = 'imagewidget';

//        config.toolbar = 'Basic';
        CKEDITOR.config.toolbar = [
         //  ['Styles','Format','Font','FontSize'],
           ['Font','FontSize'],
           '/',
           ['Bold','Italic','Underline','StrikeThrough','-','Undo','Redo','-','Cut','Copy','Paste','Find','Replace','-','Outdent','Indent','-','Print'],
           '/',
           ['NumberedList','BulletedList','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
        //   ['Image','Table','-','Link','Flash','Smiley','TextColor','BGColor','Source']
           ['Image','Table','-','Link','Smiley','TextColor','BGColor','Source']
//           ,
//           ['imagewidget']
        ];
    };
}


//$('.jquery_ckeditor').ckeditor(config);
//var editor = $('.jquery_ckeditor').ckeditorGet();
//CKFinder.SetupCKEditor(editor, '../../');

function getWysSource(replaceVar)
{
    CKEDITOR.config.startupMode = 'source';

    var editor = CKEDITOR.replace(replaceVar);

    // fetch data from the editor
    //alert(CKEDITOR.instances.page_content.getData());

    // update the data in the editor
    //CKEDITOR.instances.page_content.setData("Larry Was Here");

    CKEDITOR.editorConfig = function(config)
    {
        config.toolbarStartupExpanded = true;
        config.height = 400;
        config.FormatSource = false;
        config.FormatOutput = false;
        config.enterMode = 2;

        config.skin = 'v2';

        config.filebrowserBrowseUrl = '/ckfinder/ckfinder.html';
        config.filebrowserImageBrowseUrl = '/ckfinder/ckfinder.html?Type=Images';
        config.filebrowserFlashBrowseUrl = '/ckfinder/ckfinder.html?Type=Flash';
        config.filebrowserUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
        config.filebrowserImageUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
        config.filebrowserFlashUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';

        config.contentsCss = '/style/master_syntive.css';

        config.fullPage = false;

        //config.toolbar = 'Basic';
        /*
        CKEDITOR.config.toolbar = [
           ['Styles','Format','Font','FontSize'],
           '/',
           ['Bold','Italic','Underline','StrikeThrough','-','Undo','Redo','-','Cut','Copy','Paste','Find','Replace','-','Outdent','Indent','-','Print'],
           '/',
           ['NumberedList','BulletedList','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
           ['Image','Table','-','Link','Flash','Smiley','TextColor','BGColor','Source']
        ];
        */
    };
}

function getWysSourceWithWidth(replaceVar, width)
{
    CKEDITOR.config.startupMode = 'source';

    var editor = CKEDITOR.replace(replaceVar);

    // fetch data from the editor
    //alert(CKEDITOR.instances.page_content.getData());

    // update the data in the editor
    //CKEDITOR.instances.page_content.setData("Larry Was Here");

    CKEDITOR.editorConfig = function(config)
    {
        config.toolbarStartupExpanded = true;
        config.height = 400;
        config.FormatSource = false;
        config.FormatOutput = false;
        config.enterMode = 2;
        config.width = width;
        config.skin = 'v2';

        config.filebrowserBrowseUrl = '/ckfinder/ckfinder.html';
        config.filebrowserImageBrowseUrl = '/ckfinder/ckfinder.html?Type=Images';
        config.filebrowserFlashBrowseUrl = '/ckfinder/ckfinder.html?Type=Flash';
        config.filebrowserUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
        config.filebrowserImageUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
        config.filebrowserFlashUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';

        config.contentsCss = '/style/master_syntive.css';

        config.fullPage = false;

        //config.toolbar = 'Basic';
        /*
        CKEDITOR.config.toolbar = [
           ['Styles','Format','Font','FontSize'],
           '/',
           ['Bold','Italic','Underline','StrikeThrough','-','Undo','Redo','-','Cut','Copy','Paste','Find','Replace','-','Outdent','Indent','-','Print'],
           '/',
           ['NumberedList','BulletedList','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
           ['Image','Table','-','Link','Flash','Smiley','TextColor','BGColor','Source']
        ];
        */
    };
}

function getWys(replaceVar)
{
    CKEDITOR.config.startupMode = 'wysiwyg';

    var editor = CKEDITOR.replace(replaceVar);

    // fetch data from the editor
    //alert(CKEDITOR.instances.page_content.getData());

    // update the data in the editor
    //CKEDITOR.instances.page_content.setData("Larry Was Here");

    CKEDITOR.editorConfig = function(config)
    {
        config.toolbarStartupExpanded = false;
        config.height = 400;
        config.FormatSource = false;
        config.FormatOutput = false;
        config.enterMode = 2;

        config.skin = 'v2';

        config.filebrowserBrowseUrl = '/ckfinder/ckfinder.html';
        config.filebrowserImageBrowseUrl = '/ckfinder/ckfinder.html?Type=Images';
        config.filebrowserFlashBrowseUrl = '/ckfinder/ckfinder.html?Type=Flash';
        config.filebrowserUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
        config.filebrowserImageUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
        config.filebrowserFlashUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';

        config.contentsCss = '/style/master_syntive.css';

        config.fullPage = false;

        //config.toolbar = 'Basic';
        /*
        CKEDITOR.config.toolbar = [
           ['Styles','Format','Font','FontSize'],
           '/',
           ['Bold','Italic','Underline','StrikeThrough','-','Undo','Redo','-','Cut','Copy','Paste','Find','Replace','-','Outdent','Indent','-','Print'],
           '/',
           ['NumberedList','BulletedList','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
           ['Image','Table','-','Link','Flash','Smiley','TextColor','BGColor','Source']
        ];
        */
    };
}

function destroyWys()
{
    // remove editor from the page
    //$('#page_content').ckeditor(function()
    //{
    //    this.destroy();
    //});

    CKEDITOR.instances.page_content.destroy();
}

$(document).ready(
function()
{
    $(".draggable").draggable(
    {
        //	use a helper-clone that is append to 'body' so is not 'contained' by a pane
        helper: function() { return $(this).clone().appendTo('body').css('zIndex', 5).show(); },
        cursor: 'move'
    });
});

// fancybox images
$(document).ready(
function()
{
    $(".productImage").live('click',
    function()
    {
        $.fancybox({
            'orig': $(this),
            'padding': 0,
            'href': $(this).attr("href"),
            'transitionIn': 'elastic',
            'transitionOut': 'elastic'
        });
        return false;
    });
});


// Side Panel Editor
function createPanelContent(panelId)
{
    if (panelId > 0)
    {
        $('#panel_id_' + panelId).val(panelId);
        $('#panel_action_' + panelId).val("create");

        // Put the wysi content into the form for delivery
        if (CKEDITOR.instances['panelContent_' + panelId] != null)
        {
            $('#panelContent_' + panelId).val(CKEDITOR.instances['panelContent_' + panelId].getData());
        }
        
        formdata = $('#panel_content_form_' + panelId).serialize();

        //alert('formdata = ' + formdata);

        $.ajax(
        {
            type: "POST",
            url: "/index.php?q=content&action=createPanel&pagePanelId=" + panelId,
            data: formdata,
            success: function(data)
            {
                //$('#pagePanelContent').html(data.response);
                window.location = window.location.href;
            }
        });
    }
}

function savePanelContent(panelId)
{
    if (panelId > 0)
    {
        $('#panel_id_' + panelId).val(panelId);
        $('#panel_action_' + panelId).val("save");

        // Put the wysi content into the form for delivery
        if (CKEDITOR.instances['panelContent_' + panelId] != null)
        {
            $('#panelContent_' + panelId).val(CKEDITOR.instances['panelContent_' + panelId].getData());
        }

        formdata = $('#panel_content_form_' + panelId).serialize();

        //alert('formdata = ' + formdata);

        $.ajax(
        {
            type: "POST",
            url: "/index.php?q=content&action=savePanel&pagePanelId=" + panelId,
            data: formdata,
            success: function(data)
            {
                //$('#pagePanelContent').html(data.response);
                window.location = window.location.href;
            }
        });
    }
}

function cancelPanelContent(panelId)
{
    window.location = window.location.href;
}

function deletePanelContent(panelId)
{
    if (confirm('Are you sure you would like to delete this panel?'))
    {
        if (panelId > 0)
        {
            $('#panel_id_' + panelId).val(panelId);
            $('#panel_action_' + panelId).val("delete");

            // Put the wysi content into the form for delivery
            if (CKEDITOR.instances['panelContent_' + panelId] != null)
            {
                $('#panelContent_' + panelId).val(CKEDITOR.instances['panelContent_' + panelId].getData());
            }

            formdata = $('#panel_content_form_' + panelId).serialize();

            //alert('formdata = ' + formdata);

            $.ajax(
            {
                type: "POST",
                url: "/index.php?q=content&action=deletePanel&pagePanelId=" + panelId,
                data: formdata,
                success: function(data)
                {
                    //$('#pagePanelContent').html(data.response);
                    window.location = window.location.href;
                }
            });
        }
    }
}

$(function()
{
    $("ul.sub li").hover(
        function()
        {
            $(this).addClass("hover");
            $('ul:first',this).css('visibility', 'visible');
        },
        function()
        {
            $(this).removeClass("hover");
            $('ul:first',this).css('visibility', 'hidden');
        }
    );

    $("ul.sub li ul li:has(ul)").find("a:first").append(" &raquo; ");
});

function enablePageEdit()
{
    // TODO: show ADD button functionality over editable zones

    $("div.edit_content").hover(
        function()
        {
            $(this).addClass("hover");
            addEditHover($(this));
        },
        function()
        {
            $(this).removeClass("hover");
            removeEditHover($(this));
        }
    );
    isPageEditEnabled = true;   
    $('#adminEditPageContentButton').text("Leave Edit Mode");
}

function disablePageEdit()
{
    // TODO: if in wys edit mode, ask if ok to abandon edit session

    $("div.edit_content").unbind('mouseenter mouseleave');
    isPageEditEnabled = false;
    $('#adminEditPageContentButton').text("Edit Page Content");
}

function addEditHover(panel)
{
    var thisId = $(panel).attr('id');

    // Make sure there are not already other edit control boxes
    $("#editControlBox").remove();
    
    //var editOnClick = "editContentPanel(\"" + thisId + "\");return false;";
    var $controlBox = $('<span/>').attr('id', 'editControlBox').addClass("editControlBox");
    var $editButton = $('<input/>').attr({ type: 'button', id: 'editPanelButton', name: 'editPanelButton', value: 'Edit', title: 'Edit this content panel'}).addClass("edit_button");

    $controlBox.append($editButton);
    $(panel).prepend($controlBox);

    $('#editPanelButton').click(function()
    {
        editContentPanel(thisId);
    });
}

function removeEditHover(panel)
{
    $("#editControlBox").remove();
}


function editContentPanel(panel)
{
    editPageContent(panel);
}

function editPageContent(id)
{
    indicateAjaxRequest($("#" + id));

    // remove prefix "contentId_"
    //var panelId = id.replace("contentId_", "");
    
    //panelId = panelId.replace("contentId_", "");

    if (false)
    {
        // TEST: replace div
        var $mainBox = $('<div/>').attr('id', 'editPanelMain');
        var $headerBox = $('<div/>').attr('id', 'editPanelHeader').text('header');
        var $bodyBox = $('<div/>').attr('id', 'editPanelBody').text('body');
        var $footerBox = $('<div/>').attr('id', 'editPanelFooter').text('footer');

        $mainBox.append($headerBox);
        $mainBox.append($bodyBox);
        $mainBox.append($footerBox);

        $("#" + id).replaceWith($mainBox);

        var $newEditBox = $('<div/>').attr('id', id);
        $bodyBox.append($newEditBox);
    }


    getContentWys(id);

    $(document).ready(function()
    {
        $.getJSON('/index.php?q=content&action=contentPanel&contentPanelId=' + id,
        function(data)
        {
            CKEDITOR.instances[id].updateElement();
            CKEDITOR.instances[id].setData(data.data);

            indicateAjaxComplete($("#" + id));

            // Append button to wys footer
            if (true)
            {
                var saveOnClick = "saveContentPanel(\"" + id + "\");return false;";
                var deleteOnClick = "deleteContentPanel(\"" + id + "\");return false;";
                var cancelOnClick = "cancelContentPanel(\"" + id + "\");return false;";
                
                var $wysControlBox = $('<span/>').attr('id', 'wysControlBox').addClass("wysControlBox");

                var $savePanelButton = $('<input/>').attr({ type: 'button', id: 'savePanelButton', name: 'savePanelButton', value: 'Save', onclick: saveOnClick, title: 'Save this panel'}).addClass("save_button");
                var $deletePanelButton = $('<input/>').attr({ type: 'button', id: 'deletePanelButton', name: 'deletePanelButton', value: 'Delete', onclick: deleteOnClick, title: 'Delete this panel'}).addClass("save_button");
                var $cancelPanelButton = $('<input/>').attr({ type: 'button', id: 'cancelPanelButton', name: 'cancelPanelButton', value: 'Cancel', onclick: cancelOnClick, title: 'Cancel changes to this panel'}).addClass("save_button");

                $wysControlBox.append($cancelPanelButton);
                $wysControlBox.append($deletePanelButton);
                $wysControlBox.append($savePanelButton);

                // TODO: if content exists, add save and delete buttons, otherwise add create button
                //$("#" + panelId).parent().append($wysControlBox);

                if ($.browser.msie)
                {
                    // TODO: FIX THIS, this should be added below the wys in IE
                    $(".cke_bottom").append($wysControlBox);
                }
                else
                {
                    $(".cke_bottom").parent().after($wysControlBox);
                }

                // Include header box
                if (true)
                {
                    $("#wysHeaderBox").remove();
                    var $wysHeaderBox = $('<span/>').attr('id', 'wysHeaderBox').addClass("wysHeaderBox");

                    var $wysTitleLabel = $('<label/>').attr({ 'for': 'wysTitle'}).text("Title: ").addClass("inlineLabel");
                    var $wysTitle = $('<input/>').attr({ type: 'text', id: 'wysTitle', name: 'wysTitle', value: data.title});
                    //$wysHeaderBox.append($wysTitleLabel);
                    //$wysHeaderBox.append($wysTitle);

                    var $wysFieldset = $('<fieldset/>').addClass("togglefieldset");
                    var $wysLegend = $('<legend/>').addClass("toggleheading");
                    var $wysToggleAnchor = $('<a/>').attr({ id: 'toggleAnchor',  'href': '', 'title': "toggle"}).text("Panel Settings");
                    var $wysToggleDiv = $('<div/>').addClass("togglecontent");

                    $wysToggleDiv.append($wysTitleLabel);
                    $wysToggleDiv.append($wysTitle);

                    //$wysHeaderBox.append($wysTitleLabel);
                    //$wysHeaderBox.append($wysTitle);
                    

                    $wysLegend.append($wysToggleAnchor);
                    $wysFieldset.append($wysLegend);
                    $wysFieldset.append($wysToggleDiv);
                    
                    $wysHeaderBox.append($wysFieldset);

                    $wysLegend.addClass("toggleheading");
                    
                    $wysToggleDiv.hide();
                    $wysToggleAnchor.click(function()
                    {
                        $wysToggleDiv.slideToggle(300);
                        return false;
                    });

                    $("#cke_" + id).before($wysHeaderBox);
                }

                $("#savePanelButton").click(function()
                {
                    saveContentPanel(id);
                    return false;
                });
                $("#deletePanelButton").click(function()
                {
                    deleteContentPanel(id);
                    return false;
                });
                $("#cancelPanelButton").click(function()
                {
                    cancelContentPanel(id);
                    return false;
                });
            }

            disablePageEdit();
        });
    });
}


function saveContentPanel(contentId)
{
    CKEDITOR.instances[contentId].updateElement();
    var contentData = CKEDITOR.instances[contentId].getData();

    //alert("data = " + contentData);

    var id = contentId.replace("contentId_", "");

    var action = "savePanel";

    var contentIdPrefix = contentId.substr(0, 10);
    if (contentIdPrefix == "contentId_")
    {
        action = "saveContentTest";
    }

    var editForm = $('<form/>').attr({ action: action, id: 'editContentForm', name: 'editContentForm', method: 'post'});
    var editContentField = $('<input/>').attr({ type: 'hidden', id: 'editContentData', name: 'editContentData', value: contentData});
    editForm.append(editContentField);


    var pageName = window.location.pathname;

    var editPageField = $('<input/>').attr({ type: 'hidden', id: 'editPageName', name: 'editPageName', value: pageName});
    editForm.append(editPageField);


    var pageTitle = $("#wysTitle").val();

    var editPageTitle = $('<input/>').attr({ type: 'hidden', id: 'editPageTitle', name: 'editPageTitle', value: pageTitle});
    editForm.append(editPageTitle);


    //$("#" + contentId).prepend($editForm);
    //formdata = $('#editContentForm').serialize();

    // NOTE: serialize without adding to page
    var formdata = editForm.serialize();

    $.ajax(
    {
        type: "POST",
        url: "/index.php?q=content&action=" + action + "&pagePanelId=" + id,
        data: formdata,
        success: function(data)
        {
            //$('#pagePanelContent').html(data.response);
            //window.location = window.location.href;

            $("#wysHeaderBox").remove();

            destroyContentWys(contentId);

            // TODO: replace wys with saved content
            $('#' + contentId).html(data.response);

            enablePageEdit();
        }
    });
}

function deleteContentPanel(contentId)
{
    var id = contentId.replace("contentId_", "");

    var action = "deletePanel";

    var contentIdPrefix = contentId.substr(0, 10);
    if (contentIdPrefix == "contentId_")
    {
        action = "deleteContent";
    }

    $.getJSON('/index.php?q=content&action=' + action + '&contentPanelId=' + id,
    function(data)
    {
        var content = data.data;

        indicateAjaxComplete($("#" + contentId));
        $("#wysHeaderBox").remove();

        destroyContentWys(contentId);

        // reload content
        $(contentId).val(content);

        enablePageEdit();
    });
}

function cancelContentPanel(contentId)
{
    $.getJSON('/index.php?q=content&action=getContent&contentPanelId=' + contentId,
    function(data)
    {
        var content = data.response;

        indicateAjaxComplete($("#" + contentId));
        $("#wysHeaderBox").remove();

        destroyContentWys(contentId);

        $('#' + contentId).html(content);

        enablePageEdit();
    });
}

function getContentWys(panelId)
{
    CKEDITOR.config.startupMode = 'source';

    $("#" + panelId).html("");

    CKEDITOR.replace(panelId);
    CKEDITOR.instances[panelId].setData("");

    indicateAjaxRequest($("#" + panelId));
    $("#" + panelId).show();


    //CKEDITOR.instances[panelId].updateElement();
    //CKEDITOR.instances[panelId].setData("");

    CKEDITOR.editorConfig = function(config)
    {
        config.toolbarStartupExpanded = false;
        config.height = 400;
        config.FormatSource = false;
        config.FormatOutput = false;
        config.enterMode = 2;

        config.skin = 'v2';

        config.filebrowserBrowseUrl = '/ckfinder/ckfinder.html';
        config.filebrowserImageBrowseUrl = '/ckfinder/ckfinder.html?Type=Images';
        config.filebrowserFlashBrowseUrl = '/ckfinder/ckfinder.html?Type=Flash';
        config.filebrowserUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
        config.filebrowserImageUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
        config.filebrowserFlashUploadUrl = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';

        config.contentsCss = '/style/synthesis/master.css';

        config.fullPage = false;

        //config.toolbar = 'Basic';
        /*
        CKEDITOR.config.toolbar = [
           ['Styles','Format','Font','FontSize'],
           '/',
           ['Bold','Italic','Underline','StrikeThrough','-','Undo','Redo','-','Cut','Copy','Paste','Find','Replace','-','Outdent','Indent','-','Print'],
           '/',
           ['NumberedList','BulletedList','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
           ['Image','Table','-','Link','Flash','Smiley','TextColor','BGColor','Source']
        ];
        */
    };

    // Append control box to page (buggy)
    if (false)
    {
        var saveOnClick = "saveContentPanel(\"" + panelId + "\");return false;";
        var deleteOnClick = "deleteContentPanel(\"" + panelId + "\");return false;";
        var cancelOnClick = "cancelContentPanel(\"" + panelId + "\");return false;";

        var $wysControlBox = $('<span/>').attr('id', 'wysControlBox').addClass("wysControlBox");

        var $savePanelButton = $('<input/>').attr({ type: 'button', id: 'savePanelButton', name: 'savePanelButton', value: 'Save', onclick: saveOnClick}).addClass("save_button");
        var $deletePanelButton = $('<input/>').attr({ type: 'button', id: 'deletePanelButton', name: 'deletePanelButton', value: 'Delete', onclick: deleteOnClick}).addClass("save_button");
        var $cancelPanelButton = $('<input/>').attr({ type: 'button', id: 'cancelPanelButton', name: 'cancelPanelButton', value: 'Cancel', onclick: cancelOnClick}).addClass("save_button");

        $wysControlBox.append($cancelPanelButton);
        $wysControlBox.append($deletePanelButton);
        $wysControlBox.append($savePanelButton);

        // TODO: if content exists, add save and delete buttons, otherwise add create button
        $("#" + panelId).parent().append($wysControlBox);
        //$("#" + panelId).after($wysControlBox);
        //$("#" + panelId).append($wysControlBox);
        //$(".cke_bottom").parent().append($wysControlBox);

        $("#savePanelButton").click(function()
        {
            saveContentPanel(panelId);
            return false;
        });
        $("#deletePanelButton").click(function()
        {
            deleteContentPanel(panelId);
            return false;
        });
        $("#cancelPanelButton").click(function()
        {
            cancelContentPanel(panelId);
            return false;
        });
    }

    indicateAjaxComplete($("#" + panelId));

    $('#savePanelButton').click(
    function()
    {
        saveContentPanel(panelId);
    });
    $('#deletePanelButton').click(
    function()
    {
        deleteContentPanel(panelId);
    });
    $('#cancelPanelButton').click(
    function()
    {
        cancelContentPanel(panelId);
    });
}

function destroyContentWys(panelId)
{
    CKEDITOR.instances[panelId].updateElement();
    CKEDITOR.instances[panelId].destroy();

    // remove control box
    $("#wysControlBox").remove();

    $("#" + panelId).removeClass("neutral");
    $("#" + panelId).removeClass("hover");
}

// Initialize internal page panel dialog
function initPagePanelDialog()
{
    $('#editPagePanelDialog').dialog({ autoOpen: false, width: 320, modal: true });
    $('#pagePanelDialogCancelButton').click(
        function ()
        {
            // if error is displayed, refresh page
            if ($('.ui-state-error').length > 0)
            {
                cancelPagePanel(0);
            }

            // otherwise, just close the dialog without the roundtrip
            $('#editPagePanelDialog').dialog('close');
        }
    );

    $('#editPagePanelDialog').bind('dialogclose', function(event, ui) {
        $('#newPagePanelbutton').show();
    });
}

function fetchPagePreferences()
{
    //var pageId = $("#pageId").val();

    var bodyId = $("body").attr("id");
    var pageId = bodyId.replace("pid_", "");

    //indicateAjaxRequest($("#pagePreferencesDialogContent"));

    $(document).ready(
    function()
    {
        $.getJSON('/index.php?q=content&action=getPagePreferences&pageId=' + pageId,
        function(data)
        {
            $('#pagePreferencesDialogContent').html(data.data);

            $('#pagePreferencesDialogContent').append("<input type=\"hidden\" id=\"currentPageId\" value=\"" + pageId + "\" />\n");

            initPagePanelDialog();

            //indicateAjaxComplete($("#pagePreferencesDialogContent"));
        });
    });
}

// Page panel script
function editPagePanel(id)
{
    $('#newPagePanelbutton').hide();
    
    $('#editPagePanelDialog').dialog('option', 'title', 'Edit PagePanel');
    $('#editPagePanelDialog').show();
    $('#pagePanelDialogSubmitButton').val('Save');
    $('#formAction').val('edit');

    $.getJSON('/index.php?q=pagePanel&action=pagePanel&pagePanelId=' + id,
    function(data)
    {
        $('#dialogpagePanelId').val(data.id);
        $('#id').val(data.id);
        $('#pageId').val(data.pageId);
        $('#panelId').val(data.panelId);
        $('#location').val(data.location);
        $('#viewOrder').val(data.viewOrder);
        $('#panelVisibility').val(data.visibility);
        $('#status').val(data.status);
        $('#template').val(data.template);
    });

    if ($('.ui-state-error').length > 0)
    {
        $('#editPagePanelDialog').dialog('option', 'position', 'bottom');
    }

    $('#editPagePanelDialog').dialog('open');
}


function deletePagePanel(id)
{
    if (confirm('Are you sure you would like to delete this PagePanel?'))
    {
        $('#pagePanelId').val(id);
        $('#formAction').val('delete');


        pageId = 0;
        if ($('#pageId').length > 0)
        {
            pageId = $('#pageId').val();
        }

        formdata = $('#dialogPagePanelForm').serialize();

        $.ajax({
            type: "POST",
            url: "/index.php?q=pagepanel&action=delete&pagePanelId=" + id + "&pageId=" + pageId,
            data: formdata,
            success: function(data)
            {
                $('#pagePanelContent').html(data.response);
            }
        });
    }
}

function savePagePanel(id)
{
    $('#pagePanelId').val(id);
    $('#formAction').val('save');

    pageId = null;
    if ($('#pageId').length > 0)
    {
        pageId = $('#pageId').val();
    }

    formdata = $('#dialogPagePanelForm').serialize();

    //alert('formdata = ' + formdata);

    $.ajax({
        type: "POST",
        url: "/index.php?q=pagepanel&action=save&pagePanelId=" + id + "&pageId=" + pageId,
        data: formdata,
        success: function(data)
        {
            $('#pagePanelContent').html(data.response);
        }
    });
}

function cancelPagePanel(id)
{
    $('#pagePanelId').val('');
    $('#pagePanelAction').val('');
    $('#pagePanelForm').submit();
}

function saveDialog()
{
    //if ($('#dialogPagePanelForm').validate().form())
    //{
        id = $('#dialogpagePanelId').val();

        savePagePanel(id);

        $('#editPagePanelDialog').dialog('close');
    //}
}

function newPagePanelClick()
{
    $('#newPagePanelbutton').hide();
    $('#editPagePanelDialog').dialog('option', 'title', 'Create New PagePanel');
    $('#pagePanelDialogSubmitButton').val('Create');
    $('#formAction').val('create');

    // blank all values
    $('#id').val('');
    $('#dialogpagePanelId').val('');
    currentPageId = $('#currentPageId').val();
    $('#pageId').val(currentPageId);
    $('#panelId').val('');
    $('#location').val('');
    $('#viewOrder').val('');
    $('#panelVisibility').val('');
    $('#status').val('');
    $('#template').val('');
    $('#editPagePanelDialog').dialog('open');
}

$(document).ready(
function()
{
    $('#editPagePanelDialog').dialog({ autoOpen: false, width: 320 });

    $('#pagePanelDialogCancelButton').click(
        function ()
        {
            // if error is displayed, refresh page
            if ($('.ui-state-error').length > 0)
            {
                cancelPagePanel(0);
            }

            // otherwise, just close the dialog without the roundtrip
            $('#editPagePanelDialog').dialog('close');
        }
    );

    $('#editPagePanelDialog').bind('dialogclose', function(event, ui) {
        $('#newPagePanelbutton').show();
        //$('#dialogPagePanelForm').validate().resetForm();
    });

});


function zeroPad(number, width)
{
    width -= number.toString().length;
    if (width > 0)
    {
        return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number;
    }
    return number;
}

function impersonateUser(userId)
{
    if (confirm('Are you sure you would like to impersonate this user?'))
    {
        $.ajax(
        {
            type: "GET",
            url: "/index.php?q=users&action=impersonate&item=" + userId,
            success: function(data)
            {
                window.location = window.location;
            }
        });
    }
}

function changeSubdomain()
{
    var subdomain = $('#accountSubdomain').val();
    var path = window.location.pathname;
    $.ajax(
    {
        type: "GET",
        url: "/index.php?q=gocode&action=setSession&subdomain=" + subdomain,
        success: function(data)
        {
            var url = data;
//            window.location = url + path;
            window.location = url + '/dashboard/';
        }
    });
}

function validateBillingInfo()
{
    var isValid = true;

    // TODO: better validation

    return isValid;
}

function pickBillingState()
{
    var billingState = $('#x_state').val();
    $.ajax(
    {
        type: "GET",
        url: "/index.php?q=cart&action=calculate_tax&state=" + billingState,
        success: function(data)
        {
            $(".tableWrapper").html(data.response);
        }
    });
}

function enterPromoCode()
{
    var promoCode = $('#promo_code').val();
    $.ajax(
    {
        type: "GET",
        url: "/index.php?q=cart&action=add_promo_code&code=" + promoCode,
        success: function(data)
        {
            $(".tableWrapper").html(data.response);

            if (data != null && data.message != null && data.message.length > 0)
            {
                alert(data.message);
            }
        }
    });
}

/*
$(function()
{
    // Style all buttons using jquery ui
    //$("input:submit, button, input:button").button();
});
*/

function changePageTemplate()
{
    var pageTemplate = $("#pageTemplate").val();

    alert("pageTemplate = " + pageTemplate);
    // TODO: persist using ajax call
}

/* create some customer formatters for jqgrid */
FormatterLink = function(cellvalue, options, rowObject)
{
    return "<a href=\"/" + cellvalue + "\">" + cellvalue + "</a>";
}

function getWishlist()
{
    $.ajax(
    {
        type: "GET",
        url: "/index.php?q=cart&action=create_wishlist",
        success: function(data)
        {
            var $dialog = $('<div></div>')
                .html('Wishlist URL: <input type="text" id="wishlistDialog" value="/cart/wishlist/' +  data.wishlist + '" />')
                .dialog(
                {
                    autoOpen: false,
                    title: 'Wishlist'
                });

            $dialog.dialog('open');
        }
    });
}


// TESTING DRAG SORTING OF SIDE PANELS
/*
$(function()
{
    $("#rightcontent").sortable(
    {
        items: ".editbox",
        opacity: 0.6,
        axis: 'y',
        containment: 'parent',
        update: function(event, ui)
        {
            var order = [];
            $('#rightcontent .editbox').each( function(e)
            {
                var fieldId = $(this).attr('id');
                if (fieldId != "formManagerFormInfo")
                {
                    order.push(fieldId);
                }
            });
            var sortOrder = order.join(',')

            alert(sortOrder);
        }
    });

    //$("#formManagerFieldList").disableSelection();
});
*/

function loginAuthorizationCheck()
{
    var data = $('#loginForm').serialize();
    var myurl = "http"+':'+'//';
    $.ajax({
        type: "POST",
        data: data,
        url: "/index.php?q=login&action=LOGIN_AUTHORIZE_CHECK",
        success: function(data)
        {
            if (data.destination != null && data.destination != "")
            {
                window.location=data.destination;
            }
            else
            {
                alert("Incorrect username or password.");
            }
        }
    });
}

$(function()
{
    $('.milestone_date').datepicker();
});

function setMilestone(id)
{
    var dateFieldId = id + "_date";
    var timeFieldId = id + "_time";

    var timenow = new Date();

    var formatdate = dateFormat(timenow, 'mm/d/yyyy');
    var formattime = dateFormat(timenow, 'hh:MM TT');
    $("#" + dateFieldId).val(formatdate);
    $("#" + timeFieldId).val(formattime)
}

function saveMilestone(id)
{
    var itemId = $("#customerId").val();

    if (itemId != "")
    {
        var milestoneDate = $('#' + id + '_date').val();
        var milestoneTime = $('#' + id + '_time').val();

        var milestonePieces = id.split('_');

        var itemScope = milestonePieces[1];
        var title = milestonePieces[2];

        var milestoneDateTime = new Date(milestoneDate + " " + milestoneTime);

        $.ajax(
        {
            type: "GET",
            url: "/index.php?q=serviceevent&action=milestone_save&itemId=" + itemId + '&itemScope=' + itemScope + '&title=' + title +'&date=' + milestoneDateTime,
            success: function(data)
            {
                //$(".tableWrapper").html(data.response);

                if (data != null && data.message != null && data.message.length > 0)
                {
                    alert(data.message);
                }
            }
        });
    }
}

function saveServiceEventMilestone(id, itemId, itemScope)
{
    if (itemId != "")
    {
        var milestoneDate = $('#' + id + '_date').val();
        var milestoneTime = $('#' + id + '_time').val();

        var milestonePieces = id.split('_');

        //var itemScope = milestonePieces[0];
        var title = milestonePieces[1];

        var milestoneDateTime = new Date(milestoneDate + " " + milestoneTime);

        $.ajax(
        {
            type: "GET",
            url: "/index.php?q=serviceevent&action=milestone_save&itemId=" + itemId + '&itemScope=' + itemScope + '&title=' + title +'&date=' + milestoneDateTime,
            success: function(data)
            {
                if (data != null && data.message != null && data.message.length > 0)
                {
                    alert(data.message);
                }
            }
        });
    }
}


function saveServiceEventMilestone(id, itemId, itemScope, title, date)
{
    if (itemId != "")
    {
        var formatdate = dateFormat(date, 'mm/d/yyyy hh:MM TT');

        $.ajax(
        {
            type: "GET",
            url: "/index.php?q=serviceevent&action=milestone_save&itemId=" + itemId + '&itemScope=' + itemScope + '&title=' + title +'&date=' + formatdate,
            success: function(data)
            {
                if (data != null && data.message != null && data.message.length > 0)
                {
                    alert(data.message);
                }
            }
        });
    }
}


function getMilestone(itemId, id)
{
    if (itemId != "")
    {
        var milestonePieces = id.split('_');

        var itemScope = milestonePieces[1];
        var title = milestonePieces[2];
        
        $.ajax(
        {
            type: "GET",
            url: "/index.php?q=serviceevent&action=milestone&itemId=" + itemId + '&itemScope=' + itemScope + '&title=' + title,
            success: function(data)
            {
                indicateAjaxComplete($("#" + id + "_date"));
                indicateAjaxComplete($("#" + id + "_time"));

                if (data != null && data.milestoneDate != null)
                {
                    var milestoneDate = Date.parse(data.milestoneDate.replace(/-/g, "/"));

                    var formatdate = dateFormat(milestoneDate, 'mm/dd/yyyy');
                    var formattime = dateFormat(milestoneDate, 'hh:MM TT');

                    //alert("formatdate = " + formatdate);
                    //alert("formattime = " + formattime);

                    $("#" + id + "_date").val(formatdate);
                    $("#" + id + "_time").val(formattime);
                }

                if (data != null && data.message != null && data.message.length > 0)
                {
                    alert(data.message);
                }
            }
        });
    }
}

//============DATE formatting code=======================================
var dateFormat = function() {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function(val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function(mask, utc)
{
    return dateFormat(this, mask, utc);
};

//============END of DATE formatting code======================================



//timeout = setTimeout(timeoutWarning, 10800000); // 3 hours
//timeout = setTimeout(timeoutWarning, 1000); // 1 second

function timeoutWarning()
{
    alert("Warning, your session has expired. Please copy your work before leaving the page.");
}

// checks if the value is only alphanumeric, dash and underscore
function checkAlphanumericUnderscoreDash(val)
{
    var alphanumericunderscoredash =  '([A-Za-z0-9\-\_]+)';
    if (val == null || val == '')
    {
        return false;
    }
    return alphanumericunderscoredash.test(val);
}

// checks if the value is only alphanumeric and underscore
function checkAlphanumericUnderscore(val)
{
    var alphanumericunderscore =  /^\w*$/;
    if (val == null || val == '')
    {
        return false;
    }
    return alphanumericunderscore.test(val);
}

// checks if the value is only alphanumeric and underscore
function checkAlphanumeric(val)
{
    var alphanumericunderscore =  '([A-Za-z0-9]+)';
    if (val == null || val == '')
    {
        return false;
    }
    return alphanumericunderscore.test(val);
}
