/*
    CONFIRM REMOVALS!?
  */
  
var iAnswerInputCount = 0;
var sPreviousContent = "";
var sSubmitSuccessMsg = "Submit Successful!";

//  optional = optional || "default value"

/**
	admin_
		newsletter
		write
		email
		poll
		
	postXMLHttpRequestText( sURL, fCallBack, sArgs )

	Line 61 :     getXMLHttpRequestText( sUrl, fCallBack );
	Line 76 :     getXMLHttpRequestText( sUrl, fCallBack );
	Line 95 :     getXMLHttpRequestText( sUrl, submitNewsletter_callback );
	Line 140 :     getXMLHttpRequestText( sUrl, fCallBack );
	Line 157 :     getXMLHttpRequestText( sUrl, fCallBack );
	Line 250 :     getXMLHttpRequestText( sUrl, fCallBack );
	Line 526 :     getXMLHttpRequestText( sUrl, fCallBack );
**/

function toggleLoading( bDisplay )  {
/*    with( document.getElementById( "content_inside" ) )  {
        innerHTML = '<div class="form_submit"><img src="../img/loading.gif"></div>' + innerHTML;
    }*/
    document.getElementById( "loading" ).style.display = ( bDisplay ? 'block' : 'none' );
}

function confirmSubmitInfo( fCallBack, sRedirectLocation, /*type???*/sSubmitMsg, sWhere, sUpdateOrDelete )  {
//  you are about to permanently remove this item
    if( confirm( 'You are about to permanently remove a poll! \n\nAre you sure you want to do this?' ) )
        submitInfo( fCallBack, sRedirectLocation, sSubmitMsg, sWhere, sUpdateOrDelete );
}

//function submitInfo( fCallBack, sRedirectLocation, sSubmitMsg, sWhere, sUpdateOrDelete )
function submitInfo( fCallBack, sRedirectLocation, sSubmitMsg, sValues, sType )  {
//alert( "submitInfo" );

	enableFields( false, false );
    var sUrl = "";
	var sPost = "";
    
    switch( sType )  {
        case "newsletter":
            sUrl = 'admin_newsletter.php';
			sPost = sValues;
//            sUrl = 'THENEWSLETTER.php?' + sValues;
        break;
        case "url":
        	sUrl = "admin_write.php";
			sPost = "functionType=" + sValues;
        break;
        case "update":
        case "delete":
        default:
        	sUrl = "admin_write.php";
			sPost = "functionType=" + ( sValues ? ( sType + "&where=" + sValues ) : "insert" );
        	sPost = appendFormValues( sPost, 0 );
        break;
    }
    if( sSubmitMsg )  sSubmitSuccessMsg = sSubmitMsg;
    
    toggleLoading( true );
    
	//  send off information to be inserted.
    postXMLHttpRequestText( sUrl, fCallBack, sPost );

    //  use window.open( 'location', '_self' );
    if( sRedirectLocation )  window.location = sRedirectLocation;
}
function unsubscribe( fCallBack, sRedirectLocation, sSubmitMsg, sValues, sType ) {
	enableFields( false, false );
	sUrl = "admin_write.php";
	sPost = "functionType=" + ( sValues ? ( sType + "&where=" + sValues ) : "insert" );
	sPost = appendFormValues( sPost, 0 );
	sSubmitSuccessMsg = sSubmitMsg;
	toggleLoading( true );
	postXMLHttpRequestText( sUrl, fCallBack, sPost );
/*	alert( 'ajax sending' );
	$.ajax( {
		  url: sUrl,
		  type: 'post',
		  data: sPost,
		  complete: function( xhr, msg ) {
			alert( msg ); 
			alert( xhr.status );
			toggleLoading( false );
			enableFields( true, true );
		  }
	  });
*/
}
function showSinglePoll() {
	var id = document.getElementById( 'pollquestion_id' ).value;
//	reinit( true );
	getXMLHttpRequestText( 'admin_poll.php?functionType=poll_results&id='+id , displaySinglePollResult );
	alert( 'Poll results recorded successfully!' );
	enableFields( false, false );
}

function submitInfoEmail( fCallBack, sRedirectLocation, sSubmitMsg )  {
	enableFields( false, false );
	
	var sUrl = "admin_email.php";
	var sPost = "function=email_contactus";
	sPost = appendFormValues( sPost, 0 );

    if( sSubmitMsg )  sSubmitSuccessMsg = sSubmitMsg;
    
	//  send off information to be inserted.
    postXMLHttpRequestText( sUrl, fCallBack, sPost );
	
    if( sRedirectLocation )  window.location = sRedirectLocation;

	//  update status bar.
	//  do it here. and now..
}



/*************
    NEWSLETTER 
*************/
function submitNewsletter( sType, sId, bPreview )  {
    toggleLoading( true );
	var ed = tinyMCE.get('body') 
	var sUrl = "admin_email.php";
	var sPost = "function=email_newsletter&type=" + sType + 
        "&id=" + sId + "&additional_info=" + URLEncode( ed.getContent() );
		
	if( bPreview )  sPost += "&preview=true";
	
    postXMLHttpRequestText( sUrl, submitNewsletter_callback, sPost );
}

function submitNewsletter_callback( bSuccessful )  {

//alert( bSuccessful );

	if( bSuccessful )
		alert( 'Newsletter has been sent to all registered users successfully!' );
	else
		alert( 'Newsletter was not sent to all registered users successfully..' );
		
    toggleLoading( false );
}

function getNewsletters_callback( newsletters )  {

//alert( newsletters );
//alert( $( 'newsletters' ).innerHTML );
	if( newsletters )
		$( 'newsletters' ).innerHTML = newsletters;
	else
		alert( 'Unable to retrieve newsletters..' );
		
    toggleLoading( false );
    
}






function submitInfoAutoIncrement( fCallBack, sRedirectLocation, sSubmitMsg, sIdentifier, sPK )  {
//alert( "submitInfoAutoIncrement" );
	enableFields( false, false );
    
	var sUrl = "admin_write.php";
	var sPost = "functionType=insert-autoincrement&identifier=" + sIdentifier + "&pk=" + sPK;
	sPost = appendFormValues( sPost, 0 );
//alert( sUrl );
    
    if( sSubmitMsg )  sSubmitSuccessMsg = sSubmitMsg;
    
    toggleLoading( true );
    
    postXMLHttpRequestText( sUrl, fCallBack, sPost );
    
    if( sRedirectLocation )  window.location = sRedirectLocation;
}

//  submitInfoMultipleAutoIncrement( "initForm", null, "successful", "pollanswer_id" )
function submitInfoMultipleAutoIncrement( fCallBack, sRedirectLocation, sSubmitMsg, sPK )  {
	enableFields( false, false );
    
	var sUrl = "admin_write.php";
	var sPost = "functionType=insert-autoincrement&multiple=true&pk=" + sPK;
	sPost = appendFormValues( sPost, 0 );
    
//alert( sUrl );
    if( sSubmitMsg )  sSubmitSuccessMsg = sSubmitMsg;
    
    toggleLoading( true );
    
    postXMLHttpRequestText( sUrl, fCallBack, sPost );
    
    if( sRedirectLocation )  window.location = sRedirectLocation;
}


function submitBoxInfo( fCallBack, sRedirectLocation, sSubmitMsg, sValues, sForm ) {
//alert( "submitInfo" );

	enableFields( false, false );
    var sUrl = "";
	var sPost = "";
    
	sUrl = "admin_write.php";
	sPost = "functionType=update&where=box_id";
	sPost = appendFormValues( sPost, sForm );

    if( sSubmitMsg )  sSubmitSuccessMsg = sSubmitMsg;
    
    toggleLoading( true );
 //   alert( sPost );
	//  send off information to be inserted.
    postXMLHttpRequestText( sUrl, fCallBack, sPost );

    //  use window.open( 'location', '_self' );
    if( sRedirectLocation )  window.location = sRedirectLocation;
}


function appendFormValues( sAppendTo, iForm )  {
	var iFields = document.forms[iForm].elements.length;
	var element = null;
    var ed = tinyMCE.get('body') 
	for( i = 0; i < iFields; i++ )  {
        element = document.forms[iForm].elements[i];
		if( element.id == 'body' ) {
            document.getElementById( 'body' ).value = URLEncode( ed.getContent() );
			sAppendTo += "&" + element.id + "=" + document.getElementById( 'body' ).value;
        }
        else{
            if( element.type == "radio" )  {
                if( element.checked )  {
                    sAppendTo += "&" + element.name + "=" + element.value;
                }
            }
            else if( element.type == "checkbox" )  {
                if( element.checked )  {
                    sAppendTo += "&" + element.id + "=" + element.value;
                }
/*                else{
                    sAppendTo += "&" + element.id + "=0";
                }*/
            }
            else{
				if ( element.id != '' )
	                sAppendTo += "&" + element.id + "=" + URLEncode( element.value );
            }
        }
    }
	return sAppendTo + "&tableName=" + document.forms[iForm].id;
}


/**
    enable & clear all fields if submit is success.
  **/
function reinit( bInsertSuccessful )  {
//alert( bInsertSuccessful );
    if( bInsertSuccessful )  {
        displaySuccessful( true );
        
		enableFields( true, true );
	}
}

//  should probably pass which form to enable/disable.
function enableFields( bEnable, bClear, iForm )  {
    var iFields = document.forms[0].elements.length;
	
	//  check to be sure that submit button is included in elements array
    with( document.forms[0] )  {
    	for( i = 0; i < iFields; i++ )  {
    		elements[i].disabled = !bEnable;
    		
            if( bClear )  {
                if( elements[i].type == "radio" )  {
                    elements[i].checked = false;
                }
        		else if( ( elements[i].id != "btnSubmit" ) && 
                    ( elements[i].style.display != "none" ) &&
                    ( elements[i].type != "hidden" ) )  {
        			elements[i].value = "";
        		}
            }
    	}
    }
  
    if( bClear ) tinyMCE.setContent( "" );
}

/**
    for use with onmouseout/onmouseover.
  **/
function highlight( element, sBackgroundColor, sCursor )  {
    element.style.cursor = sCursor;
    element.style.backgroundColor = sBackgroundColor;
}


/**
    administrating pages.
  **/
function initPage( sUrl, fCallBack )  {
//    alert( sUrl );
    toggleLoading( true );
    getXMLHttpRequestText( sUrl, fCallBack );
}

function displayPage( sContent )  {
    with( document.getElementById( 'content_inside' ) )  {
        sPreviousContent = innerHTML;
        innerHTML = '<div class="div_btn_left"><img onclick="goBack();" src="../img/back.jpg" class="btn_link" /></div>' + sContent;
        toggleLoading( false );
    }
}

function displayPageEdit( sContent )  {
    displayPage( sContent );
    tinyMCE.init( tinyMCE_attributes );
}


/**
    unable to location.back with ajax content changes.
  **/
function goBack()  {
    //document.getElementById( 'content_inside' ).innerHTML = sPreviousContent;
    //location.reload();
	window.location.reload( false );
}


/**
    display customized success message.
  **/
function displaySuccessful( bSuccessful )  {
//document.getElementById( 'header' ).value = bSuccessful;
//alert( bSuccessful );

    if( bSuccessful )  {
        alert( sSubmitSuccessMsg );
    }
    else{
        alert( bSuccessful );
    }
    
    enableFields( true, false );
    toggleLoading( false );
}





/***
    for use with displaying fields only after the first have been submitted.
  ***/


/**
    append row to form table 
  **/
function appendRow( sToApppend, aFields, sRowId )  {
    var tbody = document.getElementById( sToApppend ).getElementsByTagName( "tbody" )[ 0 ];

    var row = document.createElement( "tr" );
    row.setAttribute( "id", sRowId );

    var td = null;

    for ( sFieldName in aFields )  {
        td = document.createElement( "td" );
        
        with( td )  {
            switch( typeof( aFields[ sFieldName ] ) )  {
                case "string":
                    innerHTML = aFields[ sFieldName ];
                break;
                case "object":
                    appendChild( aFields[ sFieldName ] );
                break;
            }
        }
        
        row.appendChild( td );
    }

    tbody.appendChild(row);
}

/**
    disjoin row from form table
  **/
function disjoinRow( sToDisjoin, sId )  {
    try{
        document.getElementById( sToDisjoin )
            .getElementsByTagName( "tbody" )[ 0 ]
            .removeChild( document.getElementById( sId ) );
    }
    catch( e )  {
        //  do nothing! 
    }
}

//  for comment, registrant and poll removal
/*
function removeArticleCallback( sId )  {
    if( sId )  {
        disjoinRow( "article", ( "que" + sId ) );
        displaySuccessful( true );
    }
}
*/
function removeItemCallback( sTablename_Id )  {
//alert( sTablename_Id );
    if( sTablename_Id )  {
        var aTablename_Id = sTablename_Id.split( ":" );

        disjoinRow( aTablename_Id[ 0 ], "que" + aTablename_Id[ 1 ] );
        disjoinRow( aTablename_Id[ 0 ], "ans" + aTablename_Id[ 1 ] );

        displaySuccessful( true );
    }
}
/*
function removeCommentCallback( sId )  {
//alert( sId );
    disjoinRow( "comment", ( "que" + sId ) );
    disjoinRow( "comment", ( "ans" + sId ) );
    
    displaySuccessful( true );
}

function removePollCallback( sId )  {
    disjoinRow( "poll_question", ( "que" + sId ) );
    disjoinRow( "poll_question", ( "ans" + sId ) );
    
    displaySuccessful( true );
}

*/

function createInput( sId, sType, sValue )  {
    var input = document.createElement( "input" );
    
    if( sValue )  input.setAttribute( "value", sValue );

    input.setAttribute( "id", sId );
    input.setAttribute( "type", sType );
    
    return input;
}


/**
    poll specific functionality
  **/
function createAnswerRow()  {
    var aFields = Array();
    
    aFields[ 0 ] = "Answer " + ++iAnswerInputCount + ":";
    aFields[ 1 ] = createInput( ( "answer:" + iAnswerInputCount ), "text", "" );
    
    return aFields; 
}

//  for creating a new poll question & answers
function swapQuestionAnswer( sId )  {
//alert( sId );
    swapForm( "poll_question", "poll_answer", "divSubmitQuestion", "divSubmitAnswers" );
    
    var form = document.getElementById( 'poll_answer' );
    if( form )  {  form.appendChild( createInput( 'pollquestion_id', 'hidden', sId ) );  }
    
    appendRow( 'poll_form', createAnswerRow(), ('answer:' + iAnswerInputCount) );
}


function swapForm( sOldId, sNewId, sOldSubmit, sNewSubmit )  {
    var form = document.getElementById( sOldId );
    
    var divOldSubmit = document.getElementById( sOldSubmit );
    var divNewSubmit = document.getElementById( sNewSubmit );
    
    if(  form )  {
         form.id = sNewId;
    }

    if( divOldSubmit )  {  divOldSubmit.style.display = "none";  }
    if( divNewSubmit )  {  divNewSubmit.style.display = "block";  }
}



function submitQuestion()  {
    submitInfoAutoIncrement( swapQuestionAnswer, null, null, 'question', 'pollquestion_id' );
    
    document.getElementById( 'tdQuestion' ).innerHTML = ( document.getElementById( 'question' ).value + "<br /><br />" );
    
    toggleLoading( false );
//alert( $( 'content_inside' ).innerHTML );
}

function submitAnswers()  {
    aRepeatedFields = new Array();
    aRepeatedFields[ "pollquestion_id" ] = $( 'pollquestion_id' ).value;//iAnswerInputCount;
//alert( $( 'pollquestion_id' ).value );
    submitInfoMultipleAutoIncrement( goBack, null, "successful!", "pollanswer_id" );
    toggleLoading( false );
}







/***************************************************************************************/
//    POLL RESULTS
/***************************************************************************************/
function displayPollResult( sResults )  {
    aResults = sResults.split( "<END_QUESTIONID>" );
//alert( aResults[ 0 ] );
    var tdQuestion = document.getElementById( "a" + aResults[ 0 ] );
    tdQuestion.innerHTML = aResults[ 1 ];
    
    togglePollResult( true, aResults[ 0 ] );
    toggleLoading( false );
}

function displaySinglePollResult( sResults )  {
    aResults = sResults.split( "<END_QUESTIONID>" );
	//alert( aResults[ 0 ] );

    var tdQuestion = document.getElementById( "poll_cont" );
    tdQuestion.innerHTML = aResults[ 1 ];
    
    togglePollResult( true, aResults[ 0 ] );
    toggleLoading( false );
}

function togglePollResult( bDisplay, iId )  {
	if ( document.getElementById( 'add' + iId ) ) {
	    document.getElementById( 'add' + iId ).style.display = ( bDisplay ? 'none' : 'block' );
	    document.getElementById( 'subtract' + iId ).style.display = ( bDisplay ? 'block' : 'none' );
	
	    if( !bDisplay )  document.getElementById( "a" + iId ).innerHTML = "";
	}
}

function initPollForm()  {
//alert( s );
    document.getElementById( 'tdQuestion' ).innerHTML = '<input class="form_txt"  type="text" id="question"  /><br /><br />';
    
    document.getElementById( 'divSubmitQuestion' ).style.display = 'block';
    document.getElementById( 'divSubmitAnswers' ).style.display = 'none';


var poll_form = document.getElementById( 'poll_form' ).getElementsByTagName( "tbody" );

    with( poll_form )  {
        for( i = 1; i <= iAnswerInputCount; i++ )  {
            removeChild( document.getElementById( 'answer:' + i ) );
        }
    }

    with( document.getElementById( 'poll_answer' ) )  {
        removeChild( document.getElementById( 'pollquestion_id' ) );
        id = "poll_question";
    }
    
    toggleLoading( false );
//alert( document.getElementById( 'content_inside' ).innerHTML );
}



function updatePoll( fCallBack, sId, sDisplayOrDelete )  {
	enableFields( false, false );
	
	var sUrl = "admin_poll.php";
	var sPost = "functionType=poll_" + sDisplayOrDelete + "&id=" + sId;
    
    switch( sDisplayOrDelete )  {
        case "display":
            sSubmitSuccessMsg = "The poll will be displayed next time the 'Home' page is loaded!";
        break;
        
        case "delete":
            sSubmitSuccessMsg = "The poll has been successfully deleted!";
        break;
    }
    
    toggleLoading( true );
    
	//  send off information to be inserted.
    postXMLHttpRequestText( sUrl, fCallBack, sPost );
}

function $( sElement )  {
    return document.getElementById( sElement );
}








/**
    Functions for encoding text exactly the same as the php functions urlencode/urldecode.
    For use with asynchronous calls using get.
**/

function URLEncode( clearString )
{
    clearString = clearString.toString();

    var output = '';
    var x = 0;
    var regex = /(^[a-zA-Z0-9_.]*)/;

    while (x < clearString.length) 
    {
        var match = regex.exec( clearString.substr( x ) );

        if ( match != null && match.length > 1 && match[1] != '' ) 
        {
    	output += match[ 1 ];
             x += match[ 1 ].length;
        }
        else 
        {
            if ( clearString[ x ] == ' ' )
                output += '+';
            else
            {
                var charCode = clearString.charCodeAt( x );
                var hexVal = charCode.toString( 16 );
                output += '%' + hexVal.toUpperCase();
            }

            x++;
        }
    }

    return output;
}

function URLDecode( encodedString )
{
    var output = encodedString;
    var binVal, thisString;
    var myregexp = /(%[^%]{2})/;

    while ( (match = myregexp.exec( output ) ) != null
            && match.length > 1
            && match[1] != '') 
    {
        binVal = parseInt(match[1].substr(1),16);
        thisString = String.fromCharCode(binVal);
        output = output.replace( match[ 1 ], thisString );
    }

    return output.replace( /[+]/g, ' ' );
}
