/* main podOmatic javascript library */

/* capitalize */
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
};


var checked=false;
function flipAll(field) {
    checked=!checked
        for (i = 0; i < field.length; i++) {
            if (field[i].type != 'checkbox') { continue; }
            field[i].checked = checked ;
        }
    return false;
}

function anyChecked(field) {
    for (i = 0; i < field.length; i++) {
        if (field[i].type == 'checkbox' && field[i].checked) return true
                                                                 }
    return false;
}

function submitForm(){
    document.forms.item(0).submit();
}

function observePostcode() {
    new Form.Element.Observer('user_postcode', 0.5, function(element, value) { if (value.length >= 5) { new Ajax.Updater('city_state', '/user/zip_lookup', { onLoading:function(request){ document.getElementById("user_city").value="Loading..." }, parameters:'zip=' + escape(value), asynchronous:true}); }})
        }

function setFocus(id){
    document.getElementById(id).focus();
}

function changePlayerText(id, name) {
    var text = document.getElementById( id );
    if ( text != null ) {
        text.innerHTML = name;
    }
}

function displayToolTip(div_id, event, width, height) {
    showToolTip_wh(div_id, captureMousePosition(event || window.event),width,height);
}

function textLimit(field, maxlen) {
    if (field.value.length > maxlen + 1)
        alert('iTunes limits the summary text to '+maxlen+' characters.');
    if (field.value.length > maxlen)
        field.value = field.value.substring(0, maxlen);
}

var mode = '';
function setMode(new_mode)
{
    mode = '_' + new_mode;
}

function readCookie(name)
{
    var nameEQ = name + mode + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
        {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
    return null;
}

function loggedIn()
{
    if ( readCookie( 'om_login' ) == 'out' || readCookie('om_login') == null )
        return false;
    else
        return true;
}

function getLogin()
{
    x = readCookie( 'om_login' );
    if ( x ) {
        return x.substring( 3, x.length );
    }

    return '';
}

function getName()
{
    x = readCookie( 'info' );
    if ( x ) {
        return unescape( x ).split( "\001" )[1];
    }

    return '';
}

function getEmail()
{
    x = readCookie( 'info' );
    if ( x ) {
        return unescape( x ).split( "\001" )[0];
    }

    return '';
}

function distance_of_time_in_words(from_time, to_time, include_seconds) {
    from_t = new Date(from_time);
    to_t   = new Date(to_time);
    distance_in_minutes = Math.round(Math.abs(to_t - from_t)/(60 * 1000));
    distance_in_seconds = Math.round(Math.abs(to_t - from_t)/1000);
    out_s="";

    if (distance_in_minutes >= 0 && distance_in_minutes <= 1) {
        out_s='less than a minute';

        if (! include_seconds) {
            return out_s ;
        }
        if (distance_in_seconds >= 0 && distance_in_seconds < 5) {
            out_s='less than 5 seconds';
        } else if (distance_in_seconds >= 5 && distance_in_seconds < 10) {
            out_s='less than 10 seconds';
        } else if (distance_in_seconds >= 10 && distance_in_seconds < 20) {
            out_s='less than 20 seconds';
        } else if (distance_in_seconds >= 20 && distance_in_seconds < 30) {
            out_s='half a minute';
        } else if (distance_in_seconds >= 30 && distance_in_seconds < 60) {
            out_s='less than a minute';
        } else {
            out_s='1 minute';
        }
    } else if (distance_in_minutes > 1 && distance_in_minutes <= 45) {
        out_s= distance_in_minutes + ' minutes';
    } else if (distance_in_minutes > 45 && distance_in_minutes <= 90) {
        out_s='about 1 hour';
    } else if (distance_in_minutes > 90 && distance_in_minutes <= 1440) {
        out_s='about '+Math.round(distance_in_minutes / 60.0)+' hours';
    } else if (distance_in_minutes > 1440 && distance_in_minutes <= 2880) {
        out_s='1 day';
    } else {
        out_s = Math.round(distance_in_minutes / 1440) + ' days';
    }
    return out_s;
}

function quoteComment(src,author,dest,comment_time){
    header=distance_of_time_in_words(comment_time,new Date(), false)+' ago, ' +author+' wrote: '+"\n";
    destination=$(dest);
    destination.value=header+'> '+src.split("\n").join("\n> ")+"\n\n";
}

function searchIndexSelected(index_type) {
    if (index_type == 'podcast') {
        $('search_title').innerHTML='Search Podcasts';
        $('search_media_all').disabled=true;
        $('search_media_video').disabled=true;
        $('search_media_audio').disabled=true;

        $('media_type_radio').style.color='gray';

    } else {
        $('search_title').innerHTML='Search Episodes';
        $('search_media_all').disabled=false;
        $('search_media_video').disabled=false;
        $('search_media_audio').disabled=false;

        $('media_type_radio').style.color='black';
    }
}

function selectedStatus(display) {
    $('status_post_btn').style.display = display;
    if (display == 'inline') {
        $('status_input').value = 'is ';
        $('status_input').style.color = 'black';
    } else {
        $('status_input').value = 'What are you doing now?';
        $('status_input').style.color = 'gray';
    }
}

function selectedWallComment() {
    $('wall_comment_input').value = '';
    $('wall_comment_input').style.color = 'black';
}

function stranger_submit_msg() {
    var yn = true;
    if ($('subject').value.length == 0) {
        $('subject_err').display = 'block';
        yn = false;
    }
    if ($('message').value.length == 0) {
        $('message_err').display = 'block';
        yn = false;
    }
    if (yn) {
        this.form.submit();
    }
    return false;
}

function selectAllPhotos() {
    var tocheck = $('select_all').checked;
    var nodes = document.getElementsByClassName('item_check');
    for (ii =0 ; ii < nodes.length; ii++) {
        nodes[ii].checked = tocheck;
        if (tocheck)
            nodes[ii].value = '1';
        else
            nodes[ii].value = '0';
    }
    photoLinksValidation();
}

function selectPhoto(itemid) {
    if ($(itemid).checked) {
        $(itemid).value = '1';
    } else {
        $(itemid).value = '0';
    }
    photoLinksValidation();
}

function photoLinksValidation() {
    var nodes = document.getElementsByClassName('item_check');
    var numPublic=0, numPrivate=0;
    for (ii =0 ; ii < nodes.length; ii++) {
        if (nodes[ii].checked) {
            var privacyID = 'privacy_'+nodes[ii].id;
            if ('is_public' == $(privacyID).value) {
                numPublic += 1;
            } else {
                numPrivate += 1;
            }
        }
    }
    if (0 < numPublic) {
        if (0 < numPrivate) {
            $('private_link').style.display = 'inline';
            $('private_txt').style.display = 'none';
            $('public_link').style.display = 'inline';
            $('public_txt').style.display = 'none';
        } else {
            $('private_link').style.display = 'inline';
            $('private_txt').style.display = 'none';
            $('public_link').style.display = 'none';
            $('public_txt').style.display = 'inline';
        }
    } else if (0 < numPrivate) {
        $('private_link').style.display = 'none';
        $('private_txt').style.display = 'inline';
        $('public_link').style.display = 'inline';
        $('public_txt').style.display = 'none';
    } else {
        $('private_link').style.display = 'none';
        $('private_txt').style.display = 'inline';
        $('public_link').style.display = 'none';
        $('public_txt').style.display = 'inline';
    }
    if (0 < numPublic + numPrivate) {
        $('delete_link').style.display = 'inline';
        $('delete_txt').style.display = 'none';
    } else {
        $('delete_link').style.display = 'none';
        $('delete_txt').style.display = 'inline';
    }

    // only one photo selected
    if (1 == numPublic + numPrivate) {
        for (ii =0 ; ii < nodes.length; ii++) {
            if (nodes[ii].checked) {
                if (nodes[ii].id == $('profile_photo_id')) {
                    $('profile_photo_link').style.display = 'none';
                    $('profile_photo_txt').style.display = 'inline';
                } else {
                    $('profile_photo_link').style.display = 'inline';
                    $('profile_photo_txt').style.display = 'none';
                }
                break;
            }
        }
    } else {
        $('profile_photo_link').style.display = 'none';
        $('profile_photo_txt').style.display = 'inline';
    }

}

function submitPhotoEdit(doit) {
    $('didit').value = doit;
    if (doit == 'delete') {
        if (confirm('Delete selected photos?')) {
            document.forms[1].submit();
        }
    } else
        document.forms[1].submit();
}

function showpage_comment(epi_id, didreg) {
    var prefix = '';
    if (didreg || loggedIn()) {
        prefix = 'in';
    } else {
        prefix = 'out';
    }
    if (didreg) {
        close_lightbox(false);
    }
    var aa = $(prefix+'_epi_cmnt_'+epi_id);
    if (aa) aa.onclick();
    return false;
}

function add_friend(pid) {
    var prefix = '';
    if (loggedIn()) {
        prefix = 'in';
    } else {
        prefix = 'out';
    }
    var aa = $(prefix+'_add_frnd_'+pid);
    if (aa) aa.onclick();
    return false;
}
function showpage_add_friend(pid) {
    return add_friend(pid);
}

function loggedin_add_friend(tipid, url) {
    var xhReq = getXMLRequest();
    xhReq.open("GET", url, false);
    xhReq.send(null);
    var status = xhReq.responseText;
    if (status) {
    new Tip(tipid, {
        title : 'Friend Request',
            showOn: 'click',
            ajax: {
            url: url,
                     options: {
                     onComplete: function(transport) {
                         // you could do something here after the ajax call is finished
                     }
                                     }
        },
            hideOn: { element: 'closeButton', event: 'click' }
    });
    } else {
    }
}

function become_fan(pid) {
    var prefix = '';
    if (loggedIn()) {
        prefix = 'in';
    } else {
        prefix = 'out';
    }
    var aa = $(prefix+'_become_fan_'+pid);
    if (aa) aa.onclick();
    return false;
}

function loggedin_become_fan(tipid, url) {
    var xhReq = getXMLRequest();
    xhReq.open("GET", url, false);
    xhReq.send(null);
    var status = xhReq.responseText;
    if (status) {
    new Tip(tipid, {
        title : 'Become a Fan',
            showOn: 'click',
            ajax: {
            url: url,
                     options: {
                     onComplete: function(transport) {
                         // you could do something here after the ajax call is finished
                     }
                                     }
        },
            hideOn: { element: 'closeButton', event: 'click' }
    });
    } else {
    }
}

function loggedin_send_message(tipid, url, uname) {
    var xhReq = getXMLRequest();
    xhReq.open("GET", url, false);
    xhReq.send(null);
    var status = xhReq.responseText;
    if (status == 'friend') {
        location.href = '/mail/compose/'+uname
    } else {
        new Tip(tipid, 'You must be friends to send a message.', {title:'Send a message', showOn:'click', hideAfter: 3});
    }
}

function showpage_send_msg() {
    var prefix = '';
    if (loggedIn()) {
        prefix = 'in';
    } else {
        prefix = 'out';
    }
    var aa = $(prefix+'_send_msg');
    if (aa) aa.onclick();
    return false;
}

function quickreg_add_friend(pid) {
    close_lightbox(true);
    return false;
}

var selectedRow = null, selectedBG = null;

function media_row_selection(row_id, bg) {
    var row = $('episode[media_item_id]');
    var val = row.value;
    if (0 != val && $(val)) {
        $(val).style.color = 'black';
        $(val).style.backgroundColor = selectedBG;
    }
    $(row_id).style.backgroundColor = '#427FDE';
    $(row_id).style.color = 'white';
    selectedRow = row_id;
    selectedBG = bg;
    $('episode[media_item_id]').value = row_id;
}

function epi_img_selection(img_id) {
    var row = $('episode[image_id]');
    var val = row.value;
    if (0 != val && $(val)) {
        $(val).style.backgroundColor = 'white';
    }
    $(img_id).style.backgroundColor = '#427FDE';
    $('episode[image_id]').value = img_id;
}

function zone_img_selection(img_id) {
    var row = $('podzone[image_id]');
    var val = row.value;
    if (0 != val && $(val)) {
        $(val).style.backgroundColor = 'white';
    }
    $(img_id).style.backgroundColor = '#427FDE';
    $('podzone[image_id]').value = img_id;
}

function clearMedia() {
    $('episode[media_item_id]').value = null;
    $('t_media_form').submit();
}

function clearImage() {
    $('episode[image_id]').value = null;
    $('t_photo_form').submit();
}

function clearPodzoneImage() {
    $('podzone[image_id]').value = null;
    $('t_zone_form').submit();
}

function submitPublishForm(has_media) {
    var pub_date = $('episode[pub_date]').selectedIndex;

    if (pub_date != 2 && !has_media) {
        if (!confirm('The episode has no media attached!  Really publish?')) {
            return;
        }
    }

    if (1 == pub_date) {
        // do regex on $('pub_date_input') to validate date entered
    }
    /*
    var price = $('episode[price]');
    if (price) {
        var p_val = parseFloat(price.value);
        if (p_val != p_val || p_val <= 0) {
            alert('Could not commit changes.  The price must be greater than 0');
            return;
        }
    }
    */
    $('t_review_form').submit();
}

function submitPremiumGoogGateway(form_id) {
    var gid = $('pay_gateway[gateway_id]').value;
    var gkey = $('pay_gateway[gateway_key]').value;
    if (gid.length > 0 && gkey.length > 0) {
        $(form_id).submit();
    } else {
        alert('Please enter both a merchant ID and merchant key before continuing.  Consult the Google Checkout Settings page for more information.');
    }
}

function sellerNavLink(url) {
    if (url) {
        parent.location.href = url;
    }
}

function publishNavLink(this_task_id, next_task_id, url) {
    if (this_task_id) {
        var ff = $(this_task_id+'_form');
        if (ff) {
            var next_elem = $('selected_task_id');
            if (next_elem) {
                next_elem.value = next_task_id;
                ff.submit();
                return;
            }
        }
    }
    if (url) {
        parent.location.href = url;
    }
}

function browse_skin09_images(dir) {
    var image_ids = ['dub', 'turntable'];
    // var image_ids = ['poster', 'nightclub', 'funkyfresh', 'cosmic'];

    var selection = $('selected_skin_img').value;
    var idx = 0;
    for (var ii=0; ii < image_ids.length; ii++) {
        if (image_ids[ii] == selection) {
            idx = ii;
            break;
        }
    }
    $(selection).style.display = 'none';

    if (dir == 'prev') {
        idx -= 1;
        if (idx < 0) { idx = image_ids.length - 1; }

    } else if (dir == 'next') {
        idx += 1;
        if (idx == image_ids.length) { idx = 0; }
    }
    selection = image_ids[idx];
    $(selection).style.display = 'block';
    $('selected_skin_img').value = selection;

    $('skins_hdr_lhs').innerHTML = selection.substring(0,1).toUpperCase() + selection.substring(1,selection.length);
}

function load_chapter_player(media_url, dur) {
    var hostname = document.location.hostname;
    var flashvars = {
        skin:'http://'+hostname+'/swf/profile_skin.swf',
        file:media_url,
        // file:"rtmp://streams.podomatic.com/vod",
        streamer:"rtmp://streams.podomatic.com/vod",
        // id:media_url,
        autostart:"true",
        duration:dur,
        type:'rtmp'
    }
    var params = {
        allowfullscreen:"false",
        allowscriptaccess:"always"
    }
    var attributes = {
        id:"player1",
        name:"player1"
    }
    // swfobject.embedSWF('http://'+hostname+"/swf/mediaplayer.swf", "player_placeholder", "320", "40", "9.0.115",false,flashvars, params, attributes);
    swfobject.embedSWF('http://'+hostname+"/swf/profile_player.swf", "player_placeholder", "320", "40", "9.0.115",false,flashvars, params, attributes);
}

function browse_chapter_wizard_images(dir) {
    var image_ids = ['lb1', 'lb2', 'lb3'];

    var selection = $('selected_wiz_img').value;
    var idx = 0;
    for (var ii=0; ii < image_ids.length; ii++) {
        if (image_ids[ii] == selection) {
            idx = ii;
            break;
        }
    }
    $(selection).style.display = 'none';

    if (dir == 'prev') {
        idx -= 1;
        if (idx < 0) { idx = image_ids.length - 1; }

    } else if (dir == 'next') {
        idx += 1;
        if (idx == image_ids.length) { idx = 0; }
    }
    selection = image_ids[idx];
    $(selection).style.display = 'block';
    $('selected_wiz_img').value = selection;
}

