/* script specific admin js */

/* shortUrl Management Pages */
mfScripts.shortUrlsTable 				= {};
mfScripts.shortUrlsTable.oldPage 		= null;
mfScripts.shortUrlsTable.timeOutLoader 	= null;
mfScripts.shortUrlsTable.tableParams 	= null;

mfScripts.shortUrlsTable.updateShortUrlStatus = function(id, status)
{
    var postData = "id="+id+"&status="+status;
    var callback =
    {
        success: mfScripts.shortUrlsTable.handleUpdateSuccess,
        failure: mfScripts.shortUrlsTable.handleUpdateFailure
    };
    var sUrl = "ajax/updateShortUrlState.ajax.php";
    var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
}

mfScripts.shortUrlsTable.handleUpdateSuccess = function(o)
{
    if(o.responseText !== undefined)
    {
        mfScripts.shortUrlsTable.oldPage = mfScripts.shortUrlsTable.tablePager.getCurrentPage();
        mfScripts.shortUrlsTable.DynamicData();
    }
};

mfScripts.shortUrlsTable.updatePager = function()
{
    if(mfScripts.shortUrlsTable.oldPage != null)
    {
        mfScripts.shortUrlsTable.tablePager.setPage(mfScripts.shortUrlsTable.oldPage, true);
    }
    mfScripts.shortUrlsTable.oldPage = null;
};

mfScripts.shortUrlsTable.handleUpdateFailure = function(o)
{
    /* do something */
    };

mfScripts.shortUrlsTable.DynamicData = function() {
    var Dom = YAHOO.util.Dom,
    Event = YAHOO.util.Event;
		
    var formatUrl = function(elCell, oRecord, oColumn, sData) {
        elCell.innerHTML = "<a href='" + oRecord.getData("fullUrl") + "' title='" + oRecord.getData("fullUrl").replace( /'/g, '%27' ) + "' target='_blank'>" + sData + "</a>";
    };
	
    var formatStatus = function(elCell, oRecord, oColumn, sData) {
        var color = "red";
        if(sData == "active")
        {
            color = "green";
        }
        elCell.innerHTML = "<div class='urlStatus_"+color+"'>" + sData + "</div>";
    };
	
    var formatAction = function(elCell, oRecord, oColumn, sData) {
        var status = oRecord.getData("status");
        if(status == "active")
        {
            elCell.innerHTML = "<a href='" + oRecord.getData("fullUrl") + "' title='" + oRecord.getData("fullUrl").replace( /'/g, '%27' ) + "' target='_blank'>"+t("view")+"</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='#' onClick=\"mfScripts.shortUrlsTable.updateShortUrlStatus("+oRecord.getData("id")+", 'disabled'); return false;\">"+t("disable")+"</a>";
        }
        else
        {
            elCell.innerHTML = "<a href='" + oRecord.getData("fullUrl") + "' title='" + oRecord.getData("fullUrl").replace( /'/g, '%27' ) + "' target='_blank'>"+t("view")+"</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='#' onClick=\"mfScripts.shortUrlsTable.updateShortUrlStatus("+oRecord.getData("id")+", 'active'); return false;\">"+t("enable")+"</a>";
        }
    };

    var myColumnDefs = [
    {
        key:"shortUrl",
        label:"Short Url",
        sortable:true,
        formatter:formatUrl
    },

    {
        key:"dateCreated",
        label:"Date Created",
        sortable:true
    },

    {
        key:"visits",
        label:"Total Visits",
        formatter:YAHOO.widget.DataTable.formatNumber,
        sortable:true
    },

    {
        key:"createdIp",
        label:"Created IP",
        sortable:true
    },

    {
        key:"lastAccessed",
        label:"Last Accessed",
        sortable:true
    },

    {
        key:"status",
        label:"Status",
        formatter:formatStatus,
        sortable:true
    },

    {
        key:"actions",
        label:"Actions",
        formatter:formatAction,
        sortable:false
    }
    ];

    mfScripts.shortUrlsTable.mainDataSource = new YAHOO.util.DataSource("ajax/manageUrls.ajax.php?");
    mfScripts.shortUrlsTable.mainDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
    mfScripts.shortUrlsTable.mainDataSource.connXhrMode = "queueRequests";
    mfScripts.shortUrlsTable.mainDataSource.responseSchema = {
        resultsList: "records",
        fields: ["shortUrl","fullUrl","dateCreated","visits","createdIp","lastAccessed","status","id"],
        metaFields: {
            totalRecords: "totalRecords"
        }
    };
	
    var myRequestBuilder = function(oState, oSelf)
    {
        oState = oState || {
            pagination:null,
            sortedBy:null
        };
        var sort = (oState.sortedBy) ? oState.sortedBy.key : "dateCreated";
        var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
        var startIndex = (oState.pagination != null) ? oState.pagination.recordOffset : 0;
        var results = (oState.pagination != null) ? oState.pagination.rowsPerPage : 25;
        var filter = document.getElementById('shorturl_search').value;
        var filterDisabled = document.getElementById('shorturl_search_disabled').checked;

        return 'output=json&filter='+ filter + '&filterDisabled='+filterDisabled+'&startIndex='+ startIndex + '&results=' + results + '&sort=' + sort + '&dir=' + dir;
    }
	
    /* setup default request params */
    if(mfScripts.shortUrlsTable.tableParams == null)
    {
        
        mfScripts.shortUrlsTable.tableParams = "results=25&sort=dateCreated&dir=DESC&output=json&startIndex=0&filter="+document.getElementById('shorturl_search').value+"&filterDisabled="+document.getElementById('shorturl_search_disabled').checked;
    }
	
    mfScripts.shortUrlsTable.tablePager = new YAHOO.widget.Paginator({
        rowsPerPage: 25,
        containers: 'paginatorContainer'
    });

    mfScripts.shortUrlsTable.mainDataTable = new YAHOO.widget.DataTable("dataTable", myColumnDefs,
        mfScripts.shortUrlsTable.mainDataSource, {
            initialRequest: mfScripts.shortUrlsTable.tableParams,
            dynamicData: true,
            paginator: mfScripts.shortUrlsTable.tablePager,
            generateRequest: myRequestBuilder
        });
			
    mfScripts.shortUrlsTable.mainDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
        if(typeof(oPayload) == "object")
        {
            mfScripts.shortUrlsTable.previousPayload = oPayload;
        }
        else
        {
            var oPayload = mfScripts.shortUrlsTable.previousPayload;
        }
        oPayload.totalRecords = oResponse.meta.totalRecords;
        mfScripts.shortUrlsTable.tableParams = oRequest;
        return oPayload;
    }
	
    mfScripts.shortUrlsTable.mainDataTable.subscribe('postRenderEvent', mfScripts.shortUrlsTable.updatePager);
    mfScripts.shortUrlsTable.mainDataTable.subscribe("rowMouseoverEvent", mfScripts.shortUrlsTable.mainDataTable.onEventHighlightRow);
    mfScripts.shortUrlsTable.mainDataTable.subscribe("rowMouseoutEvent", mfScripts.shortUrlsTable.mainDataTable.onEventUnhighlightRow);
    mfScripts.shortUrlsTable.mainDataTable.subscribe("rowClickEvent", mfScripts.shortUrlsTable.mainDataTable.onEventSelectRow);

    return {
        ds: mfScripts.shortUrlsTable.mainDataSource,
        dt: mfScripts.shortUrlsTable.mainDataTable
    };
};

mfScripts.shortUrlsTable.updateFilteredResults = function() {
    if(mfScripts.shortUrlsTable.timeOutLoader != null)
    {
        clearTimeout(mfScripts.shortUrlsTable.timeOutLoader);
    }
    mfScripts.shortUrlsTable.tableParams = null;
    mfScripts.shortUrlsTable.timeOutLoader = setTimeout("mfScripts.shortUrlsTable.DynamicData()", 500);
}

/* banned IPs */
function removeBannedWord(id)
{
    if(confirm(t("are_you_sure_remove_banned_word")))
    {
        window.location = "banned_words.php?r="+id;
    }
    else
    {
        return false;
    }
}

function urlEncode(s)
{
    return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /\~/g, '%7E' );
}
   
function urlDecode(s)
{
    return decodeURIComponent( s.replace( /\+/g, '%20' ).replace( /\%21/g, '!' ).replace( /\%27/g, "'" ).replace( /\%28/g, '(' ).replace( /\%29/g, ')' ).replace( /\%2A/g, '*' ).replace( /\%7E/g, '~' ) );
}