// File last updated: 03-21-2010

var AJAX_BASE_DIR = 'http://www.grigoriysidelnikov.com/ajax/';//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";

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

// Platform of reason-specific
var PUBLISHTOPIC = "publishtopic.php";
var GETANDPOPULATEFEED = "getandpopulatefeed.php";
var GETANDPOPULATEFAVORITES = "getandpopulatefavorites.php";
var GETANDPOPULATETRACKED = "getandpopulatetracked.php";
var SAVEPHASE1 = "phases/savephase1.php";
var SAVEPHASE2 = "phases/savephase2.php";
var SAVEPHASE3 = "phases/savephase3.php";
var SAVEALLPHASES = "phases/saveallphases.php";
var REPOPULATEPHASEFORMS = "phases/repopulatephaseforms.php";
var ADDTOFAVORITES = "feed/addtofavorites.php";
var UNFAVORITE = "feed/unfavorite.php";
var ADDTOTRACKING = "feed/addtotracking.php";
var UNTRACK = "feed/untrack.php";
var VOTEDOWN = "feed/votedown.php";
var VOTEUP = "feed/voteup.php";
var OPENCOMMENTS = "feed/opencomments.php";
var POSTCOMMENT = "feed/postcomment.php";
var UPLOADPHOTO = "user/uploadphoto.php";
var DELETEACCOUNT = "user/deleteaccount.php";
var SENDCOMMENT = "sendcomment.php";

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

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

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()
{
    AJAX_BASE_DIR = getBaseURL(); //window.location.href;
    AJAX_BASE_DIR += "ajax/";

    //alert(AJAX_BASE_DIR);

    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)
{
    var e = gbi('news_feed_div');
    e.innerHTML = html + '\r\n' + e.innerHTML;
}

// 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)

    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];
}

// Submit Design Quote
function SuccessEvent_QuoteReceived(html)
{
    //alert("SuccessEvent_QuoteReceived - " + html);

    // external function
    hide_costs_calculator();
}

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

function SuccessEvent_DeleteFilesFromDatabase(number_of_files)
{
    // Visually erase files from selected checkboxes
    for (var idx = 0; idx < number_of_files; idx++)
        if ($('input[id=chf' + idx + ']').attr('checked'))
            $('#chfcontainer' + idx).css('display', 'none');
    // Remove loading animation
}

/* Platform of Reason */
function SuccessEvent_UserAccountCreated(data)
{
    alert(data);
    setTimeout(function(){$('#CreateAccountLoadingContainer').fadeOut(1000, function(){ $('#CreateAccountLoadingContainer').css("display","none"); $('#CreateAccountLoadingContainer').css('display', 'none'); $('#CheckEmailMessage').fadeIn(500); })}, 2000);
}

function SuccessEvent_CheckConfirmationNumber(batch)
{

//    alert(batch);

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

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

    var SUCCESS = st;

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

    if (SUCCESS == "true")
    {
        $('#CodeAcceptSuccessMessage').fadeIn(500);

        var login_id = document.getElementById("login_id");
        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))
    {
        $("#msg_loggedinas").css("display", "none");
        $("#msg_creds").css("display", "block");
        var btn = document.getElementById("ButtonSignIn");
        btn.style.background = "transparent";

        SignedIn = 0;
    }
    else
    {
        $("#msg_loggedinas").css("display", "block");
        $("#msg_creds").css("display", "none");
        var btn = document.getElementById("ButtonSignIn");
        btn.style.background = "url('" + getBaseURL() + "Images/ButtonSignOut.png')";

        window.location = getBaseURL();

        SignedIn = 1;
    }
    //alert(ret);
}

function SuccessEvent_SignOut(ret)
{
    $("#msg_loggedinas").css("display", "none");
    $("#msg_creds").css("display", "block");
    $("#ButtonSignIn").css("background", "transparent");

    deletecookie("asid");

    SignedIn = 0;

    window.location = getBaseURL();

    //alert(ret);
}

function SuccessEvent_PublishTopic(ret)
{
    NavigateTo(4);
}

function SuccessEvent_GetAndPopulateFeed(ret)
{
    var oIframe = document.getElementById('wor_iframe');
    var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
    if (oDoc.document) oDoc = oDoc.document;
        oDoc.body.innerHTML = ret;

    //~~~todo: ensure it works in previous IE browsers (less than 5.0?)

    return true;
}

function SuccessEvent_GetAndPopulateFavorites(ret)
{
    var oIframe = document.getElementById('favorites_iframe');
    var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
    if (oDoc.document) oDoc = oDoc.document;
        oDoc.body.innerHTML = ret;

    //~~~todo: ensure it works in previous IE browsers (less than 5.0?)

    return true;
}

function SuccessEvent_GetAndPopulateTracked(ret)
{
    var oIframe = document.getElementById('tracked_iframe');
    var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
    if (oDoc.document) oDoc = oDoc.document;
        oDoc.body.innerHTML = ret;

    //~~~todo: ensure it works in previous IE browsers (less than 5.0?)

    return true;
}

function SuccessEvent_SavePhase1(ret)
{
    $('#ChangesHaveBeenSaved').fadeIn(500, function(){ setTimeout(function(){ $('#ChangesHaveBeenSaved').fadeOut(500); }, 3000) });
}

function SuccessEvent_SavePhase2(ret)
{
    //alert(ret);
    $('#ChangesHaveBeenSaved').fadeIn(500, function(){ setTimeout(function(){ $('#ChangesHaveBeenSaved').fadeOut(500); }, 3000) });
}

function SuccessEvent_SavePhase3(ret)
{
    $('#ChangesHaveBeenSaved').fadeIn(500, function(){ setTimeout(function(){ $('#ChangesHaveBeenSaved').fadeOut(500); }, 3000) });
}

/*Not implemented (yet?)*/
function SuccessEvent_SaveAllPhases(ret)
{
    alert(ret);
}

function SuccessEvent_RepopulatePhaseForms(ret)
{
    var params = ret.split('№', 100);

    //alert(params);

    // get country
    var opt = document.getElementById('id_global_location');
    if (opt) {
        for (var i=0;i<300;i++) {
            if (opt.options[i]) {
                opt.value = params[1];
                if (opt.options[i].value == params[1]) {
                    opt.options[i].selected = true;
                }
            } else
                break; }
    }

    // Phase 1 (0-15)
    document.getElementById('id_full_name').value=trimString(params[0]);
    //document.getElementById('id_global_location').value=params[1];
    document.getElementById('id_address_line_1').value=params[2];
    document.getElementById('id_address_line_2').value=params[3];
    document.getElementById('id_city').value=params[4];
    document.getElementById('id_state').value=params[5];
    document.getElementById('id_zip').value=params[6];
    document.getElementById('id_perm_phone').value=params[7];
    document.getElementById('id_email_address').value=params[8];
    document.getElementById('id_date_of_birth').value=params[9];
    document.getElementById('id_gender').value=params[10];
    document.getElementById('id_age').value=params[11];
    document.getElementById('id_nationality').value=params[12];
    document.getElementById('id_marital_status').value=params[13];
    document.getElementById('id_occupation').value=params[14];
    document.getElementById('id_education_level').value=params[15];

    //alert(params);

    // Phase 2 (16-31)

    var k,j,s='',pi=16;
    for (k = 1, j = 1; k <= 14; k++, j++)
    {
        //var j1 = j;// + 0;
        //var j2 = j+1;// + 2;
        var tag1 = "id_s" + j + "q1";
        var tag2 = "id_s" + j + "q2";
        s += tag1 + "," + tag2 + ",";

        if (document.getElementById(tag1))
            document.getElementById(tag1).value = params[pi++];
        if (document.getElementById(tag2))
            document.getElementById(tag2).value = params[pi++];
    }

    //alert(s);

    // 31
    document.getElementById('id_s12q0').value=params[pi++];

    // Phase 3

    var t1 = "id_s15q1";
    var t2 = "id_s15q2";
    var t3 = "id_s15q3";

    if (document.getElementById(t1))
        document.getElementById(t1).value = params[pi++];
    if (document.getElementById(t2))
        document.getElementById(t2).value = params[pi++];
    if (document.getElementById(t3))
        document.getElementById(t3).value = params[pi++];
}

function SuccessEvent_AddToFavorites(r)
{
    var params = r.split('№', 100);

    //alert(params);

   // alert("current_iframe_view = " + current_iframe_view);

    if (params[0] == 0)
        alert("Failed to add this item to your favorites due to program error!");
    else if (params[0] == 1)
    {
        var tag = "fav_link_feed_" + params[2];
        var tag2 = "heart_icon_" + params[2];
        var oIframe = document.getElementById(current_iframe_view);
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
        oDoc.getElementById(tag).innerHTML = "<a href = '#' onclick = 'parent.Favorite(" + params[1] + ", " + params[2] + ", false); return false;'>Unfavorite</a>";
        oDoc.getElementById(tag2).innerHTML = "<img src = 'Images/CrossedHeart.png' alt = 'Unfavorite' align = 'absmiddle' />";
    }
    else if (params[0] == 2)
        alert("Item is already in your favorites!");
}

function SuccessEvent_AddToTracking(r)
{
    var params = r.split('№', 100);

    //alert(current_iframe_view);

    //alert(params);

    if (params[0] == 0)
        alert("Failed to add this item to your tracked items due to program error!");
    else if (params[0] == 1)
    {
        var tag = "trk_link_feed_" + params[2];
        var tag2 = 'bino_icon_' + params[2];
        var oIframe = document.getElementById(current_iframe_view);
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
        oDoc.getElementById(tag).innerHTML = "<a href = '#' onclick = 'parent.Track("+params[1]+", "+params[2]+", false); return false;'>Untrack</a>";
        oDoc.getElementById(tag2).innerHTML = "<div class = 'feed_icon' id = 'bino_icon_<?php print $j; ?>'><img src = 'Images/CrossedBinoculars.png' alt = 'Track' align = 'absmiddle' /></div>";
    }
    else if (params[0] == 2)
        alert("Item is already being tracked!");
}

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

    var params = ret.split('№', 100);

    //alert(params);
    
    if (params[0] == 1)
    {
        var tag = "fav_link_feed_" + params[2];
        var tag2 = "heart_icon_" + params[2];
        var oIframe = document.getElementById(current_iframe_view);
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
        oDoc.getElementById(tag).innerHTML = "<a href = '#' onclick = 'parent.Favorite(" + params[1] + ", " + params[2] + ", true); return false;'>Favorite</a>";
        oDoc.getElementById(tag2).innerHTML = "<img src = 'Images/Heart.png' alt = 'Favorite' align = 'absmiddle' />";

        //~~~todo: ensure it works in previous IE browsers (less than 5.0?)
    }
}

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

    var params = ret.split('№', 100);

    //alert(params);

    //alert(current_iframe_view);

    if (params[0] == 1)
    {
        var tag = "trk_link_feed_" + params[2];
        var tag2 = 'bino_icon_' + params[2];
        var oIframe = document.getElementById(current_iframe_view);
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
        oDoc.getElementById(tag).innerHTML = "<a href = '#' onclick = 'parent.Track("+params[1]+", "+params[2]+", true); return false;'>Track</a>";
        oDoc.getElementById(tag2).innerHTML = "<div class = 'feed_icon' id = 'bino_icon_<?php print $j; ?>'><img src = 'Images/Binoculars.png' alt = 'Track' align = 'absmiddle' /></div>";

        //~~~todo: ensure it works in previous IE browsers (less than 5.0?)
    }
}

function SuccessEvent_VoteUp(ret)
{
    var params = ret.split('№', 5);

    if (params[0] == 7)
    {
        alert("You already voted on this topic");
    } else
    if (params[0] == 1)
    {
        var tag = "pos_thumb_" + params[2];
        if (params[3] == 1)
            tag = "pos_thumb_c" + params[2];
        tag = (tag).trim(); // trim /r/n residue
        var oIframe = document.getElementById(current_iframe_view);
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
        if (oDoc.getElementById(tag))
        {
            var curr = parseInt(oDoc.getElementById(tag).innerHTML);
            if (curr == '+0')
                curr = 0;
            curr += 1;
            oDoc.getElementById(tag).innerHTML = "+" + curr;
        }
    }
    else
    {
        // fail
    }
}

function SuccessEvent_VoteDown(ret)
{
    var params = ret.split('№', 5);

    //alert(params);

    if (params[0] == 7)
    {
        alert("You already voted on this topic");
    } else
    if (params[0] == 1)
    {
        var tag = "neg_thumb_" + params[2];
        if (params[3] == 1)
            tag = "neg_thumb_c" + params[2];
        tag = (tag).trim(); // trim /r/n residue

        //alert(tag);

        var oIframe = document.getElementById(current_iframe_view);
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
        var curr = parseInt(oDoc.getElementById(tag).innerHTML);
        if (curr == '-0')
            curr = 0;
        curr -= 1;
        oDoc.getElementById(tag).innerHTML = curr;
    }
    else
    {
        // fail
    }
}

function SuccessEvent_OpenComments(ret)
{
    var oIframe = document.getElementById(current_iframe_view);
    var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
    if (oDoc.document) oDoc = oDoc.document;
        oDoc.body.innerHTML = ret;

    //~~~todo: ensure it works in previous IE browsers (less than 5.0?)

    return true;
}

function SuccessEvent_PostComment(ret)
{
    var params = ret.split('№', 5);
    var oIframe = document.getElementById(current_iframe_view);
    var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
    if (oDoc.document) oDoc = oDoc.document;
    oDoc.getElementById('PostComment').style.display = 'none';

    var msg = "<div class = 'FeedMessage' style = 'height: auto;'><div id = 'FeedUserImage'></div>Posted by <a href = '#' onclick = 'gotoProfile(" + params[1] + ")'>" + params[4] + "</a> (just now)<br/><br/>" +
        params[3] + "<br/><br/>&nbsp;</div></div>";

    oDoc.getElementById('PostedComment').innerHTML = msg;
}

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_SendComment(ret)
{
    if (ret == 1)
    {
        document.getElementById('MovableViewContactUs').innerHTML = "Your comment has been received! If you provided a correct e-mail address, we will respond to you at our earliest convenience.";
    }
    else
    {
        document.getElementById('MovableViewContactUs').innerHTML = "Sorry, there was an error sending your message, please try again at a later time.";        
    }
}

function SuccessEvent_ProposalReceived(html)
{
    //alert("SuccessEvent_ProposalReceived");
    $('#proposal_request_sent').css("display", 'block');
    $('#sending_proposal_request').css("display", 'none');
}
