/*
* jQuery Expander plugin
* Version 0.4  (12/09/2008)
* @requires jQuery v1.1.1+
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/


(function($) {

$.fn.expander = function(options) {

  var opts = $.extend({}, $.fn.expander.defaults, options);
  var delayedCollapse;
  return this.each(function() {
    var $this = $(this);
    var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
   	var cleanedTag, startTags, endTags, tmpTags;	
   	var allText = $this.html();
   	var startText = allText.slice(0, o.slicePoint).replace(/\w+$/,'');
   	var nonTaggedText = allText.slice(0, o.slicePoint).replace(/\w+$/,'');
	startTags = startText.match(/<\w[^>]*>/g);
 	  if (startTags) {startText = allText.slice(0,o.slicePoint + startTags.join('').length).replace(/\w+$/,'');}
	tmpTags = startText.match(/<\w[^>]*>/g);
 	  if (tmpTags) {nonTaggedText = allText.slice(0,o.slicePoint + tmpTags.join('').length).replace(/\w+$/,'');}
 	  
   	if (startText.lastIndexOf('<') > startText.lastIndexOf('>') ) {
   	  startText = startText.slice(0,startText.lastIndexOf('<'));
   	}
   	var endText = allText.slice(startText.length);    	  
   	// create necessary expand/collapse elements if they don't already exist
 	  if (!$('span.expandetails', this).length) {
      // end script if text length isn't long enough.
     	if ( endText.replace(/\s+$/,'').split(' ').length < o.widow ) { return; }
     	// otherwise, continue...    
     	if (endText.indexOf('</') > -1) {
       	endTags = endText.match(/<(\/)?[^>]*>/g);
        for (var i=0; i < endTags.length; i++) {

          if (endTags[i].indexOf('</') > -1) {
            var startTag, startTagExists = false;
            for (var j=0; j < i; j++) {
              startTag = endTags[j].slice(0, endTags[j].indexOf(' ')).replace(/(\w)$/,'$1>');
              if (startTag == rSlash(endTags[i])) {
                startTagExists = true;
              }
            }              
            if (!startTagExists) {
              startText = startText + endTags[i];
              var matched = false;
              for (var s=startTags.length - 1; s >= 0; s--) {
                if (startTags[s].slice(0, startTags[s].indexOf(' ')).replace(/(\w)$/,'$1>') == rSlash(endTags[i]) 
                && matched == false) {
                  cleanedTag = cleanedTag ? startTags[s] + cleanedTag : startTags[s];
                  matched = true;
                }
              };
            }
          }
        }

        nonTaggedEndText =  endText;
		endText = cleanedTag && cleanedTag + endText || endText;
      }

	var item;
	var theText = nonTaggedEndText.substr(0,nonTaggedEndText.length-5);
	var convertedText='';
	
	theText = theText.replace(/[\s\n\r]{2,}/g, ' ');            // Consolidate multiple white-space characters down to one. (Otherwise the counter will count each of them.)
    theText = theText.replace(/(<[^<>]+>)/g,'|*|SPLITTER|*|$1|*|SPLITTER|*|');                      // Find all tags, and add a splitter to either side of them.
    theText = theText.replace(/(\|\*\|SPLITTER\|\*\|)(\s*)\|\*\|SPLITTER\|\*\|/g,'$1$2');           // Find consecutive splitters, and replace with one only.
    theText = theText.replace(/^[\s\t\r]*\|\*\|SPLITTER\|\*\||\|\*\|SPLITTER\|\*\|[\s\t\r]*$/g,''); // Get rid of unnecessary splitter (if any) at beginning and end.
    theText = theText.split(/\|\*\|SPLITTER\|\*\|/);            // Split theText where there's a splitter. Now we have an array of tags and words.
	var i = 10;
    for(i in theText) {                                     // Iterate over the array of tags and words.
        item = theText[i];                                      // Store current iteration in a variable (for convenience)		
		
		if(item.match(/<\/[pP]>/)) {            // Check if it is a closing </p> tag
            convertedText += ('<span class="paragraphBreak"><br> <br> </span>');    // If so, add two line breaks to form paragraph
        } else {
			
			if(!item.match(/<[pP]>/)) {							//Check if it's a starting <p> tag
			
				convertedText += item;							//If not, accept it and add it to the conversion.
			}
		}
	}
	
	$this.html([
		nonTaggedText,
		'<span class="read-more">',
   		o.expandPrefix,
     		'<a href="#">',
     		  o.expandText,
     		'</a>',
      '</span>',
   		'<span class="expandetails">',
   		 // nonTaggedEndText.substr(0,nonTaggedEndText.length-5),
		convertedText.substr(0,convertedText.length-1),
   		'</span>',
		'</p>',
   		].join('')	
	);
    }

	/*Initialize the span class to hidden status*/
    var $thisexpandetails = $('span.expandetails', this),
    //var $thisexpandetails = $this.find('span.expandetails').parent().siblings().filter(':last-child');
	$readMore = $('span.read-more', this);
 	$thisexpandetails.hide();
	
	/*Find the top post and make sure it's not collapsed*/
	var firstArticle = document.getElementById('news').getElementsByTagName('span');
	for(var j=0; j < firstArticle.length; j++)
	if(firstArticle[j].className == 'read-more') {
		
		var tmp = firstArticle[j];
		$(tmp).hide();
		$(tmp).next('span.expandetails').show();	
		
		break;
	}
	
	
    $readMore.find('a').click(function() {	
	var newsElement = document.getElementById('news').getElementsByTagName('span');
		for(var i=0; i < newsElement.length; i++) {
			/*Make sure more than one articles are open*/
			if(newsElement[i].className == 'expandetails' && newsElement[i].style.display == 'inline') {
				var temp = newsElement[i];
				
				/*Hide span.expandetails (main content text) of the currently open article div*/
				$(temp).hide();
				
				/*Show span.read-more (excerpt text) of the previously open article div*/
				$(temp).prev('span.read-more').show();
				//$(temp).parent().siblings().filter(':last-child');
				
			}
		}
	
	/*Hide the read more link.*/
	$readMore.hide();

    if (o.expandEffect === 'show' && !o.expandSpeed) {
        o.beforeExpand($this);
        $thisexpandetails.show();
        o.afterExpand($this);
        delayCollapse(o, $thisexpandetails);
      } else {
        o.beforeExpand($this);
        $thisexpandetails[o.expandEffect](o.expandSpeed, function() {
          $thisexpandetails.css({zoom: ''});
          o.afterExpand($this);
          delayCollapse(o, $thisexpandetails);
        });
      }
	
      return false;
    });
     
	if (o.userCollapse) {
 
	//Selects the last p element of a currently closed div   
	$this.find('span.expandetails').parent().siblings().filter(':last-child').append('<span class="re-collapse">' + o.userCollapsePrefix + '<a href="#">' + o.userCollapseText + '</a></span>');	
    
	$this.find('span.re-collapse a').click(function() {

	    clearTimeout(delayedCollapse);
	    var $expandetailsCollapsed = $(this).parents('span.expandetails');
	    reCollapse($expandetailsCollapsed);
	    o.onCollapse($this, true);
	    
		return false;
    
	});
    
	}
  
  });
  
	function reCollapse(el) {
     el.hide()
      .prev('span.read-more').show();
  }
  function delayCollapse(option, $collapseEl) {
    if (option.collapseTimer) {
      delayedCollapse = setTimeout(function() {  
        reCollapse($collapseEl);
        option.onCollapse($collapseEl.parent(), false);
        },
        option.collapseTimer
      );
    }
  }
  function rSlash(rString) {
    return rString.replace(/\//,'');
  }    
};
  // plugin defaults
$.fn.expander.defaults = {
  slicePoint:       120,  // the number of characters at which the contents will be sliced into two parts. 
                          // Note: any tag names in the HTML that appear inside the sliced element before 
                          // the slicePoint will be counted along with the text characters.
  widow:            4,  // a threshold of sorts for whether to initially hide/collapse part of the element's contents. 
                        // If after slicing the contents in two there are fewer words in the second part than 
                        // the value set by widow, we won't bother hiding/collapsing anything.
  expandText:       'read more', // text displayed in a link instead of the hidden part of the element. 
                                    // clicking this will expand/show the hidden/collapsed text
  expandPrefix:     '&hellip; ',
  collapseTimer:    0, // number of milliseconds after text has been expanded at which to collapse the text again
  expandEffect:     'fadeIn',
  expandSpeed:      '',   // speed in milliseconds of the animation effect for expanding the text
  userCollapse:     true, // allow the user to re-collapse the expanded text.
  userCollapseText: 'collapse',  // text to use for the link to re-collapse the text
  userCollapsePrefix: ' ',
  beforeExpand: function($thisEl) {},
  afterExpand: function($thisEl) {},
  onCollapse: function($thisEl, byUser) {}
};
})(jQuery);

