
var noFormFocus = true;
var isLoggedIn = false;
var hasEvents = false;
var currentsite = "";
var tagParamArray;
var demoParamArray;
var keyTimeout;
var dataArray = new Array();
var siteArray = new Array(
    "MySpace", "TypePad", "Widgetbox", "Blogger", "hi5",
    "blogigo", "Frappr", "Friendster", "Google", "myYearbook",
    "Netvibes", "Piczo", "TagWorld", "WordPress", "Xanga", "Other"
    );

if($("#holdMaker")[0] == undefined) {
    addEvent(window, 'load', initMaker);
}

function initMaker()
{
    var indImg = new Image(6, 6);
    indImg.src = "/images/indicator.gif";

    if (selectedEventID == "")
        $("#pagetitle").html("Promote Your ChipIns");
    else {
        $("#pagetitle").html("Promote Your ChipIn");
        if (!isLoggedIn)
            $("#pagetitle").html("Promote This ChipIn");
    }
    if (isSubcampaign)
        $("#pagetitle").html("Promote Your Subcampaign");

    if (webUser != "")
        isLoggedIn = true;
    dataArray = $("#datatable tr").get();
    if (dataArray.length == 0)
        hasEvents = false;
    else
        hasEvents = true;
    if (isSubcampaign) {
        hasEvents = true;
        isLoggedIn = true;
    }

    if (!isLoggedIn) {
        txt = '<a href="/signup">Sign up now</a> to use the widget or <a href="/overview">learn more</a> about ChipIn!</a>';
        $("#createsection").html(txt);
        if (selectedEventID == "") {
            $("#infosection").show();
            $("#infosection h2 span").remove();
        }
    } else
        $("#pagelink").show();
    if (isSubcampaign)
        $("#pagelink").hide();

    if (!hasEvents) {
        $("#sitelistsection h2").html("You can put the widget on these sites:");
        $("#sitelistsection").show();
        $("#createsection").show();
    } else {
        $("#sitelistsection h2").html("2. Select where you want to put your widget:");
        $("#widgetsection").show();
        $("#sitelistsection").show();
        setCopyKey();
        optStr = "";
        $.each(dataArray, function(i) {
            rowArray = $(this).find("td").get();
            name = $(rowArray[0]).text();
            eid = $(rowArray[1]).html();
            document.widgetform.event.options[i] = new Option(name, eid);
            if (selectedEventID != "" &&
            eid == selectedEventID) {
                document.widgetform.event.options[i].selected = true;
                titleObj = $(".page:eq(0) h1:eq(0)")[0];
                titleObj.style.marginBottom = "0";
            }
        });
        if (is_ie) {
            wObj = $("#widgetframe")[0];
            if (wObj)
                wObj.innerHTML = '<iframe name="wframe" width="100%" height="100%" scrolling="no" frameborder="0" src="/widget/widget.swf"/>';
        }
        setWidget();
    }

    $("#widgetsection h2").append('&nbsp;<span style="font-size:12px">(<a href="#" onclick="return false;">what\'s this?</a>)</span>');
    $("#widgetsection h2 a").click(function() {
        $("#infosection").show();
        $("#widgetsection").hide();
    });

    if (hasCreatedEvents != "true" && isLoggedIn && !isSubcampaign) {
        $("#infosection").show();
        $("#widgetsection").hide();
    }

    if (isTypepad == "true") {
        $("#pagesubtitle").html("Add a ChipIn widget to your TypePad post or sidebar");
        $("#pagesubtitle").show();
        $("#sitelistsection").hide();
        selectSite("TypePad", -1);
        $("#widget_dimensions").val("160x250");
        setWidget();
        $("#codesection .stepnum").html("2.");
        $("#instructionsection .stepnum").html("3.");
    } else if (isWidgetbox == "true") {
        $("#pagesubtitle").html("Add a ChipIn widget via Widgetbox");
        $("#pagesubtitle").show();
        $("#sitelistsection").hide();
        selectSite("Widgetbox", -1);
        $("#codesection").hide();
        $("#instructionsection .stepnum").html("3.");
    }

    listSites(4, 5);
    if (!hasEvents) {
        $("#sitelisttable td a").each(function() {
            label = $(this).html();
            $(this).after(label).remove();
        });
    }

    if (isSubcampaign) {
        $("#widgetinforow").hide();
        $("#widgetsizerow").hide();
        $("#widgetcolorrow").hide();
        $("#widgetnote").hide();
    }
    $(".loadingmsg").hide();
}

function setWidget()
{
    window.clearTimeout(keyTimeout);

    if (!isSubcampaign) {
        selectedPos = document.widgetform.event.selectedIndex;
        selectedEvent = $("#eventselect option")[selectedPos];
        eventID = selectedEvent.value;
    }

    addObjectTag = true;
    tagParamArray = new Array();
    demoParamArray = new Array();
    tagsrc = "http://widget.chipin.com/widget/id/" + eventID;
    demosrc = widgetProtocol + widgetServer +
        "/widget/id/" + eventID;
    addDemoParam("chipin_server", widgetServer);

    site = "";
    if (currentsite != "")
        site = currentsite.toLowerCase();
    if (site == "myspace") {
        addTagParam("show_url", "true");
        addObjectTag = false;
    } else if (site == "evite") {
        addObjectTag = false;
    } else if (site == "typepad") {
        addObjectTag = false;
    } else if (site == "wordpress") {
        addObjectTag = false;
    }
    else if(site =="myyearbook")    {
        addTagParam("show_url", "true");
    }
    if (eventID == "")
        addDemoParam("use_sample_data", "true");

    titleObj = document.getElementById("event_title").value;
    if (titleObj != "")
        addTagDemoParam("event_title", escape(titleObj));
    descObj = document.getElementById("event_desc");
    if (descObj && descObj != "" && (descObj.value)) {
        descObj = document.getElementById("event_desc").value;
        addTagDemoParam("event_desc", escape(descObj));
    }

    if (isSubcampaign) {
        addTagDemoParam("sc_target_amount", $("#targetamount").val());
        // addTagDemoParam("sc_end_time", $("#campaignEndTime").html());
    }

    d = document.getElementById("widget_dimensions");
    if (d && d != "" && (d.value)) {
        d = d.value;
        dArray = d.split("x");
        widgetWidth = dArray[0];
        widgetHeight = dArray[1];
    } else {
        widgetWidth = 250;
        widgetHeight = 250;
    }

    cs = document.getElementById("widget_colors");
    if (cs && cs != "" && (cs.value)) {
        addTagDemoParam("color_scheme", cs.value);
    }
    addDemoParam("color_stage", "e5e5e5");
    addDemoParam("show_copytab", "false");

    paramStr = "";
    attStr = "";
    for (paramName in demoParamArray) {
        paramVal = demoParamArray[paramName];
        paramStr += "<param name=\"" + paramName + "\" value=\"" + paramVal + "\"></param>";
        attStr += "&" + paramName + "=" + paramVal;
    }
    demostr = "";
    if (!is_ie)
        demostr += "<object width=\"" + widgetWidth + "\" height=\"" + widgetHeight + "\">" + "<param name=\"movie\" value=\"" + demosrc + "\"></param>" + "<param name=\"allowScriptAccess\" value=\"always\"></param><param name=\"wmode\" value=\"transparent\"></param>" + paramStr;
    demostr += "<embed src=\"" + demosrc + "\" " + "flashVars=\"" + attStr.substr(1) + "\" " + "type=\"application/x-shockwave-flash\" allowScriptAccess=\"always\" wmode=\"transparent\" " + "width=\"" + widgetWidth + "\" height=\"" + widgetHeight + "\"></embed>";
    demoAttStr = attStr;
    if (!is_ie)
        demostr += "</object>";

    paramStr = "";
    attStr = "";
    for (paramName in tagParamArray) {
        paramVal = tagParamArray[paramName];
        paramStr += "<param name=\"" + paramName + "\" value=\"" + paramVal + "\"></param>";
        attStr += "&" + paramName + "=" + paramVal;
    }
    tagstr = "";
    if (addObjectTag)
        tagstr += "<object width=\"" + widgetWidth + "\" height=\"" + widgetHeight + "\">" + "<param name=\"movie\" value=\"" + tagsrc + "\"></param>" + "<param name=\"allowScriptAccess\" value=\"always\"></param><param name=\"wmode\" value=\"transparent\"></param>" + paramStr;
    tagstr += "<embed src=\"" + tagsrc + "\" " + "flashVars=\"" + attStr.substr(1) + "\" " +
        "type=\"application/x-shockwave-flash\" allowScriptAccess=\"always\" wmode=\"transparent\" " +
        "width=\"" + widgetWidth + "\" height=\"" + widgetHeight + "\"></embed>";
    if (addObjectTag)
        tagstr += "</object>";

    if (has_flash) {
        if (is_ie)
            wObj = $("#widgetframe iframe").attr("src",
                demosrc + "?" + demoAttStr.substr(1));
        else
            $("#widgetframe").html(demostr);
    } else
        $("#widgetframe").html('<div style="background: #ffffb4; padding: 10px; border: 1px solid #fbbf15; font-size: 18px;font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; font-weight: bold; color: #d22119; text-align: center">The ChipIn widget requires Flash 8 or greater. Install the latest version of Flash by <a style="color: #536731" href="http://www.macromedia.com/go/getflashplayer" target="_blank">clicking here</a>, then quit and relaunch your browser.</div>');
    $("#widgetframe").css("width", widgetWidth + "px");
    $("#widgetframe").css("height", widgetHeight + "px");

    document.getElementById("widgettag").value = tagstr;

    // Fix width/height for typepad sidebar
    typepadTagStr = tagstr.replace(/width=\"(\d)*\" height=\"(\d)*\"/g, "width=\"160\" height=\"250\"");
    $("#typepadContent").val(typepadTagStr);

    bloggerTagStr = tagstr.replace(/</g, "&lt;");
    bloggerTagStr = bloggerTagStr.replace(/>/g, "&gt;");
    bloggerTagStr = bloggerTagStr.replace(/"/g, "'");
    $("#bloggerForm input[@name=widget.title]").attr("value",
        escape(titleObj));
    $("#bloggerForm input[@name=widget.content]").attr("value",
        bloggerTagStr);

    widgetboxLink = "http://www.widgetbox.com/widget/chipin?_wbx_external=1";
    widgetboxLink += "&event_id=" + eventID;
    widgetboxLink += "&event_title=" + encodeURIComponent(titleObj);
    widgetboxLink += "&event_desc=" + encodeURIComponent(descObj);
    widgetboxLink += "&color_scheme=" + cs;
    widgetboxLink += "&size=" + widgetWidth + "x" + widgetHeight;
    $("#wbxlink").attr("href", widgetboxLink);
}

function hideHelp()
{
    $("#infosection").hide();
    if (hasEvents || isSubcampaign) {
        $("#widgetsection").show();
        setWidget();
    }
}

function listSites(cols, rows)
{
    sitelist = "";
    rownum = 0;
    for (c = 0; c < cols; c++) {
        sitelist += "<tr>";
        for (r = 0; r < rows; r++) {
            index = (rows * c) + r;
            if (index < siteArray.length) {
                nameitem = siteArray[index];
                name = nameitem.toLowerCase();
                if (name == "other")
                    sitelist += "<td></td><td></td>";
                sitelist += "<td><img src=\"/images/favicons/icon." + name + ".png\" alt=\"\" width=\"16\" height=\"16\" style=\"margin-right:5px\"/><a href=\"#\" id=\"" + nameitem + "\" onclick=\"selectSite(\'" + nameitem + "\');return false;\">" + nameitem + "</a></td>";
            }
        }
        sitelist += "</tr>";
        if (rownum == 0)
            sitelist += '<tr><td colspan="' + rows + '"><div style="overflow:hidden;height:1px;border-bottom: 1px solid #999999"></div></td></tr>';
        rownum++;
    }
    if (is_ie) {
        sitelist = '<table id="sitelisttable">' +
            sitelist + '</table>';
        $("#sitelisttablewrap").html(sitelist);
    } else
        $("#sitelisttable").html(sitelist);
    $("#sitelisttable tr").find("td").each(function() {
        $(this).css("paddingTop", "4px");
        $(this).css("paddingBottom", "4px");
        $(this).css("paddingLeft", "8px");
        $(this).css("paddingRight", "8px");
        if (hasEvents) {
        $(this).mousedown(function() {
            $(this).find("a").click();
        });
        $(this).find("a").parent().hover(function() {
            $(this).css("cursor", "pointer");
            if ($(this).find("a").attr("id") ==
            currentsite) {
                $(this).css("backgroundColor", "#ffffb4");
                $(this).find("a").css("color", "black");
            } else {
                $(this).css("backgroundColor", "#fafafa");
                $(this).find("a").css("color", "#ab3636");
            }
        }, function() {
            $(this).css("cursor", "");
            if ($(this).find("a").attr("id") ==
            currentsite) {
                $(this).css("backgroundColor", "#ffffb4");
                $(this).find("a").css("color", "black");
            } else {
                $(this).css("backgroundColor", "");
                $(this).find("a").css("color", "#536731");
            }
        });
        }
    });
}

function setCopyKey()
{
    copykeytxt = "Ctrl-C";
    if (is_mac)
        copykeytxt = "\u2318" + "-C";
    $("#copykey").html(copykeytxt);
}

function addDemoParam(paramName, paramVal)
{
    if (paramVal == "")
        return;
    demoParamArray[paramName] = paramVal;
}

function addTagParam(paramName, paramVal)
{
    if (paramVal == "")
        return;
    tagParamArray[paramName] = paramVal;
}

function addTagDemoParam(paramName, paramVal)
{
    if (paramVal == "")
        return;
    tagParamArray[paramName] = paramVal;
    demoParamArray[paramName] = paramVal;
}

function selectSite(site)
{
    currentsite = site;

    if (hasEvents) {
    $("#sitelisttable a").each(function() {
        $(this).css("fontWeight", "normal");
        $(this).css("color", "");
    });
    $("#sitelisttable #" + site).each(function() {
        $(this).css("fontWeight", "bold");
        $(this).css("color", "black");
        $(this).parent().css("backgroundColor", "#ffffb4");
    });
    $("#sitelisttable tr").find("td").each(function() {
        if ($(this).find("a").attr("id") != currentsite)
            $(this).css("backgroundColor", "");
    });
    }

    sitestr = site;
    if (site == "Other")
        sitestr = "another Web site";
    $("#sitelabel1").html(sitestr);
    site = site.toLowerCase();

    showID = false;
    if (site == "google" || site == "netvibes" ||
    site == "widgetbox")
        showID = true;
    if (site == "widgetbox") {
        $("#codesection").hide();
        $("#instructionsection .stepnum").html("3.");
    } else {
        $("#codesection").show();
        $("#instructionsection .stepnum").html("4.");
    }
    $("#instructionsection").show();

    codestr = "code";
    if (showID == true) {
        codestr = "event ID";
        $("#widgettag").val(eventID);
    } else
        setWidget();
    $("#sitelabel2").html(codestr);

    selectInfo(site);
    // document.location = "#sitelist";
}

function selectInfo(site)
{
    stepnum = 1;
    errtext = "";
    infotext = "<ul>";
    $("#instructionstext ol").find("li:eq(0)").each(function() {
        if ($.trim(this.innerHTML) == site) {
            $(this).siblings().each(function() {
                linetxt = $(this).html();
                if (linetxt.indexOf("formError") != -1)
                    errtext += linetxt;
                else {
                    infotext += "<li><label>Step " +
                        stepnum + ":</label> " +
                        linetxt + "</li>";
                    infotext += getInfoImage(site,
                        stepnum - 1);
                    stepnum++;
                }
            });
        }
    });
    infotext += "</ul>";
    $("#instructions").html(errtext + infotext);
}

function getInfoImage(site, stepnum)
{
    stepnum++;
    testimg = new Image();
    imgurl = "/widget/instructions/" +
        site + "." + stepnum + ".png";
    imgstr = "<div class=\"infoimage\"><img src=\"" + imgurl + "\" onerror=\"this.style.display=\'none\';\" alt=\"\"/></div>";
    return imgstr;
}

function didFieldKeypress()
{
    window.clearTimeout(keyTimeout);
    keyTimeout = window.setTimeout('setWidget()', 1000);
}

function returnFilter(obj, e)
{
    didFieldKeypress();
    key = (e.which) ? e.which : e.keyCode;
    if (key == 8)
        return true;
    else if (key <= 13) {
        if (obj.value != "")
            setWidget();
        if (key != 9) {
            stopEvent(obj, e);
            return false;
        }
    }
    return true;
}

function strim(s)
{
    return s.replace(/^\s+|\s+$/, '');
}
