/*
 *  $Id: dipity.js 9015 2011-06-30 15:36:25Z broox $
 *
 *  Copyright (c) 2008 Underlying Inc. All rights reserved.
 */
 
//check for value in array
Array.prototype.exists = function(search) {
	if (this.length == 0) { return false; }	
	for (var i = this.length; i--;) {
		if (this[i] == search) { return true; }
  }
	return false;
}

//trim whitespace from beginning/end of string
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,'');
}

//make sure a date is valid
Date.prototype.valid = function() {
  return isFinite(this);
}

if (dipity == undefined) var dipity = {};
dipity.enableLogging = true;

dipity.log = function(msg) { this.logger.debug(msg); }
dipity.logger = { date:null, timestamp:null }
dipity.logger.init = function() {
  if (!dipity.enableLogging || !window.console) { return false; }
  this.date = new Date;
  this.timestamp = this.date.getTime();
  return true;
}
dipity.logger.debug = function(msg) {
  if (!this.init()) { return false };
  if (typeof(msg) == 'string')
    console.log('Debug [' + this.timestamp + ']: ' + msg); 
  else
    console.log('Debug [' + this.timestamp + ']: ', msg); 
}
dipity.logger.error = function(msg) {
  if (!this.init()) { return false };
  if (typeof(msg) == 'string')
    console.error('Error [' + this.timestamp + ']: ' + msg); 
  else
    console.error('Error [' + this.timestamp + ']: ',msg); 
}

dipity.analytics = {};
dipity.analytics.trackPageview = function(uri) {
  if (typeof(_gaq) == 'undefined') { dipity.log('Error tracking page view'); return; }
  dipity.log('trackPageview: '+uri);
  _gaq.push(['_trackPageview',uri]);
}

dipity.analytics.trackEvent = function(category, action, label, number) {
  if (typeof(_gaq) == 'undefined') return;
  dipity.log('trackEvent: '+category+', '+action+', '+label+', '+number);
  _gaq.push(['_trackEvent', category, action, label, number]);
}

$(document).ajaxComplete(function() {
  $('.styledButton').removeClass('loading');
  $('.styledButton div.pulse').hide();
});

/*
\if (typeof img.onerror != "undefined")
{
img.onerror = function()
{
this.src = alt_src;
return true;
}
}
*/

dipity.util = {};
dipity.util.fixImages = function(selector,image) {
  $(selector).each(function() {
    if (!this.complete || (!$.browser.msie && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0))) {
      $(this).attr('src', image);
    }
  });
  
  //this should work but doesnt...
  /*
  $(selector).error(function () {
    $(this).unbind('error').attr('src', image);
  });
  */
  
  //this seems like it should work too...
  /*
  var imageList = $(selector).each(function() {
    var img = $(this);
    dipity.log(img);
    if (typeof img.context.onerror != "undefined") {
      dipity.log('onerror is defined');
      if (img.context.onerror) {
        dipity.log('error');
      } else {
        dipity.log('no error');
      }
      
      img.context.onerror = function() {
        dipity.log('we have an error!');
        img.attr('src',image);
        return true;
      }
      
      //ghetto, doesnt really work
      if(img.height() <= 1) {
        img.attr('src',image);
      }
    } else { dipity.log('onerror is undefined'); }
  });  
  */
}

/*
dipity.search = { 
  field: undefined,
  labelText: 'Search Topics'
};

dipity.search.init = function() {
  this.field = $('#'+this.context+'CommentField');
  this.field.val(this.labelText);
  
  this.field.bind('focus',dipity.search,this.activate);
  this.field.bind('blur',dipity.search,function(event) {
    thisObject = event.data;
    setTimeout(function(thisObject,event) {
      dipity.search.clear(event)
    }, 500,dipity.search,event);
  });
}

dipity.search.activate = function(event) {
  if (!dipity.search.textEntered()) {
    dipity.search.field.val('');
    dipity.search.field.css('color','#000');
    //dipity.search.fField.addClass('activeSearch');
  }
}

dipity.search.clear = function(event) {
  if (dipity.search.textEntered()) { return false; }
  dipity.search.field.val(this.labelText);
  dipity.search.field.css('color','#CCC');
  //dipity.search.commentField.removeClass('activeSearch');
}

dipity.search.textEntered = function() {
  if (this.field.val() == this.labelText) { return false; }
  if (this.field.val() == '') { return false; }
  return true;
}
*/

ClientState = function()
{
  this.setValue = function(name, val)
  {
    if (typeof(form.elements[name]) != "undefined" && name.indexOf("[]") < 0) {
      form.elements[name].value = val;
    }
    else {
      var input = document.createElement("INPUT");
      input.type = "hidden";
      input.name = name;
      input.value = val;
      form.appendChild(input);
    }
  };

  this.unsetValue = function(name, val)
  {
    if (typeof(form.elements[name]) != "undefined") {
      if (form.elements[name] instanceof NodeList) {
        var list = form.elements[name];
        for (i = 0; i < list.length; i++) {
          if (list.item(i).value == val) {
            form.removeChild(list.item(i));
          }
        }
      }
      else {
        form.removeChild(form.elements[name]);
      }
    }
  };

  this.hasValue = function(name, val)
  {
    if (typeof(form.elements[name]) != "undefined") {
      if (form.elements[name] instanceof NodeList) {
        var list = form.elements[name];
        for (i = 0; i < list.length; i++) {
          if (list.item(i).value == val) {
            return true;
          }
        }
      }
      else {
        if (form.elements[name].value == val) {
          return true;
        }
      }
    }
    return false;
  };

  this.getValue = function(name)
  {
    if (typeof(form.elements[name]) == "undefined") {
      return false;
    }
    return form.elements[name].value;
  };

  this.numValues = function()
  {
    return form.elements.length;
  };

  this.send = function(receiverUrl, completedCallback)
  {
    this.completedCallback = completedCallback;
    YAHOO.util.Connect.setForm(form); 
    var callback = {
      success: function(o) { this_obj.processResponse(o); },
      failure: function(o) { this_obj.processError(o); }
    };
    YAHOO.util.Connect.asyncRequest('POST', receiverUrl, callback);
  };

  this.processError = function(o)
  {
    console.error("ClientState HTTP Error", o);
    this.clear();
    this.doCompletedCallback();
  };

  this.processResponse = function(o)
  {
    if (o.responseText) {
      var response = eval('(' + o.responseText + ')');
      if (response.status == 'success') {
        if (typeof response['eval'] != "undefined") {
          eval(response['eval']);
        }
      }
      else {
        console.error("ClientState Form Error", o);
      }
    }
    this.clear();
    this.doCompletedCallback();
  };

  this.doCompletedCallback = function()
  {
    if (typeof this.completedCallback == "function") {
      this.completedCallback();
    }
  }

  this.clear = function()
  {
    var body = document.getElementsByTagName("body")[0];
    if (form) {
      body.removeChild(form);
    }
    form = document.createElement("FORM");
    body.appendChild(form);
  };

  var form = null;
  var this_obj = this; // for closures

  // initialize
  this.clear();
};

if (dipity.curr_login !== "" && 
    window.opener && 
    typeof(window.opener.dipity) != "undefined" && 
    window.opener.dipity.curr_login === "") 
{
  window.opener.location.reload(false);
}

// queued update stuffff
function pollQueuedUpdate()
{
  var callback = { 
    success:checkQueuedUpdate,
    failure:function() {}
  };
  YAHOO.util.Connect.asyncRequest('GET', dipity.base_url + "/check_timeline_update_time?tidarr=" + dipity.tid + "&from_ts=" + dipity.request_time, callback);
}
function checkQueuedUpdate(d)
{
  var o = eval("(" + d.responseText + ")");
  if (typeof(o.status) != 'undefined') {
    if (o.status === 0) {
      setTimeout(pollQueuedUpdate, 5000);
      return;
    } 
    var spinner_elem = document.getElementById('queued_update_spinner');
    if (spinner_elem) {
      spinner_elem.style.display = 'none';
    }
    tl.refresh();
  }
}

