////////////////////////////////////////////
// this file contains all of the functions that will
// be associated to our login/user accounts
// and functionality


// allow us to use the "enter" button to log in
function check_key( e )
{
    var key = (window.event) ? window.event.keyCode : e.which;
    if( key == 13 ) { __login(); }
}
// log our user in
function __login()
{
loading(true);
    var id = generate_id();
    __submit("login.php",function(){ login(id); },id);
}
function login()
{
    var args = login.arguments;
    var id   = args[0];
    var r    = _response[id];

    // we have to make sure we have a response from the server
    if( !r ) { loading(false); return; }

    // check the errorcode
    if( r.errorcode != 0 ) { display_message(r.error_message); }
    else
    {
        dojo.io.bind({
            url:        "html/logged_in.html",
            load:       function( type, data )
                        {
                            // no formatting necessary, we're getting html
                            data = data.replace(/{PHOTO}/g,r.photo);
                            data = data.replace(/{NAME}/g,r.name);
                            dojo.byId("login_container").innerHTML = data;
                        },
            mimetype:   "text/html"
        });
    }
loading(false);
}
// log out
function logout() { location.href="logout.php"; }

// register a new member
function __register()
{
loading(true);

    var id = generate_id();
    set_required_fields("Email=Email","Password=Password","First Name=FirstName",id);
    __submit("register.php",function(){ register(id); },id);
}
function register()
{
    var args = register.arguments;
    var id   = args[0];
    var r    = _response[id];

    // sanity
    if( !r ) { loading(false); return; }

    // check the errorcode and act accordingly
    if( r.errorcode != 0 ) { display_message(r.error_message); }
    else
    {
        // we'll update the HTML in the login box...
        dojo.io.bind({
            url:    "html/registered.html",
            load:    function( type, data ) { dojo.byId("signup_form").innerHTML = data; loading(false); },
            mimetype: "text/html"
        });
    }
}

// update the profile of a user
function __edit_profile()
{
loading(true);

    var id = generate_id();
    set_required_fields("Email=Email","First Name=FirstName",id);
    __submit("edit_profile.php",function(){ edit_profile(id); },id);
}
function edit_profile()
{
    var args = edit_profile.arguments;
    var id   = args[0];
    var r    = _response[id];

    // sanity
    if( !r ) { loading(false); return; }

    // show the message
    display_message(r.error_message);
loading(false);
}

// check to see if we're logged in or not
function check_login()
{
    var args = check_login.arguments;

loading(true);
    dojo.io.bind({
        url:    "data/check_login.php",
        load:   function( type, data )
                {
                    var r = eval("("+data+")");
                    if( r.errorcode != 0 )
                    {
                        var template = (iWIN) ? "html/login_windows.html" : "html/login.html";
                        dojo.io.bind({
                            url:      template,
                            load:     function( type, data ) { dojo.byId("login_container").innerHTML = data; },
                            mimetype: "text/html"
                        });
                    }
                    else
                    {
                        dojo.io.bind({
                            url:        "html/logged_in.html",
                            load:       function( type, data )
                                        {
                                            // no formatting necessary, we're getting html
                                            data = data.replace(/{PHOTO}/g,r.photo);
                                            data = data.replace(/{NAME}/g,r.name);
                                            dojo.byId("login_container").innerHTML = data;
                                        },
                            mimetype:   "text/html"
                        });
                    }
loading(false);
                },
        mimetype: "text/plain"
    });
}


// search the fans
function __search_fanclub()
{
    var args = __search_fanclub.arguments;
loading(true);

    var id = generate_id();
    __submit("search_fanclub.php",function(){ search_fanclub(id); },id);
}
function search_fanclub()
{
    var args = search_fanclub.arguments;
    var id   = args[0];
    var r    = _response[id];

    // sanity
    if( !r ) { loading(false); return; }

    // check the errorcode and proceed
    if( r.errorcode != 0 ) { display_message(r.error_message); }
    else
    {
        // necessary divs...
        var clublist  = dojo.byId("clublist");
        var clear_div = document.createElement("div");
        clear_div.setAttribute("style","clear:both;");
        // clear out the clublist div!!!
        clublist.innerHTML = "";

        // we need 3 types of data divs to create
        var container; var photo_div; var info_div;
        // and temp html
        var temp_html;

        // we have to loop thru our matches and create a list
        // to filter into our clublist div
        if( r.matches == 1 )
        {
            // the item container
            container = document.createElement("div");
            container.setAttribute("class","item");
// STUPID GODDAM IE
container.setAttribute("className","item");
            container.setAttribute("onmouseover","hilite(this,'item_over')");
            container.setAttribute("onmouseout","hilite(this,'item')");
            // the photo div
            photo_div = document.createElement("div");
            photo_div.setAttribute("class","clublist_photo");
// STUPID GODDAM IE
photo_div.setAttribute("className","clublist_photo");
            temp_html  = "<a href=\"fanclub_member.php?id="+r.data.ID+"\">";
            temp_html += "<img src=\""+unescape(r.data.Icon)+"\" border=0></a>";
            photo_div.innerHTML = temp_html;
            // the info div
            info_div = document.createElement("div");
            info_div.setAttribute("class","clublist_info");
// STUPID GODDAM IE
info_div.setAttribute("className","clublist_info");
            temp_html  = "<span class=\"orangetext\"><b>"+unescape(r.data.FirstName)+"</b></span><br>\n";
            temp_html += "<span class=\"fineprint\">Registered on "+r.data.Registered+" &nbsp; &nbsp; ";
            temp_html += "<span class=\"greytext\">Last Modified on "+r.data.LastModified+"</span></span><br><br>\n";
            temp_html += "<b>"+unescape(r.data.FirstName)+"</b> has uploaded ";
            temp_html += "<a href=\"photos_album.php?id="+r.data.ID+"\">"+r.data.Photos+" photos</a>";
            info_div.innerHTML = temp_html;
            // now add them...
            container.appendChild(clear_div);
            container.appendChild(photo_div);
            container.appendChild(clear_div);
            container.appendChild(info_div);
            clublist.appendChild(clear_div);
            clublist.appendChild(container);
        }
        else
        {
            for( var i=0; i<r.matches; i++ )
            {
                var d = r.data[i];
                // the item container
                container = document.createElement("div");
                container.setAttribute("class","item");
// STUPID GODDAM IE
container.setAttribute("className","item");
                container.setAttribute("onmouseover","hilite(this,'item_over')");
                container.setAttribute("onmouseout","hilite(this,'item')");
                // the photo div
                photo_div = document.createElement("div");
                photo_div.setAttribute("class","clublist_photo");
// STUPID GODDAM IE
photo_div.setAttribute("className","item");
                temp_html  = "<a href=\"fanclub_member.php?id="+d.ID+"\">";
                temp_html += "<img src=\""+unescape(d.Icon)+"\" border=0></a>";
                photo_div.innerHTML = temp_html;
                // the info div
                info_div = document.createElement("div");
                info_div.setAttribute("class","clublist_info");
// STUPID GODDAM IE
info_div.setAttribute("className","item");
                temp_html  = "<span class=\"orangetext\"><b>"+unescape(d.FirstName)+"</b></span><br>\n";
                temp_html += "<span class=\"fineprint\">Registered on "+d.Registered+" &nbsp; &nbsp; ";
                temp_html += "<span class=\"greytext\">Last Modified on "+d.LastModified+"</span></span><br><br>\n";
                temp_html += "<b>"+unescape(d.FirstName)+"</b> has uploaded ";
                temp_html += "<a href=\"photos_album.php?id="+d.ID+"\">"+d.Photos+" photos</a>";
                info_div.innerHTML = temp_html;
                // now add them...
                container.appendChild(clear_div);
                container.appendChild(photo_div);
                container.appendChild(clear_div);
                container.appendChild(info_div);
                clublist.appendChild(clear_div);
                clublist.appendChild(container);
            }
        }
loading(false);
    }
}

// get the details for a member from the db
function __get_member_details()
{
    var args = __get_member_details.arguments;
loading(true);

    var id = generate_id();
    __submit("details_fanclub.php",function(){ get_member_details(id); },id);
}
function get_member_details()
{
    var args = get_member_details.arguments;
    var id   = args[0];
    var r    = _response[id];

    // sanity
    if( !r ) { loading(false); return; }

    // check the errorcode and proceed
    if( r.errorcode != 0 ) { display_message(r.error_message); }
    else
    {
        // we'll only have one result back... so let's play with it
        var d = r.data;
        var p = r.photo_data;
        var html;
        // set the data into our divs
        dojo.byId("member_photo").innerHTML = "<img src=\""+d.Thumbnail+"\">";
        // set up the info html
        html  = "<h2>"+unescape(d.FirstName+" "+d.LastName)+"</h2>";
        html += "<a href=\"photos_album.php?id="+d.ID+"\">"+d.Photos+" photos</a><br>\n";
        html += (d.MailingList=="YES") ? "<b>ENJOYS RECEIVING </b>" : "<b>DOES NOT SUBSCRIBE TO </b>";
        html += "the <span class=\"orangetext\"><b>ORANGEMAN</b></span> newsletter<br><br>\n";
        html += "<span class=\"fineprint\">"+unescape(d.City)+", "+d.State+"<br>\n";
        html += "Registered on "+d.Registered+"<br>\n";
        html += "<span class=\"greytext\">Last modified on "+d.LastModified+"</span></span>";
        dojo.byId("member_info").innerHTML  = html;

        if( d.Photos > 0 )
        {
        // show our random photos...
        dojo.io.bind({
            url:    "html/photos_thumbnail_display.html",
            load:   function( type, data )
                    {
                        var p_html   = data;  // no formatting necessary
                        var out_html = "";
                        // loop our random photos...
                        if( r.num_photos == 1 )
                        {
                            p_html = p_html.replace(/{PHOTOID}/g,p.ID);
                            p_html = p_html.replace(/{THUMBNAIL}/g,p.Thumbnail);
                            p_html = p_html.replace(/{NAME}/g,unescape(d.FirstName));
                            p_html = p_html.replace(/{PAGE}/g,1);
                            out_html = p_html;
                        }
                        else
                        {
                            // copy the p_html
                            var copy_html = p_html;
                            for( var i=0; i<r.num_photos; i++ )
                            {
                                var photo = p[i];
                                p_html = copy_html;
                                p_html = p_html.replace(/{PHOTOID}/g,photo.ID);
                                p_html = p_html.replace(/{THUMBNAIL}/g,photo.Thumbnail);
                                p_html = p_html.replace(/{NAME}/g,unescape(d.FirstName));
                                p_html = p_html.replace(/{PAGE}/g,1);
                                out_html += p_html;
                            }
                        }
                        // set the innerHTML
                        dojo.byId("member_uploads").innerHTML = "<b>Some uploaded photos</b><br>\n"+out_html;
loading(false);
                    },
            mimetype: "text/html"
        });
        }
    }
}


// upload a file
function upload_file()
{
    var args = upload_file.arguments;
    var file = args[0];     // our file box object
    var f    = args[1];     // our form object
    // just a random number
    var rand = Math.round(Math.random()*119000);

    // we need to get the filename
    // we need to check for windoze...
    if( iWIN ) { var idx = "\\"; }
    else { var idx = "/"; }
    var filename = file.value.substring(file.value.lastIndexOf(idx) + 1);

    // set up a hidden iframe in our uploader div
    var iframe = document.createElement("iframe");
    var if_id  = "iframe_"+rand;
    iframe.setAttribute("id",if_id);
    iframe.setAttribute("name",if_id);
    iframe.setAttribute("frameborder",0);
    iframe.setAttribute("style","width:0px;height:0px;");
//    dojo.byId("uploader").appendChild(iframe);
    document.body.appendChild(iframe);
    // IMPORTANT IE BUG FIX!!!!!
    if( self.frames[if_id].name != if_id ) { self.frames[if_id].name = if_id; }

    // change the form target
    f.target = "iframe_"+rand;
    // change the form submission
    f.action = "/cgi-bin/upload.cgi?sid="+rand;
    f.submit();
    // get rid of the value in the file box
    file.value = null;

    // put something in our upload queue so that
    // we can show the user something is happening...
    var q            = dojo.byId("upload_queue");
    var clear_div    = document.createElement("div"); clear_div.setAttribute("style","clear:both;");
    var container    = document.createElement("div");
    var progress_bar = document.createElement("div");
    var completed    = document.createElement("div");
    var label        = document.createElement("div");
    // now set up all our divs
    container.setAttribute("id","file_"+rand);
    container.setAttribute("class","item");
    container.setAttribute("onmouseover","hilite(this,'item_over')");
    container.setAttribute("onmouseout","hilite(this,'item')");
    label.setAttribute("id","label_"+rand);
    label.setAttribute("class","upload_label");
    progress_bar.setAttribute("id","bar_"+rand);
    progress_bar.setAttribute("class","upload_progress_bar");
    completed.setAttribute("id","completed_"+rand);
    completed.setAttribute("class","upload_percent_complete");
    // put our html inside the respective divs...
    label.innerHTML = "Uploading: <b>"+filename+"</b>";
    // no more html.. just append our kids
    progress_bar.appendChild(completed);
    container.appendChild(clear_div);
    container.appendChild(label);
    container.appendChild(progress_bar);
//     now append it to the page...
    q.appendChild(container);
    q.appendChild(clear_div);

    // our form vars
    var formvars  = "sid="+rand;
        formvars += (dojo.byId("avatar")) ? "&avatar=1" : "";
        formvars += (iWIN) ? "&iswin=1" : "";
    // set up our updater...
    var params = {
        asynchronous: true,
        method     : "post",
        postBody   : formvars,
        frequency  : .2,
        onSuccess  : function(t)
                     {
                        var r = eval("("+t.responseText+")");
                        var p = Math.round(r.percent);
                        dojo.byId("completed_"+rand).style.width = p+"%";
                        if( r.complete != 0 )
                        {
                            dojo.byId("label_"+rand).innerHTML = "<b>COMPLETED:</b> "+filename;
                            dojo.lfx.fadeHide("file_"+rand, 1100).play();
                            if( r.complete == "-1" ) { display_message(r.error_message); }
                            upd.onTimerEvent={};
                            // check if we're uploading an avatar!
                            if( dojo.byId("avatar_upload") ) { location.href = "fanclub_edit.php"; }
                        }
                     },
        onFailure : function(t) { display_message(t.statusText); upd.onTimerEvent={}; }
    };
    var upd = new Ajax.PeriodicalUpdater("","data/upload_photos.php",params);
}
