/*******************************************************************************
 *
 *  Ye OIde Tribe Javascripte Librarie
 *
 *  $Id: Utils.js 33443 2007-12-17 17:46:35Z root $
 *
 ******************************************************************************/

// Simple form submission method
function submitForm(myNextUrl) {
  // alert(myNextUrl);
  document.main.nextUrl.value = myNextUrl;
  document.main.submit(); 
}

// Small pop-up window
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=400,height=400');");
eval("page" + id + ".opener = self");
}

// Flexible window opening function
function openWin(url,name,width,height,winoptions) {

  var attributes = new Array();
  if (!url) return;
  if (!name) { name = "popup"; }
  if (width) { attributes[attributes.length] = "width=" + width; }        
  if (height) { attributes[attributes.length] = "height=" + height; }
  if (winoptions == "none") {
    attributes[attributes.length] = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no";
  } else if (winoptions == "simple") {
    attributes[attributes.length] = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes";
  } else if (winoptions) {
          attributes[attributes.length] = winoptions;
  } else {
          attributes[attributes.length] = "toolbar=yes,location=yes,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes";  
  }
  features = attributes.join(",");
  
  newWin = window.open(url,name,features);
  if (!newWin.opener) {
    // set reference to this window in the child
      newWin.opener = self;      
  }
  if (window.focus) { newWin.focus(); }
  return false;  
}

// Opens a popup window for images that resizes itself to fit the image
function popupPic(sPicURL) { 
  var temp = window.location.href.split("/");
  var domain = temp[2]; 
  var winUrl = "http://www.tribe.net/template/pub,PopPic.vm?picURL=" + sPicURL;
  newWin = window.open(winUrl,"photoPop","width=600,height=450,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");  
  if (!newWin.opener) {
    // set reference to this window in the child
    newWin.opener = self;      
  }
  if (window.focus) { newWin.focus(); }  
  return false;
} 

// Close window
function closeWin() {
        window.close();
}


// returns to previous page
function goBack() {
	history.go(-1);
}

// redirects to a given URL
function redirect(URL) {
	window.location.href = URL;
}

// Opens a popup window with a link to maps.yahoo.com
// Just give it a street address and city, state or zip
function checkMap(streetAddress, citystatezip) {
  query = "country=US&addr=" + escape(streetAddress) + "&csz=" + escape(citystatezip);
  maplink = "http://maps.yahoo.com/maps_result?" + query;
  openWin(maplink,'map',800,600,'');
}


// checks all checkboxes on the given form                                                                                                                         
function checkAll(formname) {
  for(var i=0;i<document.forms[formname].elements.length;i++) {
    if(document.forms[formname].elements[i].type == "checkbox") {
       document.forms[formname].elements[i].checked = true;
    }
  }
}

// checks all checkboxes in a certain divId
// HACK! v through z allow you to embed your checkboxes in a table.
// much better to do this recursively
function checkGroup(formname, divId) {
  for(var i=0;i<document.forms[formname].elements.length;i++) {
    if(document.forms[formname].elements[i].type == "checkbox") {
      v = document.forms[formname].elements[i].parentNode;
      w = v.parentNode;
      x = w.parentNode;
      y = x.parentNode;
      z = y.parentNode;
      if ((document.getElementById(divId) == v) || (document.getElementById(divId) == w) || (document.getElementById(divId) == x) || (document.getElementById(divId) == y) || (document.getElementById(divId) == z)) {
	    document.forms[formname].elements[i].checked = true;
      }
    }
  }
}

// unchecks all checkboxes on the given form                                                                                                                          
function uncheckAll(formname) {
  for(var i=0;i<document.forms[formname].elements.length;i++) {
    if(document.forms[formname].elements[i].type == "checkbox") {
       document.forms[formname].elements[i].checked = false;
    }
  }
}

// unchecks all checkboxes in a certain divId
// HACK! v through z allow you to embed your checkboxes in a table.
// much better to do this recursively
function uncheckGroup(formname, divId) {
  for(var i=0;i<document.forms[formname].elements.length;i++) {
    if(document.forms[formname].elements[i].type == "checkbox") {
      v = document.forms[formname].elements[i].parentNode;
      w = v.parentNode;
      x = w.parentNode;
      y = x.parentNode;
      z = y.parentNode;
      if ((document.getElementById(divId) == v) || (document.getElementById(divId) == w) || (document.getElementById(divId) == x) || (document.getElementById(divId) == y) || (document.getElementById(divId) == z)) {
	    document.forms[formname].elements[i].checked = false;
      }
    }
  }
}




//toggle visibility of a div
function toggleVisibility(divId) {
  myDiv = document.getElementById(divId);
  if (myDiv.style.display == "none") {
    myDiv.style.display = "";
  } else {
    myDiv.style.display = "none";
  }
  return false;
}

// disable form elements
//
// usage: onClick="toggleFormElements('thisID','element1','element2'...)
//
// where: thisID = ID of this checkbox
//        element(n) = elements you want this to show/hide
//
function toggleFormElements() {
	var toggler = arguments[0];
	if (document.getElementById(toggler).checked == true) {
		for (var i=1; i<arguments.length; i++) {
			document.getElementById(arguments[i]).disabled = true
		}
	}
	else if (document.getElementById(toggler).checked == false) {
		for (var i=1; i<arguments.length; i++) {
			document.getElementById(arguments[i]).disabled = false
		}
	}
}


// toggle visibility of a div and its image if available
//
// usage: <a href="javascript:toggleDisplay('divId')">
//
// where: fieldname = id of div to toggle
//        fieldnameDIV = id of hidden form element
//        fieldnameIMG = id of toggle image (optional)
//        fieldnameMOD = module to toggle
// 
// note: show() and hide() are used in ListingFieldsHead.vm's $bodyArgs
// to set the proper state when the page is (re)loaded

function toggleDisplay(id) {
  var myElement = document.getElementById(id);
  if (myElement) {
    if( myElement.style.display == "none") {
      show(id);
    } 
    else {
      hide(id);
    }
  }
}

function show(id) {
  if(document.getElementById(id)) {
    document.getElementById(id).style.display = "block";
    // toggle hidden form element if it exists
    if( document.getElementById(id + 'DIV') ) {
      document.getElementById(id + 'DIV').value = "show";
    }
    // toggle image if it exists
    if( document.getElementById(id + 'IMG') ) {
      document.getElementById(id + 'IMG').src = "/tribe/images/redesign/form_expanded.gif";
    }
    // toggle header image if it exists
    if( document.getElementById(id + 'HDR') ) {
      document.getElementById(id + 'HDR').src = "/tribe/images/redesign/hdr_expanded.gif";
    }
    // toggle header image if it exists
    if( document.getElementById(id + 'MOD') ) {
      document.getElementById(id + 'MOD').className = "moduleExpanded";
    }
  }
}

function hide(id) {
  if(document.getElementById(id)) {
    document.getElementById(id).style.display = "none"; 
    // toggle hidden form element if it exists
    if( document.getElementById(id + 'DIV') ) {
      document.getElementById(id + 'DIV').value = "hide";
    }
    // toggle image if it exists
    if( document.getElementById(id + 'IMG') ) {
      document.getElementById(id + 'IMG').src = "/tribe/images/redesign/form_collapsed.gif";
    }
    // toggle header image if it exists
    if( document.getElementById(id + 'HDR') ) {
      document.getElementById(id + 'HDR').src = "/tribe/images/redesign/hdr_collapsed.gif";
    }
    // toggle header image if it exists
    if( document.getElementById(id + 'MOD') ) {
      document.getElementById(id + 'MOD').className = "moduleCollapsed";
    }
  }
}


// Backtrack widget controls
// We set a cookie everytime you open/close the backtrack widget
// We call setBackTrack() in $bodyArgs

function showBacktrack() {
	document.getElementById('subnavLinks').style.display = "none";
	document.getElementById('backtrackOff').style.display = "none";
	document.getElementById('backtrackOn').style.display = "block";
	createCookie('backtrack','open');
}

function hideBacktrack() {
	document.getElementById('subnavLinks').style.display = "block";
	document.getElementById('backtrackOff').style.display = "block";
	document.getElementById('backtrackOn').style.display = "none";
	createCookie('backtrack','closed');
}

function setBackTrack() {
	var cookieState = readCookie('backtrack');
	if (cookieState == 'open') {
	 showBacktrack();
	}
	else {
		hideBacktrack();
	}
}


// Generic function to read a cookie and toggle the corresponding div. This is used onLoad().
function setToggleCookie(divId,cookieName) {
	var cookieState = readCookie(cookieName);
	if(cookieState) {
    if (cookieState == 'open') {
 		  show(divId);
	 	  createCookie(cookieName,'open');
    } else {
		  hide(divId);
		  createCookie(cookieName,'closed');
    }
  } else {
	  show(divId);
	  createCookie(cookieName,'open');
	}  
}

// Generic function to toggle div and cookie state. Triggered by user action.
function toggleCookie(divId,cookieName) {
  toggleDisplay(divId);
  if( document.getElementById(divId).style.display == "none" ) {
    createCookie(cookieName,'closed');
  } else {
    createCookie(cookieName,'open');
  }    
}

// Generic Set/Read/Hide Cookies functions
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else 
    var expires = "";
    var dom = document.domain;
    // Need to rejigger the cookie domain to subtract out any possible region info.
    var domArray = dom.split(".");
    var cookieDomain = "." + domArray[domArray.length-2] + "." + domArray[domArray.length-1];
    document.cookie = name+"="+value+expires+"; path=/; domain="+cookieDomain;
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}


// =====================================================
// Javascript Tabs
// Use the following markup structure:
//
//	<div class="tabs" id="profileTABS">
//		<div class="tab current" id="basicsTAB">
//			<a href="javascript: tab('basics', 'profile');">basics</a>
//		</div>
//		<div class="tab" id="personalTAB">
//			<a href="javascript: tab('personal', 'profile');">personal</a>
//		</div>
//	</div>
//
//	<div class="tabbed-content" id="profileDIVS">
//		<div id="basicsDIV" class="current">
//			here's the basic stuff
//		</div>
//		<div id="personalDIV" class="hidden">
//			here's the personal stuff
//	</div>

function tab(idToShow, group) {
	// reset tabs
	var x = document.getElementById(group + 'TABS').childNodes;
	for (var i=0;i<x.length;i++) {
		if (x[i].className == "tab current") {
			x[i].className = "tab";
		}
	}
	// hide all divs in group 
	var y = document.getElementById(group + 'DIVS').childNodes;
	for (var i=0;i<y.length;i++) {
		if (y[i].className == "current") {
			y[i].className = "hidden";
		}
	}
	// set class on current tab
	document.getElementById(idToShow + 'TAB').className = "tab current"; 
	// show current content
	document.getElementById(idToShow + 'DIV').className = "current"; 
}


// End Javascript Tabs
// ======================================================





// This method attaches a hover class to LI elements for the 
// suckerfish dropdown.  Used on pub,reg,Register.vm
// Swiped from www.htmldog.com
function sfHover() {
	var sfEls = document.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"), "");
		}
	}
}

// strip out MS Word control characters from <textarea>
function stringFilter(input) {
	s = input.value;
	filteredValues = "1234567890";     // Characters stripped out
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++) { 
		var c = s.charAt(i);
		if (filteredValues.indexOf(c) == -1) returnString += c;
	}
	input.value = returnString;
}

// get rid of the default stuff in peopleSearchForm
	function cleanPeopleSearchForm() {
		if(document.getElementById('firstname').value=='first name') {
			document.getElementById('firstname').value = '';
		}
		if(document.getElementById('lastname').value=='last name') {
			document.getElementById('lastname').value = '';
		}
		if(document.getElementById('email').value=='e-mail address (optional)') {
		    document.getElementById('email').value='';
		}
	}


// replace characters in form fields (from MS Word paste)
//
// When pasting from MS Word into a textarea inIE6 on a multipart form, IE6
// mangles the POST if it runs into a control character greater than 255. 
// The solution is to replace the character with its html equivalent. 
//
// Be sure and run stringReplace BEFORE you submit a form like this.
//
// Currently used on:
//
// Manage.vm
// blog/ManageEntry.vm
//
// A list of likely characters and their replacements can be found at:
// http://intertwingly.net/stories/2004/04/14/i18n.html
//

function stringReplace(input) {
	var s = input.value;
	for(var i=0;i<s.length;i++) {		
		c = s.charCodeAt(i);
		if(c>255) {
			var re = new RegExp(s.charAt(i));
// uncomment the following line to see which characters are getting replaced
//			alert(re + '= ' + c);
			s = s.replace(re, "&#"+c+";");
		}
	}
	
	// replacement string definitions
	s = s.replace(/&#8217;/gi, "&rsquo;"); // right single quote
	s = s.replace(/&#8216;/gi, "&lsquo;"); // left single quote
	s = s.replace(/&#8230;/gi, "&hellip;'"); // ...
	
	input.value = s;
}


// Popup a little javascript confirmation dialog for moderators
// who are deleting a listing, event, or post
function deleteConfirm(type) {
  return confirm("You are about to remove this " + type + " from your tribe. Proceed?")
}


// Fade effect for new postings
// First seen at http://basecamphq.com

var Color= new Array();
Color[1] = "ff";
Color[2] = "ee";
Color[3] = "dd";
Color[4] = "cc";
Color[5] = "bb";
Color[6] = "aa";
Color[7] = "99";

function waittofade() {
	if (document.getElementById('fade')) {
    setTimeout("fadeIn(7)", 10);
	 }
}

function fadeIn(where) {
    if (where >= 1) {
        document.getElementById('fade').style.backgroundColor = "#ffff" + Color[where];
		  if (where > 1) {
			  where -= 1;
			  setTimeout("fadeIn("+where+")", 200);
			} else {
			  where -= 1;
			  setTimeout("fadeIn("+where+")", 200);
			  document.getElementById('fade').style.backgroundColor = "transparent";
			}
    }
}

// sets the onclick action of the toggle div to also call functionName after the toggleDisplay function has been called.
function setToggleAction(toggleId,functionName) {
  var myToggle = document.getElementById('TOG'+toggleId);
  if(myToggle) {    
    var myElement = document.getElementById(toggleId);
    myToggle.onclick = function() { toggleDisplay(toggleId); if (myElement.style.display == "block") { eval(functionName); }  return false; }
  }
}

// Enables flagging of tribecard line items from tribecard
function submitFlagTribeCard( flagType, itemType, contentId )
{
    myForm = document.forms["flaggingForm"];            
    myForm.elements['flagType'].value = flagType; // SPAM, SCAM, etc.
    myForm.elements['itemType'].value = itemType; // 'photo' or 'listing'
    myForm.elements['contentId'].value = contentId; 
    myForm.elements['origin'].value = window.location;
    
    if(itemType == "photo") {
      myForm.elements['photoId'].value = contentId;  
      myForm.elements['action'].value = "tags.TagPhotoAction";              
    } else if(itemType == "listing" || itemType == "event") {
      myForm.elements['listingId'].value = contentId;                         
      myForm.elements['action'].value = "tags.TagListingAction";              
    }

    myForm.submit();
}

// Do setup for popup login form in masthead
function showLogin() {
	if( navigator.appVersion.indexOf("MSIE")!=-1 ) {
		return true; // bail if this is IE
	} else {
		var emailField = document.getElementById('email');     
		var realPW = document.getElementById('password');
		document.getElementById('loginButtons').style.visibility = 'hidden';
		document.getElementById('mastheadLoginForm').style.visibility = 'visible';
		if(emailField.value == '') {
			emailField.value = 'e-mail';
			emailField.style.color ='#999';
		}
		emailField.focus(); 
		emailField.select();
		if(realPW.value == '') {
			realPW.className = "passwordBg";
		}
		return false;
	}
}


// Detect keypress of enter and submit form  
  function submitEnter(myfield,e)
  {
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;
  if (keycode == 13) {
    myfield.form.submit();
    return false;
  } else
    return true;
  }  

// Set the clickpath into the cookie, rather than in the URL.  This value
// will be immediately stripped out on the back end.
function setClick(path)
{
    createCookie("clickPath", path, 0);
    return true;
}

// resize window by 1-pixel to fix rounded corners that don't appear in the right place
function tickleWindow() {
//	window.resizeBy(0,-1);
//	window.resizeBy(0,1);  
}


// disable region selector and set it to My Location if network selector = anyone 
function checkRegion(select) {
  var regionSelector = document.getElementById("regionSelector");  
  if(select.value == 0) {
    regionSelector.value = "Y";
    regionSelector.disabled = true;
  } else {
    regionSelector.disabled = false;    
  }
}



// -----------------------------------------------  
// INLINE EDIT FUNCTIONS


 // this function initializes a toggle edit form
 // pass in the id of the div containing the form
 // pass in num if there are more than one of any type of form
 function initToggleForm(id, type, num ) {
 
  var elem = document.getElementById(id);
  if (!elem) return;
  if (!type) type = "text";
  if (!num) num = '';
  
  // get all anchor tags and attach toggleFormEdit to their onclick
  var elemas = elem.getElementsByTagName('A');
  for (var i = 0; i < elemas.length; i++)
  {
    elemas[i].onclick = toggleFormEdit;
    elemas[i].num = num;
    elemas[i].type = type;    
    elemas[i].toggleId = id;    
  }
  
  //initTextAreaCounter('titleCounter' + num, 'titleField' +num , 85)
 }
 
  function toggleFormEdit() {
    var num = this.num;
    var tid = this.toggleId;
    var formType = this.type;
    var form =document.getElementById(tid+'Form'+num);
    
    if (this.id == tid+'Edit'+num) {
      if(formType == "radio") {
        // store value of currently selected radio button
        for(var i=0;i < form.elements["photo_priv"].length; i++) {
          var myRadio = form.elements["photo_priv"][i];
          if(myRadio.checked) {
            form.currentRadio = myRadio;
          }
        }         
      }
      doEdit(tid,num)
    } else if (this.id == tid+'Save'+num) {
      doSave(tid,num);
      form.submit();
    } else if (this.id == tid+'Cancel'+num) {
      if(formType == "radio") {
        // restore value of previously selected radio button
        for(var i=0;i < form.elements["photo_priv"].length; i++) {
          var myRadio = form.elements["photo_priv"][i];
          if(myRadio = form.currentRadio) {
            myRadio.checked = true;
          }
        }      
      }
      hideForm(tid,num);
      var ta =  document.getElementById(tid+'Field'+num);
      if(ta) ta.value = '';
    }
    return false;
  }
  
 
  function showForm(tid, num) {
    var formwrap =document.getElementById(tid+'FormWrap'+num);    
    var content = document.getElementById(tid+'Content'+num);    
    if(formwrap && content) {
      content.style.display = 'none';
      formwrap.style.display = 'block';    
    }
  } 
 
  function hideForm(tid, num) {
    var formwrap =document.getElementById(tid+'FormWrap'+num);    
    var content = document.getElementById(tid+'Content'+num);    
    if(formwrap && content) {
      formwrap.style.display = 'none';
      content.style.display = 'block';    
    }
  }
 
  function doEdit(tid,num) {
    var defaultText = "";
  
    // get text field
    var ta =  document.getElementById(tid+'Field'+num);
    
    // get the div containing the form
    var formwrap =document.getElementById(tid+'FormWrap'+num);
         
    // get the static content div
    var content = document.getElementById(tid+'Content'+num);
    
    // get the static content text
    var targetelem = document.getElementById(tid+'Text'+num);
    
    // get hidden field holding value of static text
    var hiddenelem = document.getElementById(tid+'Hidden'+num);

    showForm(tid,num)
  
    // set value of text field to value of hidden element (static text)
    if(ta) {
      ta.value = ( targetelem.innerHTML.toLowerCase() == defaultText.toLowerCase() ) ? '' : hiddenelem.value;
      ta.focus();
    }  
  }
 
  function doSave(tid,num) {
    var defaultText = "";
    if(!num) { num= ""; }
    // get text field
    var ta =  document.getElementById(tid+'Field'+num);
    // get hidden field holding value of static text
    var hiddenelem = document.getElementById(tid+'Hidden'+num); 
    // get the static content text
    var targetelem = document.getElementById(tid+'Text'+num);
            
    hideForm(tid,num);

    // set value of static text to value of input field
    if(ta) {
      var newvalue = ( ta.value.charAt(ta.value.length -1) == '&' ) ? ta.value+' ' : ta.value;
      targetelem.innerHTML = ( ta.value == '' ) ? defaultText : replaceHTML(newvalue, 1, 1);
      hiddenelem.value = ta.value;
      if(tid == "description") {
        // get the static content div
        var content = document.getElementById(tid+'Content'+num);      
        if(newvalue.length < 130) {
          content.style.textAlign = 'center';
        } else {
          content.style.textAlign = 'left';      
        }
      }
    } else {
    // set value of static text to value of input field
      targetelem.innerHTML = hiddenelem.value
    } 
  }
 
  function replaceHTML(str, dir, limited) {
    if (dir) {
      // Escape
      var repl = (document.all) ? /\r/gi : /\n/gi ;
      str = str.replace(/</g, '&lt;'); 
      str = str.replace(/>/g, '&gt;');
      str = str.replace(repl, '<br>');
      if(!limited) str = str.replace(/ /gi, '&nbsp;');
    } else {     
      // Unescape
      var repl = (document.all) ? '\r' : '\n' ;
      str = str.replace( /&lt;/g, '<');
      str = str.replace( /&gt;/g, '>');     
      str = str.replace(/<br>/gi, repl);
      if(!limited) str = str.replace(/&nbsp;/gi, ' ');
    }
    return str;
  }
  
  // set hidden field value for radio button forms
  function setRadioHidden(tid, text, num) {
    if (!num) num = '';
    
    // get hidden field holding value of static text
    var hiddenelem = document.getElementById(tid+'Hidden'+num);
    if(hiddenelem) {
      hiddenelem.value = text;
    }
  }
  
// INLINE EDIT FUNCTIONS
// ---------------------------------------------------------------------------

