// Maya's Mom, Inc
// Copyright 2006 (c) All Rights Reserved

function confirmMakePublic(){
  if(confirm('Do you want to make all of your photos public?\n(You can make specific photos public one at a time on the "Upload Photos" page.)')){
    return true;
  }
  else{
    return false;
  }
}

function add2list(item, list) {
   var str = '';
   item = trim(item);
   var elem = $(list);

   var cv = trim(elem.value);
   item_array = cv.split('/\s*,\s*/');

   if (!item_array.in_array(item)) {
   	if (item.length > 1) { item_array.push(item); }
   }

   for (var i=0; i < item_array.length; i++)
   {
   	if (str.length > 1) { str = str + ', ' + item_array[i]; }
   	else { str = item_array[i]; }
   }
   str = trim(str);
   elem.value = str;
}

function sendThanks(uniqid) {
   sf_elem = $('sf_'+uniqid);
   fm_elem = $('fm_'+uniqid);
   sf_elem.style.display = 'none';
   $(uniqid).innerHTML = "Sending...";

   fmdata = Form.serialize('fm_'+uniqid)
   var myAjax = new Ajax.Updater(
			uniqid, "/action/act_ajax.php",
			{
				method: 'get',
				parameters: fmdata
			});
}

function jumpTo() {
   link = $F('jumpmenu');
   if (window.urchinTracker) {
     urchinTracker('/analytics/jumpto/'+link);
   }
   top.location.href = link;
}

function set_focus(item) { $(item).focus(); }
function set_active(obj) { obj.style.color = '#000'; }

function cbsel(item) {
	fe = $(item);
	if (fe.checked) { fe.checked=false; }
	else { fe.checked = true; }
}

function togglelayer(id) {
	var d = $(id);

   if (d) {
      if (d.style.display == 'block') {
         d.style.display = 'none';
      }
      else { d.style.display = 'block'; }
   }
}

function showlayer(id) {
	var d = $(id);
   d.style.display = 'block';
}

function hidelayer(id) {
	var d = $(id);
	d.style.display = 'none';
}

function is_search_blank() {
   q = trim($F('search_q_id'));
   $('search_q_id').focus();
   if (q == "") { return false; }
   else { return true; }
}


function add_friend(fruid) {
   var obj = $('add2fr_'+fruid);
   hidelayer('frconf_box_'+fruid);

   var today = new Date(); var td = today.getDate(); var tm = 1+today.getMonth();
   obj.innerHTML = "<span class=smgray>Invite sent "+tm+"/"+td+"</span>";

   var Fsuccess = function(t) {  }
   var Ffailure = function(t) {  }

   var params = 'fruid=' + fruid + '&action=add_friend&' + Form.serialize('frform_'+fruid);
   var myAjax = new Ajax.Request('/action/act_ajax.php', {method:'post', postBody:params, onSuccess:Fsuccess, onFailure:Ffailure});

   return false;
}

function rating(num, uniqid, small) {
   img_prefix = (small) ? "/img/star_sm" : "/img/star";
   for (i=1; i <= num; i++) { $('rt'+i+uniqid).src = img_prefix + "_hlt.gif"; }
   for (i=num+1; i <=5; i++) { $('rt'+i+uniqid).src = img_prefix + ".gif"; }
}

function clear_rating(curr_rating, rating_self, uniqid, small) {
   img_prefix = (small) ? "/img/star_sm" : "/img/star";
   star_img = (rating_self) ? img_prefix + "_hlt.gif" : img_prefix + "_red.gif";
   for (i=1; i <= curr_rating; i++) { $('rt'+i+uniqid).src = star_img; }
   for (i=curr_rating+1; i <=5; i++) { $('rt'+i+uniqid).src = "/img/star.gif"; }
}


function rate_it(score, tid, type, uniqid, small) {
   var ratingFailure = function(o) {  };
   var ratingSuccess = function(o) { draw_widget(score, tid, type, 1, uniqid, small) };
   obj = $('rating_'+uniqid);
   obj.innerHTML = "Saving...";
   var pars = "action=set_rating&tid="+escape(tid)+"&type="+escape(type)+"&rating="+escape(score);
   var myAjax = new Ajax.Request("/action/act_ajax.php", {method:'get', parameters:pars, onSuccess:ratingSuccess, onFailure:ratingFailure});
}

function draw_widget(rating, tid, type, self, uniqid, small) {
   if (small) { img_prefix="/img/star_sm"; width=16; height=15; }
   else { img_prefix="/img/star"; width=19; height=18; }

   obj = $('rating_'+uniqid); stars = "";
   for (i=1; i <= 5; i++)
   {
      if (rating >= i) { img = img_prefix + "_hlt.gif"; }
      else { img = img_prefix + ".gif"; }
      stars += "<img id='rt"+i+uniqid+"' src='"+img+"' width='"+width+"' height='"+height+"' onMouseOver=\"rating("+i+", "+uniqid+", "+small+")\" onMouseOut=\"clear_rating("+rating+", "+self+", "+uniqid+", "+small+")\" onClick=\"rate_it("+i+", "+tid+", '"+type+"', "+uniqid+", "+small+")\">";
   }
   obj.innerHTML = stars;
}

function notify_me(elem, tid, type) {
   var nmSuccess = function(o) { $(elem).innerHTML = '&#187; Notification Set! <a href="#" onClick="notify_remove(\'notifyme\',\''+tid+'\',\'talk\'); return false;" title="Remove Notification"><img src="/img/icn/x.gif" border="0"></a>'; }
   var nmFailure = function(o) { }
   pars = "action=notifyme&tid="+tid+"&type="+type
   var myAjax = new Ajax.Request("/action/act_ajax.php", {method:'get', parameters:pars, onSuccess:nmSuccess, onFailure:nmFailure});
}

function notify_remove(elem, tid, type) {
   var nrSuccess = function(o) { $(elem).innerHTML = '&#187; Notification Removed'; }
   var nrFailure = function(o) { }
   pars = "action=notifyrem&tid="+tid+"&type="+type
   var myAjax = new Ajax.Request("/action/act_ajax.php", {method:'get', parameters:pars, onSuccess:nrSuccess, onFailure:nrFailure});
}

/************************************************************
 * Expand Section
 ************************************************************/
function expand_section(elem_id, cname, save) {
  elem_exp = $(elem_id + "_exp");

  if (elem_exp.className == cname+"expanded_arrow") {
    elem_exp.className=cname+"expander_arrow";
    ajaxSaveSession(elem_id, "collapsed");
  }
  else {
    elem_exp.className=cname+"expanded_arrow";
    ajaxSaveSession(elem_id, "expanded");
  }
  togglelayer(elem_id);
}


function ajaxSaveSession(varname, value) {
  var assSuccess = function(o) { };
  var assFailure = function(o) { };
  pars = "action=save_session&varname="+varname+"&value="+value;
  var myAjax = new Ajax.Request("/action/act_ajax.php", {method:'get', parameters:pars, onSuccess:assSuccess, onFailure:assFailure});
}

/************************************************************
 * Countdown Characters
 ************************************************************/
function countdown_chars(field, limit) {
  content_length = $F(field).length;
  remaining = limit - content_length;
  if (remaining < 1) {
    $(field).value = $F(field).substring(0,limit);
  }
  $('char_count').innerHTML = remaining;
}


//-- generic js
function trim(str) { return str.replace(/^\s*|\s*$/g,""); }

Array.prototype.in_array = function(search_term) {
	for (var i=0; i < this.length; i++) {
		if (this[i] === search_term) { return true; }
	}
	return false;
}

/* From: json.js http://www.json.org/js.html  2006-04-28 */
String.prototype.parseJSON = function () {
    try {
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};

/************************************************************
 * Search box popup for activity lists
 ************************************************************/
var optnum = 4;
var spos = 0;
var popup_window = null;

function addNewRow()
{
   var opttext='<div class="row clearfix"><div class="label">&nbsp;</div><div class=elem>'+optnum+'.<input type="text" name="answers['+optnum+']" value="" size=45></div></div>';
   new Insertion.Before('addopt', opttext);
   optnum = optnum + 1;
}

function SearchWindow()
{
   scrit = escape($F('scrit'));
   qs = "q=" + scrit;
   if(popup_window)
   {
      popup_window.close();
   }
   popup_window = window.open('/action/lists_search?'+qs, 'SWIN', 'width=250,height=450,scrollbars=auto,menubar=no,location=no,resizable=yes');
}

function PopURL(url, dimX, dimY)
{
   if(popup_window)
   {
      popup_window.close();
   }
   popParams = 'width=' + dimX + ',height=' + dimY + ',scrollbars=no,menubar=no,location=no,resizable=no,status=no,statusbar=no';
   popup_window = window.open(url, 'SWIN', popParams);
}


function resetForm() {
  var aFailure = function(t) { return null; };
  var aSuccess = function(t) { return null; };

  var pars = "action=clear_title";
  var myAjax = new Ajax.Request("/action/act_ajax.php", {method:'get', parameters:pars, onSuccess:aSuccess, onFailure:aFailure});
  top.document.location.reload();
}


function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function writeSessionCookie(cookieName, cookieValue) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
}

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}


var Mym_Pop = {

  pop_close: function(divid, anchor, left, top){
    this.pop(divid, anchor, left, top);
    this.delay_unpop(divid, 2000);
  },

  pop: function(divid, anchor, left, top){
    popForm = $(divid);
    posArr = findPos(anchor);

    popForm.style.top = (posArr[1] + top) + "px";
    popForm.style.left = (posArr[0] + left) + "px";
    popForm.style.display = "block";
  },

  unpop: function(divid){
    hidelayer(divid);
  },

  delay_unpop: function(divid, delay){
    setTimeout("Mym_Pop.unpop('" + divid + "')", delay);
  }

}


/************************************************************
 * popups within the page
 ************************************************************/
var ComplListPop = {
   open: function(parent){
      complDetail = $('compl_detail');
      posArr = findPos(parent);

      complDetail.style.top = (posArr[1] + 21) + "px";
      complDetail.style.left = posArr[0] + "px";
      togglelayer('compl_detail');
   },

   close: function(){
      $('compl_detail').style.display = "none";
   }
}

var ComplementPop = {
   uniqid: null,

   notes: {
      thank_you: "I will use my grown-up manners to say thank you!",
      congrats: "Break out the bubbly!",
      great_idea: "Me likey!",
      you_rock: "Now you can have TWO cookies for dessert!",
      so_sweet: "That's so sweet it's dripping with sugar.",
      just_a_note: "Roses are red, violets are blue. Something just made me think of you.",
      i_can_relate: "Excuse me while I have a deja vu moment.",
      great_photos: "Nice shots!",
      laugh_out_loud: "No really, I am Laughing. Out. LOUD."
   },

   disabledNotes: {
   },

   disabledPops: {
   },

   open: function(uniqid, anchor, left, top){
     divid = "pop_" + uniqid;
     this.pop(divid, anchor, left, top);

      if(this.disabledPops[uniqid]){
         this.delayClose(false);
         return;
      }

      noteField = $("note_" + uniqid);
      noteField.select();
      noteField.focus();
   },

   close: function(uniqid){
     hidelayer("pop_" + uniqid);
   },

   setNote: function(uniqid, obj){
      notesTextArea = $("note_" + uniqid);
      if(!this.disabledNotes[uniqid]){
         notesTextArea.value = this.notes[obj.value];
      }
      notesTextArea.select();
      notesTextArea.focus();
   },

   disableNote: function(uniqid){
     this.disabledNotes[uniqid] = true;
   },

   send: function(uniqid, reload){
      this.uniqid = uniqid;
      var fmData = Form.serialize("pop_fm_" + uniqid);

      this._sending(uniqid);
      new Ajax.Updater('pop_inner_' + uniqid, '/action/act_ajax.php',
            {method: 'post', postBody: fmData, onSuccess: this._sendSuccess, onFailure: this._sendFailure});
      this.delayClose(reload);

      this.disabledPops[uniqid] = true;
      linkWrapper = $(uniqid);
      linkWrapper.className = "smgray";
      linkWrapper.innerHTML = "Note Passed";
   },

   _sending: function(uniqid){
      var innerElem = $("pop_inner_" + uniqid);
      innerElem.innerHTML = " \
         <div style=\"text-align: center;\"> \
         <table style=\"margin-top: 75px; margin-left: auto; margin-right: auto;\"> \
         <tr><td style=\"text-align: center;\"><img src=\"/img/loading.gif\"/></td><td style=\"font-size: 2em;\">Passing Note</td></tr> \
         </table> \
         </div> \
      ";
   },

   _sendFailure: function(resp){
      var innerElem = $("pop_inner_" + this.uniqid);
      innerElem.innerHTML = " \
         <div style=\"text-align: center;\"> \
         <table style=\"margin-top: 50px; margin-left: auto; margin-right: auto;\"> \
         <tr><td style=\"text-align: center;\"></td> \
         <td style=\"font-size: 2em; color: red; text-align: center;\">There was a issue passing your note. Please try again later.</td></tr> \
         </table> \
         </div> \
      ";
      this.delayClose(false);
   },

   _sendSuccess: function(resp){
      this.delayClose(false);
   },

   delayClose: function(reloadPage){
      if(reloadPage){
         setTimeout("window.location.reload()", 2200);
      }
      setTimeout("ComplementPop.close('" + this.uniqid + "')", 2000);
   }
}

var BlockPop = {

  open: function(divid, anchor, left, top, isfriend){
    this.pop(divid, anchor, left, top);
    this.delayClose(2000);
  }
}

Object.extend(ComplementPop, Mym_Pop);


function setSendTo(recipArr){
   var sendto = $('sendto');
   sendto.value = recipArr.join(', ');
}

function getCurrRecipsArr(){
   recipArr = $('sendto').value.split(/\s{0,}\,\s{0,}/);
   if(recipArr[0] == ""){recipArr.clear();}

   return recipArr.collect(
      function(r){
         return r.replace(/^\s*/, '').replace(/\s*$/, '');
      }
   );
}

function addFJPromptSubscr(uid, type){
  if(type == "mini" || type == "bigger"){
    url = '/profile/a/edit_profile/nb_notify?a=add&tuid=' + uid;
    if(type == "mini"){
      url += '&t=m';
    }
    new Ajax.Request(url, {
      method: 'get',
      onSuccess: function(transport) {
        $('nb_sub_ctnt').innerHTML = transport.responseText;
      }
    });
  }
}

function remFJPromptSubscr(uid, type, appendUrl){
  if(type == "mini" || type == "bigger"){
    url = '/profile/a/edit_profile/nb_notify?a=rem&tuid=' + uid;
    if(type == "mini"){
      url += '&t=m';
    }
    new Ajax.Request(url, {
      method: 'get',
      onSuccess: function(transport) {
        $('nb_sub_ctnt').innerHTML = transport.responseText;
      }
    });
  }
  else{ //redirect mode
    document.location.href = '/profile/a/edit_profile/nb_notify?t=r&a=rem&tuid=' + uid + '&' + appendUrl;
  }
}

var PhotoSlider = Class.create();
PhotoSlider.prototype = {
   slider: null,
   imgHashArr: null,
   visibleImgCount: 0,
   currFirstVisIdx: 0,
   imgContArr: null,

   initialize: function(slider, imgHashArr, visibleImgCount){
      this.slider = slider;
      if(!this.slider){return;}
      this.slider.style.visibility = "hidden";
      this.visibleImgCount = visibleImgCount;
      this.imgHashArr = imgHashArr;
      this.slider.innerHTML = "";
      this.imgContArr = new Array();

      this.currFirstVisIdx = 0;
      /*
      this.currFirstVisIdx = getCookieValue("currPsIdx");
      if(!this.currFirstVisIdx){
         this.currFirstVisIdx = 0;
         writeSessionCookie("currPsIdx", "0");
      }
      else{
         this.currFirstVisIdx = parseInt(this.currFirstVisIdx);
      }
      */

      for(j = 0; j < Math.max(this.visibleImgCount, this.imgHashArr.length); j++){
         if(j < this.imgHashArr.length)
            this.imgContArr[j] = this.createDomObj(this.imgHashArr[j]);
         else
            this.imgContArr[j] = this.createDomObj(null);

         if(j == (this.currFirstVisIdx)){

         }
      }

      this.setSliderPhotos(0);
      this.addNavArrows();
      this.slider.style.visibility = "visible";
      this.slider.style.display = "block";

      this.scrolls = (this.imgHashArr.length > this.visibleImgCount) ? true : false;
   },

   addNavArrows: function(){
      leftImage = document.createElement("img");
      leftImage.className = "psLeft";
      leftImage.src = "/img/arr_l.gif";

      lAnch = document.createElement("a");
      lAnch.setAttribute("href", "#");
      Event.observe(lAnch, 'mouseup', this.scrollLeft.bindAsEventListener(this), false);
      lAnch.appendChild(leftImage);
      this.slider.parentNode.insertBefore(lAnch, this.slider);

      rightImage = document.createElement("img");
      rightImage.className = "psRight";
      rightImage.src = "/img/arr_r.gif";

      rAnch = document.createElement("a");
      rAnch.setAttribute("href", "#");
      Event.observe(rAnch, 'mouseup', this.scrollRight.bindAsEventListener(this), false);
      rAnch.appendChild(rightImage);

      this.slider.parentNode.insertBefore(rAnch, this.slider.nextSibling);

      clearDiv = document.createElement("div");
      clearDiv.style.clear = "both";
      rAnch.parentNode.insertBefore(clearDiv, rAnch.nextSibling);
   },

   scrollRight: function(){
      if(!this.scrolls){return false;}

      this.currFirstVisIdx = ((this.currFirstVisIdx + 1) > (this.imgHashArr.length - 1)) ? 0 : this.currFirstVisIdx + 1;
      this.setSliderPhotos(this.currFirstVisIdx);
      return false;
   },

   scrollLeft: function(){
      if(!this.scrolls){return false;}

      this.currFirstVisIdx = (this.currFirstVisIdx == 0) ? this.imgHashArr.length - 1 : this.currFirstVisIdx - 1;
      this.setSliderPhotos(this.currFirstVisIdx);
      return false;
   },

   setSliderPhotos: function(firstIdx){
      while(this.slider.firstChild){
         Element.remove(this.slider.firstChild);
      }

      currIdx = firstIdx;

      for(i = 0; i < this.visibleImgCount; i++){
         idxCont = this.imgContArr[currIdx];

         if(i != 0)
            idxCont.style.marginLeft = "3px";
         else
            idxCont.style.margin = "0px 0px";

         this.slider.appendChild(idxCont);

         if(this.scrolls)
            currIdx = (((currIdx + 1) > (this.imgHashArr.length - 1))) ? 0 : currIdx + 1;
         else
            currIdx++;
      }

      writeSessionCookie("currPsIdx", String(firstIdx));
   },

   createDomObj: function(imgHash){
      // create the div for the spot in the slider
      idxCont = document.createElement("div");
      idxCont.className = "ps_idx_cont";

      // create the image container, create the image, add it to the container
      imgCont = document.createElement("div");
      imgCont.className = "ps_img_cont";

      // if we actually have an image for this spot, add it
      if(imgHash != null){
         // create the nickname container
         nickCont = document.createElement("div");
         nickCont.innerHTML = "<a href=\"/profile/" + imgHash['shortname'] + "\">" + imgHash['nickname'] + "</a>";
         nickCont.style.textAlign = "center";

         imgObj = this.createImg(imgHash);
         imgCont.appendChild(imgObj);

         // append the image container and the nickname container to the index div
         idxCont.appendChild(imgCont);
         idxCont.appendChild(nickCont);
      }
      else{
         idxCont.appendChild(imgCont);
      }

      return idxCont;
   },

   createImg: function(imgObj){
      // create an image element
      img = document.createElement("img");
      img.setAttribute("src", "/phs/" + imgObj['basedir'] + "/sq/" + imgObj['filename']);

      // create the href that wraps the image
      anch = document.createElement("a");
      anch.setAttribute("href", "/photos/" + imgObj['shortname'] + "/" + imgObj['id']);
      anch.appendChild(img)

      // return the image within the href
      return anch;
   }
}