//=====================================================================
// Thread Helper Functions
//=====================================================================

function countLines(obj) {
	cols = obj.cols;
	strtocount = obj.value;
    var hard_lines = 1;
    var last = 0;
    while ( true ) {
        last = strtocount.indexOf("\n", last+1);
        hard_lines ++;
        if ( last == -1 ) break;
    }
    var soft_lines = Math.round(strtocount.length / (cols-1));
    var hard = eval("hard_lines  " + unescape("%3e") + "soft_lines;");
    if ( hard ) soft_lines = hard_lines;
    obj.rows = soft_lines;
}	

// Creates URL links for URLs that start with http://, https://, or "www"
function addURLLinks(text) {

//URLs starting with http://, https://, or ftp://
 var replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
 var replacedText = text.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

 //URLs starting with www. (without // before it, or it'd re-link the ones done above)
 var replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
 var replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

 //Change email addresses to mailto:: links
 var replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
 var replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

 return replacedText

}


function stripHTML(text) {
	return text.replace(/<(?!\/?(?=>|\\s.*>))\/?.*?>/g,'');
}


function trim(value) {
	return value.replace(/^\s+|\s+$/g, '');
	
}


// Extending the Ajax.Autocompleter to prevent an auto focus on the first element
// Additionally, this fixes the page jump when using arrow keys up and down
// as well as provides a local cache
Ajax.IpiqiAutocompleter = Class.create();
Object.extend(Object.extend(Ajax.IpiqiAutocompleter.prototype, Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {	

  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
	this.cache 				   = {};    
	this.index                 = -1;
  },

	getUpdatedChoices: function() {
		var t = this.getToken();
		if (this.cache[t]) {
			this.updateChoices(this.cache[t]);
		} else {
			entry = encodeURIComponent(this.options.paramName) + '=' + encodeURIComponent(t);
	
			this.options.parameters = this.options.callback ?
			this.options.callback(this.element, entry) : entry;
	
			if(this.options.defaultParams)
				this.options.parameters += '&' + this.options.defaultParams;
	
			new Ajax.Request(this.url, this.options);
		}
	},

	onComplete: function(request) {
		this.updateChoices(this.cache[this.getToken()] = request.responseText);
	},

	// Page jump fix
markPrevious: function() {
 if(this.index > 0) {this.index--;}
 else {
  this.index = this.entryCount-1;
  this.update.scrollTop = this.update.scrollHeight;
 }
 selection = this.getEntry(this.index);
 selection_top = selection.offsetTop;
 if(selection_top < this.update.scrollTop){
  this.update.scrollTop = this.update.scrollTop-selection.offsetHeight;
 }
},

markNext: function() {
 if(this.index < this.entryCount-1) {this.index++;}
 else {
  this.index = 0;
  this.update.scrollTop = 0;
 }
 selection = this.getEntry(this.index);
 selection_bottom = selection.offsetTop+selection.offsetHeight;
 if(selection_bottom > this.update.scrollTop+this.update.offsetHeight){
  this.update.scrollTop = this.update.scrollTop+selection.offsetHeight;
 }
},


  onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         if(Prototype.Browser.WebKit) Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         if(Prototype.Browser.WebKit) Event.stop(event);
         return;
      }
     else 
       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 
         (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer = 
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },


	 updateChoices: function(choices) {
		if(!this.changed && this.hasFocus) {
		  this.update.innerHTML = choices;
		  Element.cleanWhitespace(this.update);
		  Element.cleanWhitespace(this.update.down());

		  if(this.update.firstChild && this.update.down().childNodes) {
		    this.entryCount = 
		      this.update.down().childNodes.length;
		    for (var i = 0; i < this.entryCount; i++) {
		      var entry = this.getEntry(i);
		      entry.autocompleteIndex = i;
		      this.addObservers(entry);
		    }
		  } else { 
		    this.entryCount = 0;
		  }

		  this.stopIndicator();
		  this.update.scrollTop = 0;
		  this.index = -1;

		  if(this.entryCount==1 && this.options.autoSelect) {
		    this.selectEntry();
		    this.hide();
		  } else {
		    this.render();
		  }
		}
	 },
	  selectEntry: function() {
	    this.active = false;
		if(this.index == -1) {
			Effect.Fade(this.update);
		}
		this.updateElement(this.getCurrentEntry());
	  }

});

/**
 * converts an rgb value to hsl
 * @param $r, an int, the amount of red, between 0 and 255
 * @param $g, an int, the amount of blue, between 0 and 255
 * @param $b, an int, the amount of green, between 0 and 255
 * @return an array of 3 values, Hue between 0 and 359, Saturation between 0 and 1, Lightness between 0 and 1
 */
function convertRGBtoHSL( red, green, blue )
{ 

 r = red / 255;
 g = green / 255;
 b = blue / 255;

 min = Math.min( r, g, b );
 max = Math.max( r, g, b );
 delta = max - min;
 avg = ( max + min ) / 2;

 l = avg;

 if( delta == 0 )
 {
  h = 0;
  s = 0;
 }
 else
 {
  if( avg <= 0.5 ) {
    s = delta / ( max + min );
  } else {
    s = delta / ( 2 - max - min );
  }

  if( r == max ) {
    h = ( 60 * ( ( g - b ) / ( max - min ) ) ) % 360;
  } else if ( g == max ){
    h = 60 * ( ( b - r )/( max - min ) ) + 120;
  } else if( b == max ) {
    h = 60 * ( ( r - g )/( max - min ) ) + 240;
  }
 }
 tmpArray = new Array(h,s,l);
 return tmpArray;
}


function formatDate(d) {


var formattedDate = "";
var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");

var m_names = new Array("January", "February", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December");

var curr_day = d.getDay();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
   {
   sup = "st";
   }
else if (curr_date == 2 || curr_date == 22)
   {
   sup = "nd";
   }
else if (curr_date == 3 || curr_date == 23)
   {
   sup = "rd";
   }
else
   {
   sup = "th";
   }
var curr_month = d.getMonth();

formattedDate += m_names[curr_month] + " " + curr_date + "<SUP>"
+ sup + "</SUP> at ";


var a_p = "";
var curr_hour = d.getHours();
if (curr_hour < 12)
   {
   a_p = "AM";
   }
else
   {
   a_p = "PM";
   }
if (curr_hour == 0)
   {
   curr_hour = 12;
   }
if (curr_hour > 12)
   {
   curr_hour = curr_hour - 12;
   }

var curr_min = d.getMinutes();

curr_min = curr_min + "";

if (curr_min.length == 1)
   {
   curr_min = "0" + curr_min;
   }

formattedDate += curr_hour + ":" + curr_min + " " + a_p;

return formattedDate;


}


function convertTimestampToDate(timestamp) {

	var postDate = timestamp;
	var space = postDate.indexOf(' ');
	var ymd = postDate.substring(0,space);
	var ymdArray = ymd.split('-');
	var year =  ymdArray[0];
	var month = ymdArray[1]-1; //0 is january so need to subtract 1
	var day = ymdArray[2];

	var hms = postDate.substring(space+1);
	var hmsArray = hms.split(':');
	var hours = hmsArray[0];
	var minutes = hmsArray[1];
	var seconds = hmsArray[2];

	var d = new Date(year, month, day, hours, minutes, seconds )
	return d
}


// Return the time if it is today or the Month and Day if it is older than today
function createSmartDate(d) {
	
	var today = new Date();
	var timeZoneOffsetHours = today.getTimezoneOffset()/60;	
	var offsetDate = new Date();

	offsetDate.setTime(d.getTime() - (timeZoneOffsetHours * 3600000));	
	
	var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");	
	
	if((today.getDate() == offsetDate.getDate()) && (today.getMonth() == offsetDate.getMonth()) && (today.getFullYear() == offsetDate.getFullYear())) {
		
		hours = offsetDate.getHours();
		var suffix = "AM";
		if(hours >= 12) {
			hours -= 12;
			suffix = "PM";
		} 
		
		if(hours == 0) {
			hours = 12;
		} 
		
		var minutes = offsetDate.getMinutes();
		if(minutes < 10) {
			minutes = "0"+minutes;
		}
		return hours + ":" + minutes  + " " + suffix;
	} else {
		return m_names[offsetDate.getMonth()] + " " + offsetDate.getDate();
	}
	
}

function userSays(postDate) { 
	var today = new Date();
	var timeZoneOffsetHours = today.getTimezoneOffset()/60;	
	var offsetDate = new Date();
	offsetDate.setTime(postDate.getTime() - (timeZoneOffsetHours * 3600000));					

	if((today.getDate() == offsetDate.getDate()) && (today.getFullYear() == offsetDate.getFullYear()) && (today.getMonth() == offsetDate.getMonth())) {
		return " at";
	} else {
		return " on";
	}
}

var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
function modalBox(content, width, callback) {
	if(!content){
		jQuery('#ipiqi_modal').remove();
		jQuery('#ipiqi_overlay').fadeOut(function(){jQuery(this).remove();});
		try{if(IE6){jQuery('body').find('select.unhideThis').removeClass('unhideThis').visibility('visible');}}catch(err){};
		jQuery('embed.unhideThis, object.unhideThis').removeClass('unhideThis').css('visibility', 'visible');
		return false;
	}
	try{if(IE6){$('body').find('select:visible').addClass('unhideThis').visibility('hidden');}}catch(err){};
	jQuery('embed:visible, object:visible').addClass('unhideThis').css('visibility', 'hidden');
	jQuery('body').append('<div id="ipiqi_overlay"></div>');
	jQuery('#ipiqi_overlay').css({
		width		:	'100%',
		height		:	jQuery(document).height(),
		position	:	'absolute',
		left		:	0,
		top		:	0,
		backgroundColor	:	'#999999',
		zIndex		:	9990,
		opacity		:	0
	}).fadeTo(200, 0.5).click(function() {modalBox()});
	jQuery('body').append('<div id="ipiqi_modal"></div>');
	jQuery('#ipiqi_modal').css({
		border		:	'1px solid #2d7abb',
		width		:	width ? width : 350,
		backgroundColor	:	'#000000',
		position	:	'absolute',
		left		:	'50%',
		top		:	jQuery(document).scrollTop()+50,
		zIndex		:	9995,
		marginLeft	:	-(Math.ceil((width ? width : 800)/2))
	}).append(content);
	jQuery('#ipiqi_modal a:eq(0), #ipiqi_modal input, #ipiqi_modal textarea').focus();
	try{
		callback.call();
	}catch(err){};	
	jQuery(document).bind('scroll', function(){
		jQuery('#ipiqi_modal').css({
			top:jQuery(document).scrollTop()+50
		});
	});
};

function showModalVideo() {
		modalBox('<div id="helpVideo" style="text-align:center;width: 100%;margin:10px;"><object width="640" height="505"><param name="movie" value="http://www.youtube.com/v/CKeOXoeOkYU&hl=en_US&fs=1&rel=0&hd=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/CKeOXoeOkYU&hl=en_US&fs=1&rel=0&hd=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="505"></embed></object></div>',800);
}

function chooseTagForSearch(item) {
	itemClass = item.className;
	if(itemClass.indexOf('geotag') != -1) {
		// Since we are showing all geotag data with commas, we need to ensure we only pass the keyword for visually creating the tag block

		geotagSpans = $$("li.autocompleteResult span");
		longitude = geotagSpans[0].innerHTML;
		latitude = geotagSpans[1].innerHTML;
		geotagElements = geotagSpans[2].innerHTML.split(',');					
		geotagKeyword = trim(jQuery("#geotagData",item).html().split(',')[0]);
		window.location = "/geotag/"+geotagKeyword;		
	} else if(itemClass.indexOf('user') != -1) {
		window.location = "/user/"+item.innerHTML;
	} else {
		window.location = "/tag/"+item.innerHTML;
	}

}

function linkToPost(id, text) {
	return "<a href='/discussion/view/id/"+id+"#SPP_"+id+"'>"+text+"</a>";
}

function linkToUser(username) {
	return "<a href='/user/"+username+"'>"+username+"</a>";
}

function ipiqiurlencode(input) {
	out = input.replace(/[^\w\d]/gi,'_');
	return out;
}

function showTip(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;

	$(targ.id + '_tip').style.display = "block";
}

// This is used to display an "instructional" text within an input field, and not show it when there is manual data there
// e is from an event
// input is a String of text that will show up in the input field
function toggleInput(e, input, option) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;

	if(targ.value == input) {
		targ.value = "";
		//targ.style.color = "#000000";
	} else if((targ.value == "") && (option != 1)){
		targ.value = input;
		//targ.style.color = "#707070";
	}
}

function hideTip(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;

	$(targ.id + '_tip').style.display = "none";
}