// File last updated: 03-21-2010

var AJAX_BASE_DIR = GetSiteLocation(); //window.location.href + "/ajax/"; //"http://localhost/titanicwebdesign.com/ajax/";

// Admin site control panel
var ADDNEWS    = "controlpanel/addnews.php";
var EDITNEWS   = "controlpanel/editnews.php";
var UPDATENEWS = "controlpanel/updatenews.php";
var DELETENEWS = "controlpanel/deletenews.php";
var ADDFILETODATABASE = "controlpanel/addfiletodatabase.php";
var DELETEFILES = "controlpanel/deletefiles.php";
var DELETEUSERS = "controlpanel/deleteusers.php";
var ADDNEWCATEGORY = "controlpanel/addnewcat.php";
var SAVENEWSLETTER = "controlpanel/savenewsletter.php";
var SAVEANDSENDNEWSLETTER = "controlpanel/saveandsendnewsletter.php";
var APPROVEFEEDS = "controlpanel/approvefeeds.php";
var UPDATEADS = "controlpanel/updateads.php";

// other commands
var CREATEUSER = "createuser.php";
var CHECKCONFIRMATIONCODE = "checkconfirmationcode.php";
var SIGNIN = "signin.php";
var SIGNOUT = "signout.php";

// AuthenticSociety-specific
var UPDATEPROFILE = "updateprofile.php";
var VOTEDOWN = "feed/votedown.php";
var VOTEUP = "feed/voteup.php";
var POSTCOMMENT = "feed/postcomment.php";
var UPLOADPHOTO = "user/uploadphoto.php";
var DELETEACCOUNT = "user/deleteaccount.php";
var RETREIVEPASSWORD = "retreivepassword.php";

// Submit Design Quote
var SUBMITQUOTE = "execquoterequest.php";

// Rosado - Photo Gallery Specific
var ADDGALLERY = "addgallery.php";
var DELETEGALLERY = "deletegallery.php";
var EDITGALLERYNAME = "editgalleryname.php";
var EDITGALLERYDESCRIPTION = "editgallerydescription.php";
var REPOPULATEGALLERYINTO = "repopulate_gallery_into.php"; /*re-display gallery list dynamically using innerHTML*/
var REORDERGALLERIES = "reordergalleries.php";

// Rosado - Site Section Specific
var ADDSECTION = "addsitesection.php";
var DELETESECTION = "deletesitesection.php";
var EDITSECTIONNAME = "editsectionname.php";
var EDITSECTIONDESCRIPTION = "editsectiondescription.php";
var REPOPULATESECTIONINTO = "repopulate_section_into.php"; /*re-display gallery list dynamically using innerHTML*/
var REORDERSECTIONS = "reordersitesections.php";

var CREATEGALLERYLIST = "create_gallery_list.php";
var DUMPPERMANENTLY = "dump_permanently.php";
var GALTOCAT = "galtocat.php";
var MOVETOGALLERY = "movetogallery.php"; /*move selected files to gallery*/
var SENDCONTACTINFO = "sendcontactinfo.php";

// Global SignIn(Out) Status used only for user interface states (has no effect on actual signed in/out state)
var SignedIn = 0;

/*
function gbi(id) {
    return document.getElementById(id);
} */

function GetLastAjaxCommand() { return (ajaxFunctionHistory[ajaxFunctionHistorySize-1]).toString().toUpperCase(); }

// Utility string function: trim a string
function trimString(s) { return s.replace(/^\s*/, "").replace(/\s*$/, ""); }

// Javascript, javascript...
function setCharAt(str,index,chr)
{
    if (index > str.length-1)
        return str;
    return str.substr(0,index) + chr + str.substr(index+1);
}

function GetSiteLocation()
{
    return "http://www.rosadophotography.com/TitanicWebDesign/ajax/";
    //return "http://www.authenticsociety.com/ajax/";

    AJAX_BASE_DIR = getBaseURL(); //window.location.href;
    AJAX_BASE_DIR += "ajax/";

    return AJAX_BASE_DIR;
}

// Interface update code
// Success action events for each of the comands above

// Shows a just added news story
function SuccessEvent_AddNews(html)
{
    //alert(html);

    //if (trimString(e.innerHTML) == "No news has been published yet.")
      //e.innerHTML="";

    $('#news_feed_div').html( html + '\r\n' + $('#news_feed_div').html() );
}

// Hides the news from UI
function SuccessEvent_DeleteNews(id)
{
    var e = gbi('main_news_' + parseInt(id) + '_container');
    e.style.display = 'none';
}

function SuccessEvent_UpdateNews(batch)
{
    var params = batch.split('№', 2); // ? is a special splitter character (Russian)


    //alert(params[0]);
    //alert(params[1]);

    var id = params[0];
    switchdiv('news_id_' + parseInt(id) + '_solid', 'news_id_' + parseInt(id) + '_editable');

    var e = gbi('news_id_' + parseInt(id) + '_solid');

    if (e) e.innerHTML = params[1];
}

function SuccessEvent_AddFileToDatabase(data)
{
    //alert("SuccessEvent_AddFileToDatabase," + data);

    var arr = data.split(",");

    var index = arr[0];

    var last_pic_key_id = arr[1];


    var insertable_tag = "insert_" + trimString(index);

    //alert(insertable_tag);

    document.getElementById( insertable_tag ).innerHTML = '<input type = "hidden" id = "chf_key_' + trimString(index) + '" value = "' + last_pic_key_id + '" />';
}

function SuccessEvent_DeleteFilesFromDatabase(ret)
{

    //alert("SuccessEvent_DeleteFilesFromDatabase="+ret);

    var number_of_total_files = ret;

    // Visually erase files from selected checkboxes
    for (var idx = 0; idx < number_of_total_files; idx++)
    {
        //alert(idx);

        if ($('input[id=chf' + idx + ']').attr('checked'))
        {
            //alert('#chfcontainer' + idx);
            $('#chfcontainer' + idx).css('display', 'none');
        }
    }
    // Remove loading animation
}

/* Platform of Reason */
function SuccessEvent_UserAccountCreated(data)
{
    if (data == 7) /* exists, not activated */
    {
        var msg = "Your account is not yet active. Please check your email inbox (or filtered messages folder) for an email from Authentic Society containing activation code.";
        $('#CreateAccountErrorLog').html('<b>Note</b>: Account with this email address already exists. ' + msg);
        $('#ActivateAccountForm').fadeIn(500);
    }
    else
    if (data == 8) /* exists, activated */
    {
        var msg = "This account is also already activated. To guarantee safety of your privacy, there is no way to recover your password if you forget it.";/* Please use <a href = 'http://www.authenticsociety.com/ForgotPassword'>Password Recovery</a> form if you don't remember your sign in credentials.";*/
        $('#CreateAccountErrorLog').html('<b>Note</b>: Account with this email address already exists. ' + msg);

    }
    else
    {
        $('#ActivateAccountForm').fadeIn(500);
    }

    $('#CreateAccountLoading').css('display', 'none');
}

function SuccessEvent_CheckConfirmationNumber(batch)
{
    $('#CreateAccountLoading').css('display', 'none');
    $('#CreateAccountErrorLog').css('display', 'none');

    var params = batch.split("№", 4); // ? is a special splitter character (Russian)

    var id = params[0];
    var cc = params[1];
    var st = params[2]; // status

    var SUCCESS = st;

    //alert(id + "," + cc + ", SUCCESS = " + SUCCESS);

    if (SUCCESS == "true")
    {
        $('#ActivateAccountForm').css('display', 'none');
        $('#CodeAcceptFailMessage').css('display', 'none');
        $('#CodeAcceptSuccessMessage').fadeIn(500);
        var login_id = document.getElementById("login_id");
        id = id.replace(/\s/g, "");
        login_id.value = id;
    }
    else
    {
        $('#CodeAcceptFailMessage').fadeIn(500);
    }
}

function SuccessEvent_SignIn(ret)
{
    //alert(ret);

    var params = ret.split("№", 2);
    var re = new RegExp('Bad Login Initiation');
    if (params[0].match(re)) alert("Sorry, login provided is incorrect. There is no existing user with the username and password combination you have provided. Try again using correct credentials."); else { /* Successful login */ }
    if (params[0].match(re))
    {
        SignedIn = 0;
    }
    else
    {
        redirect('http://www.authenticsociety.com/FrontPage');
        SignedIn = 1;
    }
}

function SuccessEvent_SignOut(ret)
{
    deletecookie("asid");

    SignedIn = 0;

    redirect('http://www.authenticsociety.com/FrontPage');

    //alert(ret);
}

function SuccessEvent_VoteUp(ret)
{

}

function SuccessEvent_VoteDown(ret)
{

}

function SuccessEvent_OpenComments(ret)
{

}

function SuccessEvent_PostComment(ret)
{

}


function SuccessEvent_DeleteAccount(ret)
{
    if (ret == 1) {
        alert("Your account has been deleted. You have been signed out.\r\n\r\nThanks for using Platform of Reason!");
        parent.window.SignOut();
    }
    else
        alert("Ooops, there has been a problem deleting your account at this time. Try again later.\r\n\r\n" + ret);
}

function SuccessEvent_RetreivePassword(ret)
{
    $('#retpw_msg').html(ret);
}

function SuccessEvent_UpdateProfile(ret)
{
    //alert(ret);

    $('#UpdateProfileLoading').css('display', 'none');

    $('#FinishedUpdatingProfile').css('display', 'block');

    setTimeout(function(){ $('#FinishedUpdatingProfile').fadeOut(500) }, 1500);
}

/* Galleries and sections */

function SuccessEvent_RepopulateGalleryInto( batch )
{
    //alert(batch);

    //var params = batch.split("№", 4); // ? is a special splitter character (Russian)

    document.getElementById("div_existing_galleries").innerHTML = ''+batch;

    $('#prompt').fadeOut();

    //$('#div_existing_galleries').html( params[1] );

    //$('#div_existing_galleries').css("display","none");
}

function SuccessEvent_ReorderGalleries( batch )
{
    //alert( batch );
    ajax.httpExecute(SuccessEvent_RepopulateGalleryInto, REPOPULATEGALLERYINTO, [0]);

    update_file_gallery_selector();
}

function SuccessEvent_GalleryAdded(ret)
{
    alert(ret);

    ajax.httpExecute(SuccessEvent_RepopulateGalleryInto, REPOPULATEGALLERYINTO, [0]);

    update_file_gallery_selector();
}

function SuccessEvent_DeleteGallery(ret)
{
    ajax.httpExecute(SuccessEvent_RepopulateGalleryInto, REPOPULATEGALLERYINTO, [0]);

    update_file_gallery_selector();
}

function SuccessEvent_EditGalleryName(ret)
{
    //if (ret != "fail" && isnumeric(ret))
        ajax.httpExecute(SuccessEvent_RepopulateGalleryInto, REPOPULATEGALLERYINTO, [ret]);

    update_file_gallery_selector();
}

function SuccessEvent_EditGalleryDescription(ret)
{
   // if (ret != "fail" && isnumeric(ret))
        ajax.httpExecute(SuccessEvent_RepopulateGalleryInto, REPOPULATEGALLERYINTO, [ret]);

}







function SuccessEvent_RepopulateSectionInto( batch )
{
    //alert(batch);

    //var params = batch.split("№", 4); // ? is a special splitter character (Russian)

    document.getElementById("div_existing_sections").innerHTML = ''+batch;

    $('#prompt').fadeOut();

    //$('#div_existing_galleries').html( params[1] );

    //$('#div_existing_galleries').css("display","none");
}

function SuccessEvent_ReorderSections( batch )
{
    //alert( batch );
    ajax.httpExecute(SuccessEvent_RepopulateSectionInto, REPOPULATESECTIONINTO, [0]);
}

function SuccessEvent_SectionAdded(ret)
{
    //alert(ret);
    ajax.httpExecute(SuccessEvent_RepopulateSectionInto, REPOPULATESECTIONINTO, [0]);
}

function SuccessEvent_DeleteSection(ret)
{
    ajax.httpExecute(SuccessEvent_RepopulateSectionInto, REPOPULATESECTIONINTO, [0]);
}

function SuccessEvent_EditSectionName(ret)
{
    //if (ret != "fail" && isnumeric(ret))
        ajax.httpExecute(SuccessEvent_RepopulateSectionInto, REPOPULATESECTIONINTO, [ret]);
}

function SuccessEvent_EditSectionDescription(ret)
{
   // if (ret != "fail" && isnumeric(ret))
        ajax.httpExecute(SuccessEvent_RepopulateSectionInto, REPOPULATESECTIONINTO, [ret]);
}




function SuccessEvent_CreateGalleryList(ret)
{
    document.getElementById("file_gallery_selector").innerHTML = ''+ret;
}

function update_file_gallery_selector()
{
    setTimeout(function(){ajax.httpExecute(SuccessEvent_CreateGalleryList, CREATEGALLERYLIST, [0]);},500);
}

function dump_permanently()
{
    ajax.httpExecute(SuccessEvent_DumpPermanently, DUMPPERMANENTLY, [0]);
}

function SuccessEvent_DumpPermanently(ret)
{
    document.getElementById("div_deleted_galleries").innerHTML = '';
}

function SuccessEvent_GalToCat(ret)
{

    ajax.httpExecute(SuccessEvent_RepopulateGalleryInto, REPOPULATEGALLERYINTO, [0]);

    document.getElementById('gal_message').innerHTML = "Galleries were successfully moved";
}

/*Move selected files to gallery*/

function SuccessEvent_MoveToGallery( ret )
{
    alert("Files have been successfully moved to selected gallery!\r\nPlease refresh control panel to see actual changes.");
}

function SuccessEvent_SendContactInfo( ret )
{
    $('#send_message_msg').html('Your message has been received. We will get back to your shortly. Thank You!');
}
















