
function ShowHideLRForm( id,AlwaysShow,ScrollInto )
{
    F = document.getElementById(id);
    Clicker = document.getElementById('LRFormShowHide');

    if( F.style.display !== 'block' || AlwaysShow === true )
    {
    	Clicker.src='/images/lr/form_arrow_up.png';
        F.style.display = 'block';
        if( ScrollInto === true )
        	document.getElementById('LeftColumn').scrollIntoView();
    }
    else
    {
        Clicker.src='/images/lr/form_arrow_down.png';
        F.style.display = 'none';
    }
}

function toggleNewAlias()
{
    var fld = document.getElementById('PreviousAlias');

    if (fld.style.visibility == 'visible')
    {
        fld.style.visibility = 'hidden';
    }
    else
    {
        fld.style.visibility='visible';
    }
}


function mouse_over_email(div_obj)
{
    helpHTML = 'This information is kept private and will not be exposed on BroBible.' ;

    // show help overdiv
    helpOverRight(div_obj, helpHTML) ;

    return false;
}



/* this function will show the help over div when we are over the link
'Forget something' at /Login2 */
function login_box_on_mouse_over(obj)
{
    helpHTML = '<strong>It happens.</strong> Hell, sometimes I can\'t\
    even remember my name. Click here to reset your BroBible\
    password.' ;

    // show help overdiv (this function is in support/bb.js)   
    helpOverRight(obj, helpHTML) ;

    return false;
}


/* onMouseOut event for the 'Forget link' at /Login2 */
function login_box_on_mouse_out()
{
    helpOut() ;
}


function get_rating_description(star_number)
{
    switch(star_number)
    {
        case '0':
            rating_description = 'Unrated' ;
            break ;
                
        case '1':
            rating_description = 'Bust' ;
            break ;
        
        case '2':
            rating_description = 'Fold' ;
            break ;
        
        case '3':
            rating_description = 'Check' ;
            break ;
            
        case '4':
            rating_description = 'Raise' ;
            break ;
            
        case '5':
            rating_description = 'All-In' ; 
            break ;            
    
        default:
            break ;
    }

    return rating_description ;
}


    
/* cursor on rating image */
function star_on(star_number)
{
    /* debug
    // div where we will show the coordinates
    div = document.getElementById('coords_xy') ;
     
    div.innerHTML = 'Star: ' + star_number ;
    */

    // set the corresponding image according to the
    // star where the user is pointing with the cursor
    
    /* careful: if you try to assign the src to a variable it will not
    work on IE, dont ask me why, we know story between IE and JS...*/

    document.getElementById('rating_image').src = '/images/ratings/rated' + star_number + '.gif' ;

    // this function will return the description according to the
    // number of stars selected
    rating_description = get_rating_description(star_number) ;

    // set it in the rating description div, we cant use the 'alt' 
    // it seems that the image object doesnt allow as to access this
    // property from js
    document.getElementById('rating_description_text').innerHTML = '(' + rating_description + ')' ;

    //'/images/rated' + star_number + '.gif' ;

    // delete the text in rating_sent since we are not using it anymore
    //  - rating_sent is filled when the user sends the rating with 
    //    'Thanks for rating!' or '*you have already rated the story*'
    document.getElementById('rating_sent').innerHTML = '' ;
}


   
/* cursor out from rating image */
function star_out()
{
    // current rating image has the actual rating for this
    // story (which is restored if the user do not select a new
    // one from a hidden field called current_rating_image
        
    document.getElementById('rating_image').src = document.getElementById('current_rating_image').value ;


    // and we have to update the current description
    document.getElementById('rating_description_text').innerHTML = document.getElementById('current_rating_description').value  ;
 
}    
 
 
/* 
    change story's rating
    stars: number of stars that we will set the rating to 
*/
function change_rating(StoryGID, stars, request_url)
{
    // only logged in users can rate
/*
    if (document.getElementById('logged_in').value != true)    
    {
        document.getElementById('rating_sent').innerHTML = '<a href="/Login" class="story_links">Only logged in users can rate. Click here to log in</a>' ;
        return ;
    }
*/

    // we should check if the user is allowed to rate the story first
    if (document.getElementById('allowed_to_rate').value == 0)
    {
        document.getElementById('rating_sent').innerHTML = '<font color="red">Sorry Bro but you have already rated this post</font>' ;
        return ;
    }

    // set the new rating to the one the user selected so we reflect
    // the changes (we will not show the average but his own selection

    // we will update the image and the current_image so if star_out is called
    // we dont miss the selection

    document.getElementById('rating_image').src = '/images/ratings/rated' + stars + '.gif' ;
    document.getElementById('current_rating_image').value = '/images/ratings/rated' + stars + '.gif' ;

    // and the description
    new_description = get_rating_description(stars) ;

    document.getElementById('rating_description_text').innerHTML = '(' + new_description + ')' ;

    document.getElementById('current_rating_description').value = '(' + new_description + ')' ;

    // and send the AJAX Request through this function

    AJAX_change_rating(StoryGID, stars, request_url); 

    // set allowed_to_vote to 0 so the user will not be able to vote again
    // (if he reloads the page it will be handled by PHP directly and
    // 'allowed_to_rate' set to zero
    document.getElementById('allowed_to_rate').value = 0 ;
}

/*

AJAX_StateChanged handler

possible states for the request:

State	Description
0	The request is not initialized
1	The request has been set up
2	The request has been sent
3	The request is in process
4	The request is complete

*/

function AJAX_StateChanged() 
{	
	/*
	// enable if we need to do something with the response 


	// 200=OK and 4 means it is complete

	if(req.readyState == 4 && req.status == 200) 
	{
        if(req.responseText != null)
		{
		      //alert('200 ok, sent') ;
		      
			//alert(req.responseText) ;
		}
 	}
 	*/
	
}

/* start the AJAX GET Request and change the rating in the db */

function AJAX_change_rating(StoryGID, stars, request_url)
{
    //alert('Sending request! StoryGID=' + StoryGID + ' stars=' + stars) ;

    // initialize XMLHttpRequest object
    // firefox 
    if (window.XMLHttpRequest) 
    {
    	req = new XMLHttpRequest();
    }
    else // IE
    {
    req = new ActiveXObject("Microsoft.XMLHTTP");
    }


    // set our handler to hook the changes in the REQUEST 
    req.onreadystatechange = AJAX_StateChanged ;

    

    // enable this (if not set IE will show an error)
    // true = async operation
    
    req.open("GET", request_url, true) ;



    // null = body
    // definition of the method: XMLHttpRequest.send( [varBody])
    
    // enable this (if not set IE will show an error)
    req.send(null);
    
    
    // add the message 'Thanks for rating!' near the description and remove the image map
    
    document.getElementById('rating_sent').innerHTML = '<font color="green">Thanks Bro</font>' ;
    document.getElementById('rating_image').useMap = '';
    document.getElementById('rating_image').isMap = false;
}

function preload_stars_images()
{
    star1 = new Image(96, 25);
    star1.src = "/images/ratings/rated1.gif" ;

    star2 = new Image(96, 25) ;
    star2.src = "/images/ratings/rated2.gif" ;
    
    star3 = new Image(96, 25) ;
    star3.src = "/images/ratings/rated3.gif" ;
    
    star4 = new Image(96, 25) ;
    star4.src = "/images/ratings/rated4.gif" ;
    
    star5 = new Image(96, 25) ;
    star5.src = "/images/ratings/rated5.gif" ;
    
    // preload the image with all the stars empty too 
    star6 = new Image(96, 25) ;
    star6.src = "/images/ratings/rated0.gif" ;
}



/* start the AJAX POST Request and save the draft */
function AJAX_auto_save_draft()
{
    // initialize XMLHttpRequest object
    // firefox 
    if (window.XMLHttpRequest) 
    {
        req = new XMLHttpRequest();
    }
    else // IE
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }


    // set our handler to hook the changes in the REQUEST 
    req.onreadystatechange = AJAX_auto_save_state_changed ;


    // post params must be url-encoded, escape() in JS is the urlencode()
    // from PHP
    // we have them because we will fill it before calling 
    // the JS functions 
    
    // params will be:
    //  - title = subject
    //  - category = genre
    //  - words
    //  - post as = is the user posting as anonymous or not? 
    //  - keywords
    //  - contains
    
    var title = 'Title=' + escape(document.getElementById('subject').value) ;

    //alert(subject) ;

    var Category = 'Category=' + escape(document.getElementById('genre').value) ;
    
    //alert(genre) ;

    var Content = 'Content=' + escape(document.getElementById('words').value) ;
    
    //alert(words) ;
    if( document.getElementById('Anonymous').checked == true )
        var Anonymous = 'Anonymous=1';
    else
        var Anonymous = 'Anonymous=0';

    // alert(Anonymous) ;

    var Tag = 'Tag=' + escape(document.getElementById('keywords').value) ;

    //alert(keywords) ;


/*
    // no need to escape integers
    var contains_profanity = 'profanity=' + document.getElementById('prof0').checked ;

    //alert(contains_profanity) ;
    

    
    var contains_drugs = 'drugs=' + document.getElementById('drug0').checked ;

    //alert(contains_drugs) ;
    

    var contains_sex = 'sex=' + document.getElementById('sexl0').checked ;
    
    //alert(contains_sex) ;
*/    


    // and add the saved_draft_id which let us update any existing
    // copy of it 
    var saved_draft_id = 'saved_draft_id=' + document.getElementById('saved_draft_id').value ;

    var SaveDraft = 'SaveDraft=1';

    // now create the params for the post
    params = SaveDraft + '&' + title + '&' + Category + '&' + Content + '&' + Anonymous + '&' + Tag + '&' + saved_draft_id ;

//    alert(params) ;

    //alert(params.length) ;



    // XXX: use the form action URL as the request url where we will post ?
    // var request_url = document.Stories.action ;



    // open the url 
    // true = async operation


    req.open('POST', '/aj/save-draft',true) ;

    
    // Set the header information
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.setRequestHeader("Content-length", params.length);
    req.setRequestHeader("Connection", "close");

    // send the request 
    req.send(params);

}


/*

AJAX_StateChanged handler

possible states for the request:

State   Description
0   The request is not initialized
1   The request has been set up
2   The request has been sent
3   The request is in process
4   The request is complete

*/

function AJAX_auto_save_state_changed() 
{   
    // enable if we need to do something with the response 

    // 200=OK and 4 means it is complete

    if(req.readyState == 4 && req.status == 200) 
    {
        if(req.responseText != null)
        {
            // debug
            //alert('200') ;
            // fake_responseText = '{ "saved_draft_id": "325" }' ;
    
        
            // parse the response and save the draft id


            //alert(req.responseText) ;
            
            var response_obj = eval('(' + req.responseText + ')');


            //var response_obj = eval('(' + fake_responseText + ')') ;

    
           


            // get the saved draft it
            saved_draft_id = response_obj.saved_draft_id ;
                   
            // alert(saved_draft_id) ;
            
            
            
            // save it so we can re-send in the next update
//            document.getElementById('saved_draft_id').value = saved_draft_id ;
           
            
            
            //alert(document.getElementById('saved_draft_id').value) ;
            
            
            
           
            // update the auto-saved draft "timestamp"
            var current_timestamp = get_current_timestamp() ;
            
            
            // original string: 'Draft Saved Automatically: 2:24pm 08/14/08'
            document.getElementById('Autosave').innerHTML = 'Draft Saved Automatically: ' + current_timestamp ;
        }
    }
}



/*
    we will to fill in the current timestamp when saving the draft, so
    this function will return it in the following format:
    
    h:i(am|pm) mm/dd/YYYY
*/
function get_current_timestamp()
{
    oDate = new Date() ;


    // 1) get the time h:i am/pm 

    var hours = oDate.getHours() ;

    var minutes = oDate.getMinutes() ;
    
    if (minutes < 10)  // add a zero
        minutes = '0' + minutes ; 


    // calculate if AM or PM
    
    if (hours > 12) // PM
    {
        hours = hours - 12 ;
        if (hours < 10)
            hours = '0' +  hours ; // add a zero
        
        var time = hours + ':' + minutes + 'pm' ; 
    }
    else // AM
    {
        if (hours < 10)
            hours = '0' +  hours ; // add a zero
    
        var time = hours + ':' + minutes + 'am' ; 
    }

 


    // 2) get the date 

    var day = oDate.getDate();
    if (day < 10)
        day = '0' + day ;


    var month = oDate.getMonth();

    if (month < 10)
        month = '0' + month ;


    var year = oDate.getFullYear();



    // join everything and format the "timestamp"

//    var timestamp = time + ' ' + month + '/' + day + '/' + year ;

    var timestamp = time;

    //alert(timestamp) ;

    return timestamp ;
}


/*
    Handles the auto-save feature in /Sharestory to save drafts
    every 60 seconds
*/


/* will set a timer that triggers every 60 seconds and posts to /Savedraft
   so we are able to save everything in /ShareStory */
function set_autosave_interval() 
{        
    // 0 means that we are calling the function from the timer 
    // the user may execute it directly using the link 'Save Draft'
    window.setInterval("save_draft(0)", 5 * 1000); // 5 seconds
   
    return false;
}


/* will save the current draft posting everything to /Unleash (only in
   case there is something written in Words field */
function save_draft(from_link)
{
    // is there something to save ?
    if (document.getElementById('words').value != '')
    {   
        // send an AJAX post to save the draft
        AJAX_auto_save_draft() ;
    }
    else
    {
        if (from_link == 1)
        {
            // show an error 
            document.getElementById('Autosave').innerHTML = "<font color=\"yellow\">Sorry Bro, there's nothing to save.</font>";
        }
    }
}

function var_dump(obj) {
   if(typeof obj == "object") {
      return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
   } else {
      return "Type: "+typeof(obj)+"\nValue: "+obj;
   }
}


function helpOut()
{	if(!document.getElementById('HelpBox')) return false;
	var helplyr = document.getElementById('HelpBox');
	helplyr.style.display = "none";
	return;
}

function findPosX(obj,div)
{	var curleft = 0;
	if (obj.offsetParent)
	{	while (obj.offsetParent)
		{	curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)	curleft += obj.x;
	return curleft;
}
function findPosY(obj,div)
{	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)	curtop += obj.y;
	if(div) curtop -= document.getElementById(div).scrollTop; //added for scrolling divs (MC 04/18/07)
	return curtop;
}
/* helpOverRight will show an overdiv positioned on the right */
function helpOverRight (obj, htxt)
{
    var newX = findPosX(obj);
    var newY = findPosY(obj);

    if(!document.getElementById('HelpBox') || !document.getElementById('HelpBoxHeader')) 
       return false;
    
    var helplyr = document.getElementById('HelpBox');
    var helplyrT = document.getElementById('HelpBoxHeader');

    helplyrT.innerHTML = htxt ;

    // we will always set the pixels to the top or the 
    // middle of the link
    helplyr.style.top = ((newY+0)-12) + 'px';

    /*
    // this is tricky: we dont know the current width of the link
    // and it can vary according to the length of the description
    
    link_length = obj.text.length;
    
    
    
    // we will calculate the approximated width of the link
    
    alert(obj.style.fontSize) ;
    */

    helplyr.style.left = ((newX+0)-0) + 'px' ; 

    helplyr.style.display = "block";
    
    return;
}

var CurrentTextFocus = null;

//myField accepts an object reference, myValue accepts the text strint to add
function insertAtCursor( clickO,o )
{
	if( CurrentTextFocus === null )
		TheText = document.getElementById('words');
	else
		TheText = document.getElementById(CurrentTextFocus);

	TheText.focus();

	//IE support
    if (document.selection)
    {
//        o.TheDiv.focus();

        //in effect we are creating a text range with zero
        //length at the cursor location and replacing it
        //with myValue
        sel = document.selection.createRange();
        sel.text = o.TheContent;
    }
    //Mozilla/Firefox/Netscape 7+ support
    else if (TheText.selectionStart || TheText.selectionStart == '0' )
    {
        //Here we get the start and end points of the
        //selection. Then we create substrings up to the
        //start of the selection and from the end point
        //of the selection to the end of the field value.
        //Then we concatenate the first substring, myValue,
        //and the second substring to get the new value.
        var startPos = TheText.selectionStart;
        var endPos = TheText.selectionEnd;
        TheText.value = TheText.value.substring(0, startPos)+ o.TheContent + TheText.value.substring(endPos, TheText.value.length);
    }
    else
    {
    	TheText.value += o.TheContent;
    }

    TheText.focus();
//    document.getElementById("words").focus();
}


