//setup the check for w3c compliance
var W3CDOM = (document.createElement && document.getElementById);

//make built fields available at global scope
var field_screen_name;
var label_screen_name;
var field_exlink;
var label_exlink;
var field_content;
var label_content;
var field_title;
var label_title;
var share_form;
var field_page_state;
var field_session_id;
var container_hiddens;
var container_name;
var container_link;
var container_content;
var container_title;
var container_submit;


function prepAdditionalContent() {
    var need_content = [];
    var raw_id = [];
    for (i=0; i < $('#homePrimary > p.homePrimaryHeading').size(); i++) {
         if ($('#homePrimary > p.homePrimaryHeading ~ p:contains("...")').eq(i)) {
              need_content.push($('#homePrimary > p.homePrimaryHeading ~ p').eq(i));
//              alert(need_content[i].text());
              raw_id.push($('#homePrimary > p.homePrimaryHeading > a').eq(i).attr('href').substring(15));
              need_content[i].append($('<a href=\"' + raw_id[i] + '\">read more</a>.'));
         }
    }
}



// takes identified link and adds specified onclick action
// example: addLinkAction('#share_link',surfaceShareForm)
function addLinkAction(identifier,func) {
    if (!W3CDOM) return;
    link = $(identifier);
    link.bind("click", function(event) {
        event.preventDefault();
        func();
    });
    return false;
}

// removes event from link
// example: removeLinkAction('#share_link',surfaceShareForm)
function removeLinkAction(identifier,func) {
    if (!W3CDOM) return;
    link = $(identifier);
    link.unbind('click');                         // unbind the function
    link.bind('click',function(){return false;}); // disable the normal link action
    return false;
}

function buildShareForm() {
    if (!W3CDOM) return;

    share_form = document.createElement("form");
    share_form = $('<form id=\"share_form\"></form>')
                   .attr('method','POST')
                   .attr('action','/share2/')
                   .attr('name','share_form')
                   .attr('onsubmit','return validateForm2(this)');

    //build the field-containing divs
    container_div = $('<div></div>').attr('class','field');
    container_hiddens = $(container_div).clone();
    container_name = $(container_div).clone();
    container_link = $(container_div).clone();
    container_content = $(container_div).clone();
    container_title = $(container_div).clone();
    container_submit = $(container_div).clone();

    //build the hidden fields
    field_session_id = $('<input type=\"hidden\"\>')
                         .attr('name','sessionIdentityId')
                         .attr('value',sessionId);
    field_page_state = $('<input type=\"hidden\"\>')
                         .attr('name','pageState')
                         .attr('value','10');
    field_view_state = $('<input type=\"hidden\"\>')
                         .attr('name','viewStateId')
                         .attr('value','ViewState66220');
    field_homepage_flag = $('<input type=\"hidden\"\>')
                         .attr('name','home_page_flag')
                         .attr('value','yes');
    $(container_hiddens).append(field_session_id);
    $(container_hiddens).append(field_page_state);
    $(container_hiddens).append(field_view_state);
    $(container_hiddens).append(field_homepage_flag);


    //build the screenname field
    field_screen_name = $('<input type=\"text\"\>')
                          .attr('name','screenName')
                          .attr('id','share_screenName')
                          .attr('size','25')
                          .attr('maxlength','80')
                          .attr('value',sn);
    label_screen_name = $('<label\>').attr("for","share_screenName").text('* Screen Name');
    $(container_name).append(label_screen_name);
    $(container_name).append(field_screen_name);

    field_exlink = $('<input type=\"text\"\>')
                     .attr('name','share_externalLink')
                     .attr('id','share_externalLink')
                     .attr('size','25')
                     .attr('maxlength','256')
                     .attr('value','');
    label_exlink = $('<label\>').attr('for','share_externalLink').text('* External Link');
    $(container_link).append(label_exlink);
    $(container_link).append(field_exlink);

    field_content = $('<textarea></textarea>')
                       .attr('name','share_storyContent')
                       .attr('id','share_storyContent')
                       .attr('cols','25')
                       .attr('rows','5')
                       .text('');
    label_content = $('<label\>').attr('for','share_storyContent').text('* Story Content');
    $(container_content).append(label_content);
    $(container_content).append(field_content);


    field_title = $('<input type=\"text\"\>')
                     .attr('name','share_storyTitle')
                     .attr('id','share_storyTitle')
                     .attr('size','25')
                     .attr('maxlength','1000')
                     .attr('value','');
    label_title = $('<label\>').attr('for','share_storyTitle').text('* Share Title');
    $(container_title).append(label_title);
    $(container_title).append(field_title);

    //build the submit button
    field_submit = $('<input type=\"submit\"\>')
                     .attr('id','share_submit')
                     .attr('name','submit1')
                     .attr('value','Share Your Story')
                     .attr('class','button');
    field_cancel = $('<input type=\"button\"\>')
                     .attr('id','share_cancel')
                     .attr('name','share_cancel')
                     .attr('value','Cancel')
                     .attr('class','button');
    $(container_submit).append(field_submit);
    $(container_submit).append(field_cancel);
}


function surfaceShareForm() {
    if (!W3CDOM) return;
    anchor = $('#homePrimary');
    var popup = $('<div></div>').attr('id','special2');
    var heading = $('<p></p>')
                    .attr('class','popup')
                    .attr('style','font-weight: bold; font-size: 1.3em;')
                    .text('Share a Story');
    var instr = $('<p></p>').text('please fill out all fields.');
    $(popup).append(heading);
    $(popup).append(instr);
    $(anchor).append(popup);

    $(popup).append(share_form);
    $(share_form).append(container_hiddens);
    $(share_form).append(container_name);
    $(share_form).append(container_link);
    $(share_form).append(container_title);
    $(share_form).append(container_content);
    $(share_form).append(container_submit);
    // bind cancel to this function here because it won't work 
    // more than once if bound in buildShareForm()
    $('#share_cancel').bind("click", function() {
         removeForm();
         return true;
    });
    removeLinkAction('#share_link',surfaceShareForm);
}



function removeForm() {
    if (!W3CDOM) return;
    if ($('#special2')) {
         $('#special2').remove();
         addLinkAction('#share_link',surfaceShareForm);
    }
}





function previewImage(id,key) {
    if (!W3CDOM) return;
    base = "/webshare/images/memberimage.jhtml?id=";
    image = $('<img\>').attr('src',base + id + '&key=' + key + '&prop=profile_image')
    thumb = $('<img\>').attr('src',base + id + '&key=' + key + '&prop=profile_image_thumbnail')
    $('#image_preview').append(image);
    $('#image_preview').append(thumb);
}





// ------------------ form validation ------------//
function validateForm2(form) {
    if (isNotEmpty(form.share_screenName,"Screen Name")) {
         return true;
    } else {
         container_name.setAttribute("class","field error");
         return false;
    }

    if (isNotEmpty(form.share_externalLink,"External Link")) {
         return true;
    } else {
         container_link.setAttribute("class","field error");
         return false;
    }
    if (isNotEmpty(form.share_storyTitle,"Story Title")) {
         return true;
    } else {
         container_title.setAttribute("class","field error");
         return false;
    }
    if (isNotEmpty(form.share_storyContent,"Story Content")) {
         return true;
    } else {
        container_content.setAttribute("class","field error");
         return false;
    }
}

function validateForm(form) {
    if (isNotEmpty(form.share_screenName,"Screen Name")) {
         container_name.setAttribute("class","field error");
         if (isNotEmpty(form.share_externalLink,"External Link")) {
              container_link.setAttribute("class","field error");
              if (isNotEmpty(form.share_storyTitle,"Story Title")) {
                   container_title.setAttribute("class","field error");
                   if (isNotEmpty(form.share_storyContent,"Story Content")) {
                       container_content.setAttribute("class","field error");
                        return true;
                   }
              }
         }
    }
    return false;
}


// validates that the field value string has one or more characters in it
function isNotEmpty(elem,fld) {
    var str = elem.value;
    if(str == null || str.length == 0) {
        //alert("Please fill in the required " + fld + " field.");
        return false;
    } else {
        return true;
    }
}

function tweakLoginForm() {
    if (!W3CDOM) return;
    $('input#grid-username').example('email address');
}



$(document).ready(function(){
   tweakLoginForm();
 });