/* copy a string to a user's clipboard.  This loads /flash/clipboard.swf . */
function copy(text2copy) {
    if (false /*window.clipboardData*/) {
        window.clipboardData.setData("Text",text2copy);
    } else {
        var flashcopier = 'flashcopier';
        if(!document.getElementById(flashcopier)) {
            var divholder = document.createElement('div');
            divholder.id = flashcopier;
            document.body.appendChild(divholder);
        }
        document.getElementById(flashcopier).innerHTML = '';
        var divinfo = '<embed src="/flash/_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        document.getElementById(flashcopier).innerHTML = divinfo;
    }
}

function captureMousePosition(e) {
    if (document.layers) {
        // When the page scrolls in Netscape, the event's mouse position
        // reflects the absolute position on the screen. innerHight/Width
        // is the position from the top/left of the screen that the user is
        // looking at. pageX/YOffset is the amount that the user has
        // scrolled into the page. So the values will be in relation to
        // each other as the total offsets into the page, no matter if
        // the user has scrolled or not.
        xMousePos = e.pageX;
        yMousePos = e.pageY;
    } else if (document.all) {
        // When the page scrolls in IE, the event's mouse position
        // reflects the position from the top/left of the screen the
        // user is looking at. scrollLeft/Top is the amount the user
        // has scrolled into the page. clientWidth/Height is the height
        // width of the current page the user is looking at. So, to be
        // consistent with Netscape (above), add the scroll offsets to
        // both so we end up with an absolute value on the page, no
        // matter if the user has scrolled or not.
        xMousePos = window.event.x+document.body.scrollLeft;
        yMousePos = window.event.y+document.body.scrollTop;
    } else if (document.getElementById) {
        // Netscape 6 behaves the same as Netscape 4 in this regard
        xMousePos = e.pageX;
        yMousePos = e.pageY;
    }

    return [ xMousePos, yMousePos ];
}

function showToolTip(obj_id, pos) {
    obj = document.getElementById( obj_id );

    obj.style.top  = pos[1];
    obj.style.left = pos[0];

    obj.style.display='block';

    document.onmousedown=function() {
        document.getElementById(obj_id).style.display='none';
        document.onmousedown=function(){};
    };
        }

function showToolTip_wh(obj_id, pos, width, height ) {
    obj = document.getElementById( obj_id );

    obj.style.top  = pos[1];
    obj.style.left = pos[0];

    obj.style.display='block';
    obj.style.height=height;
    obj.style.width=width;

        document.onmousedown=function() {
            document.getElementById(obj_id).style.display='none';
            document.onmousedown=function(){};
        };
        }
function revShowToolTip(obj_id, pos, width, height ) {
    obj = document.getElementById( obj_id );

    obj.style.top  = ( pos[1] - height );
    obj.style.left = ( pos[0]  - width );

    obj.style.display='block';

    document.onmousedown=function() {
        document.getelementbyid(obj_id).style.display='none';
        document.onmousedown=function(){};
    };
        }
function showToolTipForm(obj_id, pos, width, height) {
    obj = document.getElementById( obj_id );

    obj.style.top  = ( pos[1] - height );
    obj.style.left = ( pos[0]  - width );

    obj.style.display='block';
    obj.inner_html += '<a onclick="$('+obj_id+").style.display='none'\">close</a>";
        }


function episode_edit_select_library() {
    //    $('episode_edit_file_upload').value = '';
        return false;
}
function check_episode_title() {
    if (document.getElementById('episode[title]').value.length > 0)  {
        return true;
    }
    alert('Title must not be blank');
    return false;
}

function click_tag(elem_id, tt, index) {
    $(elem_id).value += ' ' + tt;
    tag_id = 'tag_'+index;
    anchor_id = 'a_'+index;
    $(tag_id).style.background = 'blue';
    $(anchor_id).style.color = 'white';
}
function click_tag_pub(elem_id, tt, index) {
    $(elem_id).value += ' ' + tt;
}
function check_tag_limit(id_val) {
    var tags = document.getElementById(id_val).value;
    var a_tags = tags.split(/( |,)/);
    var num_tags = 0;
    for (var idx = 0; idx < a_tags.length; idx++) {
        if (a_tags[idx].length > 0 && !(a_tags[idx]==',' || a_tags[idx]==' ')) {
            num_tags++;
        }
    }
    if (num_tags > 12) {
        alert('There is a limit of 12 tags per episode.  You have '+num_tags+'.');
        return false;
    }
    return true;
}

function convert_radio_select(selected_id) {
    $('qlty_wmv').style.display = 'none';
    $('qlty_mp4').style.display = 'none';
    $('qlty_3gp').style.display = 'none';
    if (selected_id) {
        $(selected_id).style.display = 'block';
    }
    return true;
}

function editing_published_confirm() {
    var yn = confirm("You have changed the media associated with this published episode.  If you continue, your episode will become hidden from your podcast page until you complete the Review & Publish step.\n\nWould you like to continue?");
    return yn;
}

function getXMLRequest() {
        var xmlReq = null;
        if (window.XMLHttpRequest) {
            xmlReq = new XMLHttpRequest();
        } else {
            xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xmlReq;

}


/* this checks whether the media is changing
   when editing an episode
*/
function episode_media_selected(upload_redirect_url, media_id) {
    // given the currently selected media_item_id,
    // checks the media selection widgets for changes;
    // widgets include pull-down, upload file, and record
    // if the episode is published, then warn user
    // their episode will become hidden untill next publish

    var is_upload = false;  // $('episode_edit_file_upload').value.length != 0;
    var should_continue = true;

    if (media_id !== null) {    // only passed in if episode is already published
        // check if upload, media item changed, or recording
        if (!is_upload) {
            // check if media item changed or recording
            if ($('recorded_fn') && $('recorded_fn').value.length > 0) {
                should_continue = editing_published_confirm();  //is it a recording?
            } else {
                if ($('media_item').value != media_id) {
                    should_continue = editing_published_confirm();  //did the media item change?
        }
            }
        } else {
            should_continue = editing_published_confirm();  // its an upload
        }
    }
    if (!should_continue) { return false; }

    if (!is_upload) {
        var media_url;
        if ($('recorded_fn') && $('recorded_fn').value.length > 0) {
            media_url = '/episode/recording/'+$F('id')+'?recorded_fn='+$('recorded_fn').value+'&recorded_id='+$('recorded_id').value;

        } else {
            var mid;
            if ($('media_item')===null) {
                mid = 0;
            } else {
                mid = $F('media_item');
            }
            // work around for Internet Explorer bug!  WTF is wrong with Microsoft?
            media_url = '/episode/mediaitem/'+$F('id')+'?mi='+mid;
            // clear the form onsubmit cause its loaded with progress stuff for uploading
            // $('episode_upload_form').onsubmit = null;
            // $('episode_upload_form').target = null;
        }


        var xhReq = getXMLRequest();  // new XMLHttpRequest();
        xhReq.open("GET", media_url, false);
        xhReq.send(null);

        var uu = '/episode/info/'+$('id').value;
        parent.window.location.href = uu;
        return false;

    }
    return true;
}

function episode_upload_selected(media_id) {
    // given the currently selected media_item_id,
    // checks the media selection widgets for changes;
    // widgets include pull-down, upload file, and record
    // if the episode is published, then warn user
    // their episode will become hidden untill next publish

    var uppath = $('episode_edit_file_upload').value;
    if (uppath.match(/.*\/(.*\..*)/) || uppath.match(/.*\\(.*\..*)/)) {
        $('upload_filename').innerHTML = '&nbsp;&nbsp;Uploading file: '+RegExp.$1;
        $('upload_filename').style.display = '';
        $('upload_media_submit').style.display = 'none';
    }
    // $('episode_edit_file_upload').enabled = false;

    var is_upload = uppath.length != 0;
    // var is_upload = $('episode_edit_file_upload').value.length != 0;
    var should_continue = true;

    if (media_id !== null) {    // only passed in if episode is already published
        // check if upload, media item changed, or recording
        should_continue = editing_published_confirm();  // its an upload
    }
    if (!should_continue) { return false; }

    if (is_upload) {
        var xhReq1 = getXMLRequest();  // new XMLHttpRequest();
        xhReq1.open("GET", '/episode/uploading/'+$('id').value+'?state=begin', false);
        xhReq1.send(null);
    }
    return true;
}

function clear_frame_if_upload_complete() {
    // deprecated, i.e., not called
    //alert("clear_frame_if_upload_complete");

    if (parent.frames[0] && parent.frames[0].document.getElementById('episode_upload_complete_view')) {
        if ('block' == parent.frames[0].document.getElementById('episode_upload_complete_view').style.display) {

            if (parent.frames[1].window.location.href.match(/.*?episode.*?/)) {

                /* upload completed, and we're editing episode, so reset frames so top is active, bottom inactive  */
                parent.frames[0].document.getElementById('episode_upload_progress_view').style.display = 'none';
                parent.frames[0].document.getElementById('episode_upload_complete_view').style.display = 'none';

                parent.frames[0].window.location.href = parent.frames[1].window.location.href;
                //alert('clear_frame_if_upload_complete(): '+parent.frames[0].window.location.href);

                parent.document.getElementById('upload_frameset').rows = "0, *";
            }
        }
    }
}

function upload_finished(errors) {
    if ($('is_uploading')) { $('is_uploading').style.display = 'none';}
    if ($('not_uploading')) { $('not_uploading').style.display = 'block'; }

    var xhReq1 = getXMLRequest();  // new XMLHttpRequest();
    xhReq1.open("GET", '/episode/uploading/'+$('id').value+'?state=end', false);
    xhReq1.send(null);

    //        $('episode_upload_progress_view').style.display = 'none';
    //        $('episode_upload_complete_view').style.display = 'block';

        /*
    if (parent.frames[0]) {
        parent.frames[0].document.getElementById('episode_upload_progress_view').style.display = 'none';
        parent.frames[0].document.getElementById('episode_upload_complete_view').style.display = 'block';

        var hh = parent.frames[1].window.location.href;
        if (hh.match(/.*?episode.*?/) || hh.match(/.*?podcast\/post.*?/)) {
            parent.frames[1].window.location.reload();
            parent.document.getElementById('upload_frameset').rows = "0, *";
        }
    }
        */
    if (errors) {
        alert(errors);
    }
    return true;
}

function deactivate_upload(elem, url) {
    if (elem) {
        elem.stop();
    }

    // must be synchronous
    var xhReq = getXMLRequest();  // new XMLHttpRequest();
    xhReq.open("GET", url, false);
    xhReq.send(null);

    //alert('deactivate_upload');
    clear_frames();
    // parent.document.getElementById('upload_frameset').rows = "0, *";

    return false;
}


function check_frames(url) {
    // if (parent.frames.length > 0)
    if (parent.document.getElementById('upload_frameset')) {
        var myAjax = new Ajax.Request(url, {method: 'get'});
    }
}

function should_delete_episode() {
    var episode_id = $('id');
    if (episode_id.value) {
        var url = '/episode/should_delete/'+episode_id.value;
        var myAjax = new Ajax.Request(url, {method: 'get'});
    }
    return true;
}

function copy_post_contents() { $('gigya_code_post').innerHTML = $('post_body').innerHTML; }

function change_bmark_url(url) {
    Wildfire.divWildfirePost_bmark.applyConfig({
    bookmarkURL: url,
    includeShareButton: 'true',
    defaultContent: '',
    UIConfig: '<config><display codeBoxHeight="30" showEmail="false" showBookmark="true" showPost="false" /></config>'
   });
  return true;
}

function toggle_art(elink, imgurl) {
  var yn = $('art').checked;
  var art = '<br /><div style="float:left"><a href="'+elink+'"><img border=0 src="'+imgurl+'" /></a></div>';
  if (yn) {
    $('gigya_code_post').innerHTML += art;
  } else {
    var a1 = art.replace(/</g, '&lt;');
    var a2 = a1.replace(/>/g, '&gt;');
    a1 = $('gigya_code_post').innerHTML.replace(a2, '');
    $('gigya_code_post').innerHTML = a1;
  }
  return true;
}


function show_upload_window(url,eid) {
    window.open(url,'uploadEpisode','toolbar=0,scrollbars=0,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=350');
    parent.window.location.href = '/episode/info/'+eid;
}

function show_publish_upload_window(url, parenturl) {
    window.open(url,'uploadEpisode','toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=700,height=350');
    // window.open(url,'uploadEpisode','toolbar=0,scrollbars=0,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=350');
    parent.window.location.href = parenturl;
}

function disableCommentForm(cid) {
  form_obj=$('comment_form_'+cid);
  Element.extend(form_obj);
  form_obj.disable();
  $('csubmit_'+cid).value='Comment posted!';
  return true;
}

function confirm_date_select(datetime_id) {
    alert('confirm');
    return true;
}

function close_lightbox(reload_page) {
    Lightbox.hideBox();
    if (reload_page) window.location.reload();
}

function lb_show_profile_comments() {
    document.getElementById('div_add_comment').style.display='block';
    document.getElementById('cmt_content').focus();
    Lightbox.hideBox();
    return false;
}

function loaded_qr_lightbox() {
    // Nifty('div#lb_box_contents');
    var elem = document.getElementById('email');
    if (elem) elem.focus();
}

function player_window_episode(url) {
    var epis = $('episodes');
    if (epis.selectedIndex > 0) {
        document.location.href = url + epis.options[epis.selectedIndex].value;
    }
    return true;
}

/* check the EDU survey form to be sure all required fields are filled in */
function checkEduForm() {

  required_fields = $H({ FirstName: "Please enter your first name",
    LastName: "Please enter your last name",
    Email: "Please enter your e-mail address",
    SchoolName: "Please enter the name of your school",
    City: "Please enter the name of the city your school is in" });

  keys = required_fields.keys();
  for (i=0; i<keys.length ; i++){
    if ('' == $F(keys[i])){
      alert(required_fields[keys[i]]);
      return false;
    }
  }
  return true;
}

function friend_did_request(url, req_id, action) {
    var xhReq = getXMLRequest();
    xhReq.open("GET", url, false);
    xhReq.send(null);
    $('action_'+req_id).innerHTML = 'Request '+action;
    $('ignore_'+req_id).disabled = true;
    $('accept_'+req_id).disabled = true;
}

function toggle_consolidated_activity(div_class, display) {
    if (display == 'block') {
        $$('.'+div_class).each(function(item){
            item.style.display = 'block';
        });
        $('less_'+div_class).style.display = 'block';
        $('more_'+div_class).style.display = 'none';

    } else if (display == 'none') {
        $$('.'+div_class).each(function(item){
            item.style.display = 'none';
        });
        $('more_'+div_class).style.display = 'block';
        $('less_'+div_class).style.display = 'none';
    }
}


//////////////////////
//Gigya Socialize Stuff
//////////////////////
var conf={"APIKey":"2_2T31ik2KX21QVXAjKSA4tw=="};
// var conf={"APIKey":"2_2T31ik2KX21QVXAjKSA4tw==", "enabledProviders":"twitter"};
var containerID = "gigyaContainer";
var componentID = "gigyaComponentDiv";
// var conf={"APIKey":"2_2T31ik2KX21QVXAjKSA4tw==", "enabledProviders":"twitter"};
// var conf = { APIKey:'2_2T31ik2KX21QVXAjKSA4tw==' }


var status_url = null;

function setStatus_callback(response) {
    var response_elem = $('twitter_response');
    response_elem.style.display = 'inline';

    switch (response.status) {
    case 'OK':
        response_elem.style.color = "green";
        response_elem.innerHTML = "Status&nbsp;Updated";
        break;
    default:
        response_elem.style.color = "red";
        response_elem.innerHTML = "Unable to update your status&nbsp;status;&nbsp;response status=" + response.status + "; response message = "+response.statusMessage;
    }
}

function tweetStatus(status_str) {
    if (status_str && status_str.length > 0) {
        var params = {
            status: status_str,
            callback:setStatus_callback
        };
        gigya.services.socialize.setStatus(conf, params);
    }
    return true;
}

function clicky(url) {
    $('twitter_response').style.display = 'none';
    status_url = url;
    checkConnected(url);
}

function checkConnected(url) {
    var ctxt = {url : url};
    gigya.services.socialize.getUserInfo(conf, {callback:checkConnected_callback, context:ctxt});
    gigya.services.socialize.addEventHandlers(conf, { onConnect:checkConnected_callback, onDisconnect:disconnected_callback});
}

function disconnected_callback(response) {
    $(containerID).style.display = 'block';
    var logout = $('gigya_logout')
    if (logout) logout.style.display = 'none';
    gigyaShowConnectUI();
}

function checkConnected_callback(response) {
    var isConnected = !(response.user==null || !response.user.isConnected);
    var logout = $('gigya_logout')
    var authfail = $('auth_fail')

    if (isConnected) {
        if (authfail) authfail.style.display = 'none';
        $(containerID).style.display = 'none';
        if (status_url) {  // response.context
            doTweet(status_url);
        }

        if (logout) logout.style.display = 'inline';

    } else {
        $(containerID).style.display = 'block';
        if (logout) logout.style.display = 'none';

        // FIXME:  not the best way to determine if authentication failed
        if (response.operation)
            alert("First sign in to Twitter/Facebook/MySpace.");
        else {
            if (authfail) authfail.style.display = 'block';
            alert("Authentication failed.  Please try again, or use a different browser.");
        }
        return;
    }
}

function doTweet(url) {
    var xhReq = getXMLRequest();
    xhReq.open("GET", url, false);
    xhReq.send(null);
    var status = xhReq.responseText;
    if (status && status.length > 0) {
        tweetStatus(status);
    }
}


var connect_params = {"height":60,
                      "width":90,
                      "containerID":componentID};

function gigyaShowConnectUI() {
    gigya.services.socialize.showConnectUI(conf,connect_params);
}

function socializeDisconnect() {
    gigya.services.socialize.disconnect(conf,connect_params);
}

//////////////////////
//Gigya Socialize Stuff
//////////////////////

function showEpisodeTip(tid, url, title) {
    new Tip(tid, {
        title : title,
            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' },
                        width: 'auto', // We don't want the default 250px.
                                   // Images inside the tooltip will need to have dimensions set since Prototip needs to fixate width for proper rendering.
                                   hook: { target: 'bottomMiddle', tip: 'topRight' },
                                   stem: 'topRight',
                                             offset: { x: 6, y: 3 }
    });
}

function showPremiumEpisode(tid, url, title) {
    new Tip(tid, {
        title : title,
            stem : 'topMiddle',
            style : 'premium',
            hook: { target: 'bottomMiddle', tip: 'topMiddle' },
            ajax: {
            url: url,
                     options: {
                     onComplete: function(transport) {
                         // you could do something here after the ajax call is finished
                     }
                                     }
        },
            hideOn: { element: 'closeButton', event: 'click' }
                                   // Images inside the tooltip will need to have dimensions set since Prototip needs to fixate width for proper rendering.
                                   // hook: { target: 'bottomMiddle', tip: 'topRight' },
                        // stem: 'topRight',
                        // offset: { x: 6, y: 3 }
    });
}

function showChapterImageOptions(tid, url, title) {
    new Tip(tid, {
        title : title,
            showOn: 'click',
            ajax: { url: url, options: {} },
            hideOn: { element: 'closeButton', event: 'click' },
                        width: 'auto', // We don't want the default 250px.
                                   // Images inside the tooltip will need to have dimensions set since Prototip needs to fixate width for proper rendering.
                                   hook: { target: 'bottomMiddle', tip: 'topRight' },
                                   stem: 'topRight',
                                             offset: { x: 6, y: 3 }
    });
}

function selectedPubDate() {
    var idx = $('episode[pub_date]').selectedIndex;
    if (1 == idx) {
        $('pub_date_fields').style.display = 'block';
    } else {
        $('pub_date_fields').style.display = 'none';
    }
}

function did_login_for_comment(epi_id) {
    close_lightbox(false);
    var lnk = $('load_epi_cmnt_form_'+epi_id);
    if (lnk) lnk.onclick();
}

function flagPremiumContent(link_id) {
    var tips = $$('.prototip');
    if (tips) $A(tips)[0].style.display = 'none';
    $(link_id).onclick();
}

function selectedOrderEpisode(url) {
    var epis = $('order[episode]');
    if (epis) document.location.href = url + '?episode=' + epis.options[epis.selectedIndex].value;
}

function insertChapter(url) {
    // get the current time from chapter player
    //
}

function getRequestParameter( name ) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}

