//useful function from http://www.dustindiaz.com/top-ten-javascript/
// determine if an element is in an array
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

  
// custom function to remove an array element
Array.prototype.rmInArray = function (value) {
	var i;
	var ret = new Array();
	for (i=0; i < this.length; i++) {
		if (this[i] === value || this[i] === '') {
			//return true;
		}else{
			ret.push(this[i].trim(), ret);
		}
	}
	return ret;
};
function indicator_on(theDiv){
	$(theDiv).innerHTML = "<br><center><img src='/images/progress/indicator_64.gif' border=0></center><br>";
}

function indicator_off(theDiv){
	$(theDiv).innerHTML = "";
}

// from: http://ajaxian.com/archives/ajax-activity-indicators-with-rails
Ajax.Responders.register({
  onCreate: function() {
    if($('busy') && Ajax.activeRequestCount>0)
      Effect.Appear('busy',{duration:0.5,queue:'end'});
  },
  onComplete: function() {
    if($('busy') && Ajax.activeRequestCount==0)
      Effect.Fade('busy',{duration:0.5,queue:'end'});
  }
});


function SlideUpAndDown(element) {
  element = $(element);
  if(Element.visible(element)) {
  	new Effect.SlideUp(element);
  }else{ 				
 	new Effect.SlideDown(element);	
  }
}

function showBox(){
   var objOverlay = document.getElementById('overlay');
   var arrayPageSize = getPageSize();
   var arrayPageScroll = getPageScroll();
   objOverlay.style.height = (arrayPageSize[1] + 'px');
   objOverlay.style.display = 'block';
	
    $('overlay').show();
    //$('box').show();
    center('box');
    return false;
}

function hideBox(){
    $('box').hide();
    $('overlay').hide();
    return false;
}

function showBox2(){	
    $('overlay').show();
    $('channels').show();
    //center('channels');
    return false;
}

function hideBox2(){
    $('channels').hide();
    $('overlay').hide();
    return false;
}

function center(element){
    try{
        element = $(element);
    }catch(e){
        return;
    }

    var my_width  = 0;
    var my_height = 0;

    if ( typeof( window.innerWidth ) == 'number' ){
        my_width  = window.innerWidth;
        my_height = window.innerHeight;
    }else if ( document.documentElement && 
             ( document.documentElement.clientWidth ||
               document.documentElement.clientHeight ) ){
        my_width  = document.documentElement.clientWidth;
        my_height = document.documentElement.clientHeight;
    }
    else if ( document.body && 
            ( document.body.clientWidth || document.body.clientHeight ) ){
        my_width  = document.body.clientWidth;
        my_height = document.body.clientHeight;
    }

    element.style.position = 'absolute';
    element.style.zIndex   = 99;

    var scrollY = 0;

    if ( document.documentElement && document.documentElement.scrollTop ){
        scrollY = document.documentElement.scrollTop;
    }else if ( document.body && document.body.scrollTop ){
        scrollY = document.body.scrollTop;
    }else if ( window.pageYOffset ){
        scrollY = window.pageYOffset;
    }else if ( window.scrollY ){
        scrollY = window.scrollY;
    }

    var elementDimensions = Element.getDimensions(element);

    var setX = ( my_width  - elementDimensions.width  ) / 2;
    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

    setX = ( setX < 0 ) ? 0 : setX;
    setY = ( setY < 0 ) ? 0 : setY;

    element.style.left = setX + "px";
    element.style.top  = setY + "px";

    element.style.display  = 'block';
}

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}

}

function addOnLoad(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function hideShow(which, what) {
	var menu = document.getElementById(which);

	if (what == "show") {
		menu.className = "on";
	} else if (what == "hide") {
		menu.className = "off";
	}
}

function initNav() {
	if (document.getElementById && document.getElementById('subnav')) {
		var tabnav = document.getElementById('tabnav').getElementsByTagName('li');
		for (var i = 0; i < tabnav.length; i++) {
			if (tabnav[i].className == "last") {
				var lasttab = tabnav[i].getElementsByTagName('a');
				lasttab[0].setAttribute("id", "tabmenu");
			}
		}

		var tabmenu = document.getElementById('tabmenu');
		tabmenu.className == "off";
		tabmenu.onclick = function () { hideShow('subnav','show'); return false; }
		tabmenu.onmouseover = function () { hideShow('subnav','show'); }

		var subnav = document.getElementById('subnav');
		subnav.onmouseover = function () { hideShow('subnav','show'); }
		subnav.onmouseout = function () { hideShow('subnav','hide'); }
		subnav.onblur = function () { hideShow('subnav','hide'); }
	}
}

// from explore.js
function initExplore() {
	var tab, subnav;

	if (document.getElementById && document.getElementById('sort-selected')) {
		tab = document.getElementById('sort-selected');
		tab.onclick = function () { hideShow('sortnav','show'); return false; }
		tab.onmouseover = function () { hideShow('sortnav','show'); }

		subnav = document.getElementById('sortnav');
		subnav.onmouseover = function () { hideShow('sortnav','show'); }
		subnav.onmouseout = function () { hideShow('sortnav','hide'); }
		subnav.onblur = function () { hideShow('sortnav','hide'); }
	}
	if (document.getElementById && document.getElementById('from-selected')) {
		tab = document.getElementById('from-selected');
		tab.onclick = function () { hideShow('fromnav','show'); return false; }
		tab.onmouseover = function () { hideShow('fromnav','show'); }

		subnav = document.getElementById('fromnav');
		subnav.onmouseover = function () { hideShow('fromnav','show'); }
		subnav.onmouseout = function () { hideShow('fromnav','hide'); }
		subnav.onblur = function () { hideShow('fromnav','hide'); }
	}
}

var newwindow = '';

//----------------------- common functions
function popup(url,width,height) {
        window.open(url,'popup','width='+width+',height='+height+',scrollbars=auto,resizable=yes,toolbar=no,directories=no,menubar=no,status=no,left=100,top=100');
        return false;
}

//validation for signup
function checkYear() {
	var year = $('birthday_year').value;
	if (year > 1920 && year < 1994)
	{
		//this is good. do nothing.
	}
	else if (year < 1920)
	{
		alert('Damn! You\'re seriously old. Are you sure you want to use Socialight???')		
	}	
	else if (year > 1994)
	{
		alert('Sorry! You must be at least 13 years old to sign up.')		
	}
	else
	{
		alert('Sorry! I couldn\'t understand that year. Please try a different one')		
	}
}
	
// some helper functions
// joel de gan - 2007
function home_tog_channels_on(){
	$('contacts_tab').className	= "";
	$('channels_tab').className	= "on";
	
	$('my_contacts').className	= "my_contacts off";
	$('contact_buttons').className	= "contact_buttons off";
	
	$('my_channels').className	= "my_channels";
	$('channel_buttons').className	= "channel_buttons";
}
function home_tog_contacts_on(){
	$('channels_tab').className	= "";
	$('contacts_tab').className	= "on";
	
	$('my_channels').className	= "my_channels off";
	$('channel_buttons').className	= "channel_buttons off";
	
	$('my_contacts').className	= "my_contacts";
	$('contact_buttons').className	= "contact_buttons";
}

function menuflip(whatison){
	var max = 5;
	for (a=1;a<max;a++){
		if (a == whatison){
			$('mapmenu' + a).className = "selected";
		}else{	
			$('mapmenu' + a).className = "";
		}
	}
}

var IE = document.all?true:false

/*
this is for finding the exact positions of elements on a page.
*/
function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

/*
set opacity of an element by 'this'
*/
function set_opacity(div, val) {
	if(!IE){
  if (div.filters) {  //For IE
    val *= 100;
    div.style.filter = 'alpha(opacity='+ val +')';
    try {
      div.filters.item("DXImageTransform.Microsoft.Alpha").opacity = val;
    } catch (e) { 
      // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
      div.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+val+')';
    }
  } else {
    div.style.opacity = val;
    div.style.MozOpacity = val;  //This is for older Mozilla Browsers
  }
	}
}

/*
set opacity of an element by id and add a centered spinner to it if spin, otherwise remove the spinner.
*/
function spin_opacity(tdiv, val, spin) {
  div = $(tdiv);
	if(!IE){
	
  if (div.filters) {  //For IE
    val *= 100;
    div.style.filter = 'alpha(opacity='+ val +')';
    try {
      div.filters.item("DXImageTransform.Microsoft.Alpha").opacity = val;
    } catch (e) { 
      // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
      div.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+val+')';
    }
  } else {
    div.style.opacity = val;
    div.style.MozOpacity = val;  //This is for older Mozilla Browsers
  }
	}
  if(spin == 1){
	  	//p = div.offsetParent		
		tleft =  (findPosX(div) + ((div.offsetWidth / 2) - 28));  // spinner is 56px wide
		ttop = (findPosY(div) + ((div.offsetHeight / 2) - 11)); // spinner is 21px tall
		$('gspin').style.top = ttop + 'px';
		$('gspin').style.left = tleft + 'px';
		$('gspin').style.display = 'block';
  }else{
	  	setTimeout("$('gspin').style.display = 'none'", 500);
  }
  
}
function busy_opacity(tdiv, val) {
  div = $(tdiv);	
	if(!IE){
  if (div.filters) {  //For IE
    val *= 100;
    div.style.filter = 'alpha(opacity='+ val +')';
    try {
      div.filters.item("DXImageTransform.Microsoft.Alpha").opacity = val;
    } catch (e) { 
      // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
      div.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+val+')';
    }
  } else {
    div.style.opacity = val;
    div.style.MozOpacity = val;  //This is for older Mozilla Browsers
  }
	}
}
/*
set opacity of an element by id from an iframe.
*/
function remote_spin_opacity(tdiv, val, spin) {
  div = $(tdiv);	
	if(!IE){
  if (div.filters) {  //For IE
    val *= 100;
    div.style.filter = 'alpha(opacity='+ val +')';
    try {
      div.filters.item("DXImageTransform.Microsoft.Alpha").opacity = val;
    } catch (e) { 
      // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
      div.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+val+')';
    }
  } else {
    div.style.opacity = val;
    div.style.MozOpacity = val;  //This is for older Mozilla Browsers
  }
	}
  if(spin == 1){
	  	//p = div.offsetParent		
		tleft =  (findPosX(div) + ((div.offsetWidth / 2) - 28));  // spinner is 56px wide
		ttop = (findPosY(div) + ((div.offsetHeight / 2) - 11)); // spinner is 21px tall
		parent.document.getElementById('gspin').style.top = ttop + 'px';
		parent.document.getElementById('gspin').style.left = tleft + 'px';
		parent.document.getElementById('gspin').style.display = 'block';
  }else{
	  	setTimeout("parent.document.getElementById('gspin').style.display = 'none'", 500);
  }
}
if (!IE) document.captureEvents(Event.MOUSEMOVE)
	
//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the overlay.
//

function getKey(e){
        if (e == null) { // ie
                keycode = event.keyCode;
        } else { // mozilla
                keycode = e.which;
        }
        key = String.fromCharCode(keycode).toLowerCase()
}


//
// listenKey()
//
function listenKey () { document.onkeypress = getKey; }

// string functions for trimming
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

// do tags for a field
function add_tag(tag, tofield, myid){
	var fieldParts = $(tofield).value.split(" ");	
	if(fieldParts.inArray(tag)){
		// remove the tag if clicked on again
		fieldParts = fieldParts.rmInArray(tag);
		$(tofield).value = fieldParts.join(" ").trim();
		$(myid).style.color = "";
		$(myid).style.background = "";		
	}else{
		// add the tag to the list
		fieldParts.push(tag);
		$(tofield).value = fieldParts.join(" ").trim();
		$(myid).style.background = "#c0c0c0";
		$(myid).style.color = "#fff";		
	}
	return true;
}

function URLEncode(plaintext){
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
	"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
	"abcdefghijklmnopqrstuvwxyz" +
	"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	//var plaintext = document.URLForm.F1.value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
		if (ch == " ") {
			encoded += "+";				// x-www-urlencoded, rather than %20
			} else if (SAFECHARS.indexOf(ch) != -1) {
				encoded += ch;
				} else {
					var charCode = ch.charCodeAt(0);
					if (charCode > 255) {
						alert( "Unicode Character '" 
						+ ch 
						+ "' cannot be encoded using standard URL encoding.\n" +
						"(URL encoding only supports 8-bit characters.)\n" +
						"A space (+) will be substituted." );
						encoded += "+";
						} else {
							encoded += "%";
							encoded += HEX.charAt((charCode >> 4) & 0xF);
							encoded += HEX.charAt(charCode & 0xF);
						}
					}
					} // for
					return encoded;
					//document.URLForm.F2.value = encoded;
					//return false;
				};
				
	function repls(){
		letters = "0123456789abcdefghijklmnnopqrstuvwxyz ABCDEFGHIJKLMNNOPQRSTUVWXYZ";
		desc = $('channel_name').value;
		newdesc = '';
		for (i = 0; i < desc.length; i++){
			Char = desc.charAt(i);
			if (letters.indexOf(Char) != -1){
				newdesc = newdesc + Char;
			}
		}
		// here is some nice prototype string functions at work
		desc = newdesc.gsub(' ', '_');
		desc = desc.toLowerCase();
		desc = desc.truncate(20, '');
		$('url_view').value = desc;
		$('url').value = desc;
		$('url2').innerHTML = "http://socialight.com/channels/" + desc;		
	}
	
function chSrc(text, more, isrc){
  img = "<img class='popup_img' src='"+ isrc +"'>";
  if (more == ''){more = img + "<br />" + text }else{more = img + '<p class="popup_mantra">' + text + '<br />"' +more + '"</p>';}
  tx = ['',more];
  //st = ["black","#ffffff","","","",,"black","","","","",,,,,,,,,,,"",2,,,]

  //original
  st=["white","","","","",,"white","#777","","","",,100,,2,"",2,,,,,"",,,,]

  //st=["white","#000099","","","",,"black","#e8e8ff","","","",,,,2,"#000099",2,,,,,"",3,,,]
  stm(tx, st);
}


function mapPop(text, more, isrc){
  more = more; // + "<br><img src='"+ isrc +"'>";
  tx = [text + more,''];	
  st = ["black","#ffffff","","","",,"black","","","","",,,,,,,,,,,"",2,,,]
  stm(tx, st);	
}

//suckerfish dropdowns
sfHover = function() {
	var sfEls = document.getElementById("tabnav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);