var xmlHttp;
var rootpath;
 
 
String.prototype.trimCommas = function () {
    return this.replace(/^,*/, "").replace(/,*$/, "");
}

var sortableListId;

function initSortableCRUD(sortableId)
{
    switch (sortableId) {
        case "iegsrquicklinks":
            sortableListId = 'quicklinks';
            break;
        default:
            break;
    }
}

function executeSortableCRUD(user)
{
	xmlHttp=GetXmlHttpObject(stateChanged);
	xmlHttp.open("GET", user , true);
	xmlHttp.send(null);
}

function submitSortOrder(sourceListType) {

	initSortableCRUD(sourceListType);
	
	//clean up the sorted list generated by script.aculo.us into a comma-separated string
	//using the new sequence method instead of cleaning up the serialize method output
	var sortOrder = Sortable.sequence(sortableListId).join(',');
	
	var url;
	switch (sourceListType){
	    case "iegsrquicklinks":
	        url = "/services/iegsr/IEGSR.aspx?method=PutQuickLinks&user=" + currentUser + "&quicklinksdata=" + sortOrder;
	        break;
	    default:
	        break;
	        }
	
	//alert(url);
	executeSortableCRUD(url);
}

function addSortableItem(sourceListType, sortableItemValue, sortableItemContent)
{
    //alert('initializing sortable CRUD');
	initSortableCRUD(sourceListType);

	//clean up the sorted list generated by script.aculo.us into a comma-separated string
	//using the new sequence method instead of cleaning up the serialize method output
	var sortOrder = Sortable.sequence(sortableListId).join(',');
	
    var sortOrder = new String(',' + Sortable.sequence(sortableListId).join(',') + ',');
	
    //find and remove the specified element
    //alert('testing for duplicate item');
    if (sortOrder.indexOf(',' + sortableItemValue + ',') < 0)
    {
        sortOrder += ',' + sortableItemValue;
    	
        //clean up the string for storage
        //trim
        sortOrder = sortOrder.trimCommas();
    	
        //replace consecutive delims
        sortOrder = sortOrder.replace(',,',',');
	
	
        var url;
        switch (sourceListType){
            case "iegsrquicklinks":
                //add a new node to the list container
                var tba = document.getElementById(sortableListId);
                var ja = document.createElement('div');
                ja.setAttribute('id','quicklink_' + sortableItemValue)
                ja.setAttribute('class','item');
                ja.innerHTML = '<a href="/IEGSR/Topics.aspx?categoryid=' + sortableItemValue + '">' + sortableItemContent + '</a>'+
                    '<a class="quicklinkshandle customizeQuicklinks" href="#" onclick="return false" style="width: 20px; font-size: .5em;"><img src="/images/iegsr/crosshair.gif" width="13" height="13" border="0" style="margin: 3px 1px 2px 0;" /></a>' + 
                    '<a class="quicklinksRemove customizeQuicklinks" href="#" onclick="removeSortableItem(\'iegsrquicklinks\', \'' + sortableItemValue + '\');return false;" style="width: 20px;">-</a>';
                tba.appendChild(ja);
                //alert(ja.innerHTML);
                //fix for ie not applying specified class to ja element
                document.getElementById('quicklink_' + sortableItemValue).className = "item";
                //rebuild sortable
                Sortable.create('quicklinks',{tag:'div', handles:$$('a.quicklinkshandle'),
                    onUpdate:function(){submitSortOrder('iegsrquicklinks', 'quicklinks', currentUser)} });
                url = "/services/iegsr/IEGSR.aspx?method=PutQuickLinks&user=" + currentUser + "&quicklinksdata=" + sortOrder;
                break;
            default:
                break;
        }
    	
        //alert(url);
        executeSortableCRUD(url);
        //alert('item added');
    }
    else
    {
        alert("That item is already in the list.");
    }
} 

function removeSortableItem(sourceListType, sortableItemValue)
{

	initSortableCRUD(sourceListType);

	//clean up the sorted list generated by script.aculo.us into a comma-separated string
	//using the new sequence method instead of cleaning up the serialize method output
	var sortOrder = new String(',' + Sortable.sequence(sortableListId).join(',') + ',');
	
	//alert('testing for existence of item');
	if (sortOrder.indexOf(',' + sortableItemValue + ',') >= 0)
	{
	    //find and remove the specified element
	    sortOrder = sortOrder.replace(',' + sortableItemValue + ',',',')
    	
	    //clean up the string for storage
	    //trim
	    sortOrder = sortOrder.trimCommas();
    	
	    //replace consecutive delims
	    sortOrder = sortOrder.replace(',,',',');
    	
    	
	    var url;
	    switch (sourceListType){
	        case "iegsrquicklinks":
	            //remove the node from the dom
	            var tbd = document.getElementById('quicklink_' + sortableItemValue);
	            tbd.parentNode.removeChild(tbd);
	            //and build the ajax command for the server
	            url = "/services/iegsr/IEGSR.aspx?method=PutQuickLinks&user=" + currentUser + "&quicklinksdata=" + sortOrder;
	            break;
	        default:
	            break;
	            }
    	
	    //now execute the ajax request
	    executeSortableCRUD(url);
	    //alert('item removed');
	}
	else
	{
	    //alert('item not present');
	}
} 

function stateChanged()
{
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    {
        var requestResponse=xmlHttp.responseText;
		if (requestResponse=="success") {
			return "success";
		} else {
			//alert("Sortable update failed: \n"+requestResponse);
			alert("Sorry, the change you just made couldn't be saved.  Please refresh the page and try again.");
		}
    }
}
 
function GetXmlHttpObject(handler)
{
    var objXmlHttp=null
 
    if (navigator.userAgent.indexOf("Opera")>=0)
    {
        alert("Opera not supported...");
        return;
    }
    if (navigator.userAgent.indexOf("MSIE")>=0)
    {
        var strName="Msxml2.XMLHTTP";
        if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
        {
            strName="Microsoft.XMLHTTP";
        }
        try
        {
            objXmlHttp=new ActiveXObject(strName);
            objXmlHttp.onreadystatechange=handler;
            return objXmlHttp;
        }
        catch(e)
        {
            alert("Error. Scripting for ActiveX might be disabled");
            return;
        }
    }
    if (navigator.userAgent.indexOf("Mozilla")>=0)
    {
        objXmlHttp=new XMLHttpRequest();
        objXmlHttp.onload=handler;
        objXmlHttp.onerror=handler;
        return objXmlHttp;
    }
} 
 
function showCustomizeQuicklinks()
{
    changecss('.customizeQuicklinks','visibility','visible');
    changecss('#leftNav .customizeQuicklinks','visibility','visible');
    changecss('.saveQuicklinks','visibility','hidden');
    changecss('#leftNav .saveQuicklinks','visibility','hidden');
}

function hideCustomizeQuicklinks()
{
    changecss('.saveQuicklinks','visibility','visible');
    changecss('#leftNav .saveQuicklinks','visibility','visible');
    changecss('.customizeQuicklinks','visibility','hidden');
    changecss('#leftNav .customizeQuicklinks','visibility','hidden');
}
