﻿



// prototypes //
String.prototype.startsWith = function(str) {
    return (this.match("^" + str) == str)
}





var IMAGE = "IMAGE";
var VIDEO = "VIDEO";

var HOME_URL = "http://www.bizarroishere.com/";
var ASSETS_URL = "http://www.bizarroishere.com/";
var IMAGE_PATH = "images/ugc/tests/";

var currentImageName = "";
var currentPage = 1;
var sortType = "RECENT";

function init() {
    showThumbsTable(true);
    showPreviousVoteArea(false);

    // check for specific image request
    var tgtimage = getUrlVar("med");

    if (tgtimage != null) {
        $.ajax({
            type: "GET",
            cache: false,
            url: HOME_URL + "bizarrohandler.ashx",
            data: { rt: 1, med: tgtimage },
            datatype: "xml",
            success: init_callback,
            error: init_failed
        });
        
    } else {
        // init thumbs and main image request //
        $.ajax({
            type: "GET",
            cache: false,
            url: HOME_URL + "bizarrohandler.ashx",
            data: { rt: 1 },
            datatype: "xml",
            success: init_callback,
            error: init_failed
        });
    }

    // init radio vote buttons //
    $(".voteBtns").click(submitVote);
}

function init_callback(xml, textStatus) {
    parseThumbnails(xml);
    parseMainImage(xml);
}

function init_failed(XMLHttpRequest, textStatus, errorThrown) {
    alert("An error has occurred.  Please try again later.");
}


function parseMainImage(xml) {
    //alert("parseMainImage();");

    $("media", xml).each(function() {

        var type = $(this).attr("medtype");

        if (type.toUpperCase() == IMAGE) {
            type = IMAGE;
        } else if (type.toUpperCase() == VIDEO) {
            type = VIDEO;
        } else {
            // invalid request
            alert("Error.  Invalid media type.");
            return;
        }

        var mediapath = $(this).find("link").text();
        
        setCurrentImageName(mediapath);

        var title = $(this).find("title").text();
        var desc = $(this).find("description").text();
        var nickname = $(this).find("nickname").text();

        setMainImageContent(mediapath, type, title, desc, nickname);

    });

}

function parseThumbnails(xml) {
    var i = 0;
    var itemcount = $("thumb", xml).length;

    if (sortType == "ALPHA" && itemcount > 1) {
        $("#alphaDiv").empty();
    }

    // for every 'thumb' element within the xml object, set the tmbnail image and click target //
    $("thumb", xml).each(function() {

        var tmbid = "#tmb" + i.toString();
        var tmblinkid = "#tmblnk" + i.toString();

        var tmbpath = $(this).text();
        var imagename = $(this).attr("name");

        //alert("$(this).attr('name'): " + imagename + "   (value): " + tmbpath + "   (i): " + i);
        //alert("$(" + tmbid + "): " + $(tmbid).attr("src"));


        if (sortType == "ALPHA") {
            var anchor = "<a href=\"javascript:getMainImageContent('" + imagename + "');\">" + tmbpath + "</a><br />";

            $("#alphaDiv").append(anchor);

        } else {
            // set thumbnail image
            $(tmbid).attr("src", tmbpath);

            // set thumbnail click target
            var jscript = "javascript:getMainImageContent(\"" + imagename + "\");";
            $(tmblinkid).attr("href", jscript);

            i++;
        }

    });
}

function getMainImageContent(filename) {
    //alert("getMainImageContent(" + filename + ")");

    $.ajax({
        type: "GET",
        cache: false,
        url: HOME_URL + "bizarrohandler.ashx",
        data: { med: filename, rt: 3 },
        datatype: "xml",
        success: getMainImageContent_callback,
        error: init_failed
    });

}

function getMainImageContent_callback(xml, textStatus) {
    if (textStatus.toUpperCase() == "SUCCESS") {
        parseMainImage(xml);
    } else {
        // showError(); 
    }
}


function setMainImageContent(filename, type, title, desc, nickname) {

    // if we have received a strange request, do nothing //
    if (type != IMAGE && type != VIDEO) {
        return;
    }

    $("#uname").empty();
    $("#uname").append(nickname);

    $("#title").empty();
    $("#title").append(title);

    $("#loc").empty();
    //$("loc").append(title);        

    $("#desc").empty();
    $("#desc").append(desc);

    clearAllRadioButtons();

    // remove all children of the photovideoDiv //
    $("#photovideoDiv").empty();
    $("#photovideoDiv").removeClass("imagepad");
    $("#photovideoDiv").removeClass("videopad");

    if (type == IMAGE) {
        $("#photovideoDiv").addClass("imagepad");
        $("#photovideoDiv").append("<img alt=\"\" src=\"" + filename + "\" />");

    } else if (type == VIDEO) {
        
        filename = stripMain(filename);
    
        $("#photovideoDiv").addClass("videopad");
        $("#photovideoDiv").flash(
                {
                    src: 'swfs/vidplayer.swf',
                    width: 335,
                    height: 285,
                    quality: "high",
                    allowFullScreen: "true",
                    menu: "false",
                    flashvars: { vidurl: filename }
                },
                { version: 9 }
            );
    }

    // add trackback link
    var trackbacklink = HOME_URL + "default.htm?rt=1&med=" + currentImageName;
    $("#permalink").attr("value", trackbacklink);
    

}

function getNextMainImage() {
    //alert("getNextMainImage()");

    $.ajax({
        type: "GET",
        cache: false,
        url: HOME_URL + "bizarrohandler.ashx",
        data: { rt: 6 },
        datatype: "xml",
        success: getMainImageContent_callback,
        error: init_failed
    });
}

function getMoreThumbs() {
    $.ajax({
        type: "GET",
        cache: false,
        url: HOME_URL + "bizarrohandler.ashx",
        data: { rt: 7 },
        datatype: "xml",
        success: parseThumbnails,
        error: init_failed
    });
}

function sortThumbs(id) {
    sortType = id;

    $.ajax({
        type: "GET",
        cache: false,
        url: HOME_URL + "bizarrohandler.ashx",
        data: { rt: 7, ord: id },
        datatype: "xml",
        success: sortThumbs_callback,
        error: init_failed
    });
}

function sortThumbs_callback(xml, textSuccess) {
    //alert("sortThumbs_callback: " + textSuccess);

    // parse xml and set thumbs
    parseThumbnails(xml);

    // set tab style
    setSortTabStyle(sortType);

    if (sortType == "ALPHA") {
        showThumbsTable(false);
    } else {
        showThumbsTable(true);
    }
}

function setSortTabStyle(id) {
    switch (id) {
        case "RANDOM":
            $("#thumbtab_random").removeClass("thumbborder_notselected");
            $("#thumbtab_random").addClass("thumbborder_selected");

            $("#thumbtab_recent").removeClass("thumbborder_selected");
            $("#thumbtab_recent").addClass("thumbborder_notselected");

            $("#thumbtab_alphabetical").removeClass("thumbborder_selected");
            $("#thumbtab_alphabetical").addClass("thumbborder_notselected");
            break;

        case "TIME":
            $("#thumbtab_recent").removeClass("thumbborder_notselected");
            $("#thumbtab_recent").addClass("thumbborder_selected");

            $("#thumbtab_random").removeClass("thumbborder_selected");
            $("#thumbtab_random").addClass("thumbborder_notselected");

            $("#thumbtab_alphabetical").removeClass("thumbborder_selected");
            $("#thumbtab_alphabetical").addClass("thumbborder_notselected");
            break;

        case "ALPHA":
            $("#thumbtab_alphabetical").removeClass("thumbborder_notselected");
            $("#thumbtab_alphabetical").addClass("thumbborder_selected");

            $("#thumbtab_recent").removeClass("thumbborder_selected");
            $("#thumbtab_recent").addClass("thumbborder_notselected");

            $("#thumbtab_random").removeClass("thumbborder_selected");
            $("#thumbtab_random").addClass("thumbborder_notselected");
            break;

        default:
            break;
    }
}

function submitVote() {
    //alert("submitVote: " + $(this).attr("value"));

    var voteValue = $(this).attr("value")

    //alert("rt: 4, med: currentImageName, vot: currentImageName: " + currentImageName + " votevalue: " + voteValue);

    $.ajax({
        type: "GET",
        cache: false,
        url: HOME_URL + "bizarrohandler.ashx",
        data: { rt: 4, med: currentImageName, vot: voteValue },
        datatype: "xml",
        success: submitVote_callback,
        error: init_failed
    });
}

function submitVote_callback(xml, textSuccess) {
    if (textSuccess.toUpperCase() == "SUCCESS") {
        var prevVote = -1;
        var avgVote = -1;
        var prevThumb = "";

        $("votes", xml).each(function() {
            prevVote = $(this).find("yourvote").text();
            avgVote = $(this).find("avg").text();
        });

        $("media", xml).each(function() {
            prevThumb = $(this).find("link").text();
        });

        if (prevVote >= 0 && avgVote >= 0) {
            $("#prevVoteValue").empty();
            $("#prevVoteValue").append(prevVote);
            $("#avgVoteValue").empty();
            $("#avgVoteValue").append(avgVote);
            $("#prevThumb").attr("src", prevThumb);

            showPreviousVoteArea(true);
        } else {
            showPreviousVoteArea(false);
            alert("Error.  Invalid vote data.");
        }

        // cycle to next image
        getNextMainImage();

    } else {
        //showError();
    }
}

function showPreviousVoteArea(truefalse) {
    if (truefalse) {
        $("#prevVoteArea").show();
    } else {
        $("#prevVoteArea").hide();
    }
}

function showThumbsTable(truefalse) {
    if (truefalse) {
        $("#alphaTable").hide();
        $("#thumbsTable").show();
    } else {
        $("#thumbsTable").hide();
        $("#alphaTable").show();
    }
}

function clearAllRadioButtons() {
    $(".voteBtns").each(function() {
        $(this).attr("checked", "");
    });
}

function setCurrentImageName(path) {
    var pathsections = path.split("/");
    var imgname = pathsections[pathsections.length - 1];
    var imgID = imgname.split(".");
    var ID = "";

    // we only want to remove the extension, so provide flexibility for filenames with dots in them
    if (imgID.length > 2) {
        ID = imgID[0];
        for (var i = 1; i < imgID.length - 1; i++) {
            ID += "." + imgID[i];
        }
    } else {
        ID = imgID[0];
    }

    // set the global var 
    if (ID.startsWith("main_")) {
        //alert("trimming...");
        currentImageName = ID.substr(5);
    } else {
        currentImageName = ID;
    }

    //alert("currentImageName: " + currentImageName);
}


function stripMain(filepath) {
    var tmp = filepath.split("/");
    var filename = tmp[tmp.length - 1];

    if (filename.startsWith("main_")) {
        tmp[tmp.length - 1] = filename.substr(5);
    }

    var filepath = tmp.join("/");

    return filepath;
}


function getUrlVar(id) {
    var qs = window.location.search.substring(1);
    var namevals = qs.split("&");

    for (i = 0; i < namevals.length; i++) {
        var name = namevals[i].split("=");
        if (name[0] == id) {
            return name[1];
        }
    }

    return null;   
}