
if(typeof Ajax == 'undefined')
  throw("helper.js requires including prototype.js library");

var RemoteUpdate = { }
RemoteUpdate.Base = Class.create({
  baseInitialize: function(object, action, item, options) {
    element          = $(object+"-"+action+"-"+item);
	this.object 	 = object;
    this.action 	 = action;
	this.element     = element; 
    this.update      = $('visibility'+'-'+object+'-'+item);  
    this.hasFocus    = false; 
    this.changed     = false; 
    this.active      = false; 
    this.index       = 0;     
    this.entryCount  = 0;
	this.remobject  = $('tr_'+this.object+"_"+item);
    if(this.setOptions)
      this.setOptions(options);
    else
      this.options = options || { };

    this.options.paramName    = this.options.paramName || this.element.id;
    this.options.tokens       = this.options.tokens || [];
    this.options.frequency    = this.options.frequency || 0.4;

    this.observer = null;

    Event.observe(this.element, 'click', this.onClick.bindAsEventListener(this));
 },

  hide: function() {
    this.stopIndicator();
    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
    if(this.iefix) Element.hide(this.iefix);
  },

  startIndicator: function() {
    this.element.src = "/images/spinning-wait-icons/wait20trans.gif";
  },

  stopIndicator: function() {
    if(this.options.indicator) Element.hide(this.options.indicator);
  }

});

Ajax.RemoteUpdate = Class.create(RemoteUpdate.Base, {
  initialize: function(object, action, item,  options) {
    this.baseInitialize(object, action, item, options);
    
	this.options.asynchronous  = true;
	this.options.evalScripts   = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
	this.options.defaultParams += '&ajax=true';	
    this.url                   = '/'+object+'/'+action+'/'+item;
  },

  onClick: function() {
    this.startIndicator();

    if(this.options.defaultParams) 
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Updater(this.update, this.url, this.options);
  },

  onComplete: function(request) {
	if (this.action == 'remove')
    	this.remobject.remove();
	else
		this.updateChoices(request.responseText);
  }
});


var MoveElement = { }
MoveElement.Base = Class.create({
  baseInitialize: function(object, id, source, destination, options) {
	temp_item = $('temp_tr_'+object+"-"+id);
	target_id = 'tr_'+object+"-"+id; 
	target = $(target_id);
	
	this.object = options.object || object;
	this.options = options;
	this.destination = destination;
	this.source = source;
	this.setSourceDestination();
	//Check to see if target_id already exists, if it does delete temp_item and exit;	
	if (target)
	{
		temp_item.remove();
		return;
	}
	
	
	this.target = temp_item;
	this.target.id = target_id;
	

	this.button_left = new Element('td', {'id':'not_in_'+object+"_"+id });
	temp= new Element('input', { 'type':'image', 'src':'/images/skins/default/arrow_left.png', 'class': 'in' });
	this.button_left.appendChild(temp);
	this.button_right = new Element('td', {'id':'in_'+object+"_"+id});
	temp = new Element('input', { 'type':'image', 'src':'/images/skins/default/arrow_right.png', 'class': 'not_in' });
	this.button_right.appendChild(temp);
	
	

    this.observer = null;
	
    Event.observe(this.button_left, 'click', this.onClick.bindAsEventListener(this));
    Event.observe(this.button_right, 'click', this.onClick.bindAsEventListener(this));
	
	temp = this.target.remove();
	this.addArrow(temp, this.destination);
	this.from.appendChild(temp);
	temp.show();

 	},
	
	setSourceDestination: function() {
		if (this.options.object)
		{
			testval = this.options.object+"-"+this.source+"_bucket";
	
			this.from = $(this.options.object+"-"+this.source+"_bucket");	
			this.to = $(this.options.object+"-"+this.destination+"_bucket");	
		}	    
		else
		{
			this.to      	= $(object+"-"+this.destination+"_bucket");  
		    this.from       = $(object+"-"+this.source+"_bucket");  		
		}
	},
	
  addArrow: function(row, destination) {
	if (destination == 'in')
	{
		row.insert({ bottom: this.button_right });
	}
	else
	{
		row.insert({ top: this.button_left });
	}
  },
	
	removeArrow: function( row ) {
		if (this.destination == 'in')
		{
			row.removeChild(this.button_right);
		}
		else
		{
			row.removeChild(this.button_left);
		}
	},

  hide: function() {
    this.stopIndicator();
    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
    if(this.iefix) Element.hide(this.iefix);
  },

  startIndicator: function() {
    this.button_left.src = "/images/spinning-wait-icons/wait20trans.gif";
    this.button_right.src = "/images/spinning-wait-icons/wait20trans.gif";
  },

  stopIndicator: function() {
    this.button_left.src ='/images/skins/default/arrow_left.png';
    this.button_right.src = '/images/skins/default/arrow_right.png';
  },

  move_item: function () {
	tempobject = this.target.remove();
	this.removeArrow(tempobject);
	this.addArrow(tempobject, this.source);
	this.to.appendChild(tempobject);
	if (this.destination == "in")
		$(this.object+"_bucket").scrollTop = $(this.object+"_bucket").scrollHeight;
	else
		$(this.object+"_list").scrollTop = $(this.object+"_list").scrollHeight;
	tempdest = this.destination;
	this.destination = this.source;
	this.source = tempdest;
	this.setSourceDestination();	
	
	},
	
  onClick: function() {
	this.move_item();
  }
	
});

MoveItem = Class.create(MoveElement.Base, {
  initialize: function(object, id, source, destination,  options) {
    this.baseInitialize(object, id, source, destination, options);
 }
});

function moveAll( object, location)
{
	target = $(object+'-'+location+'_bucket');
	
	$A(target.getElementsByClassName(location)).each(
		function(item){
			if(item.visible()) 
			item.click();		
		});
 }



var Bucket = {
  SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
  
  Buckets: { },
  
  _findRootElement: function(element) {
    while (element.tagName.toUpperCase() != "BODY") {  
      if(element.id && Bucket.Buckets[element.id]) return element;
      element = element.parentNode;
    }
  },

  options: function(element) {
    element = Bucket._findRootElement($(element));
    if(!element) return;
    return Bucket.Buckets[element.id];
  },
  
  destroy: function(element){
    var s = Bucket.options(element);
    
    if(s) {      
      delete Bucket.Buckets[s.element.id];
    }
  },

  create: function(element) {
    element = $(element);
    var options = Object.extend({ 
      element:     element,
      tag:         'tr',       // assumes li children, override with tag: 'tagname'
      dropOnEmpty: false,
      tree:        false,
      treeTag:     'table',
      overlap:     'vertical', // one of 'vertical', 'horizontal'
      constraint:  'vertical', // one of 'vertical', 'horizontal', false
      containment: element,    // also takes array of elements (or id's); or false
      handle:      false,      // or a CSS class
      only:        false,
      delay:       0,
      hoverclass:  null,
      ghosting:    false,
      quiet:       false, 
      scroll:      false,
      scrollSensitivity: 20,
      scrollSpeed: 15,
      format:      Bucket.SERIALIZE_RULE,
      
      // these take arrays of elements or ids and can be 
      // used for better initialization performance
      elements:    false,
      handles:     false,
      
      onChange:    Prototype.emptyFunction,
      onUpdate:    Prototype.emptyFunction
    }, arguments[1] || { });
	
    // clear any old Bucket with same element
	Bucket.destroy(element);
	(options.elements || Bucket.findElements(element, options) || []).each( function(e,i) {
	  var handle = options.handles ? $(options.handles[i]) :
	    (options.handle ? $(e).select('.' + options.handle)[0] : e);  
	});
    // fix for gecko engine
    Element.cleanWhitespace(element); 


    // keep reference
    Bucket.Buckets[element.id] = options;
  },

  // return all suitable-for-Bucket elements in a guaranteed order
  findElements: function(element, options) {
    return Element.findChildren(
      element, options.only, options.tree ? true : false, options.tag);
  },


  /* Construct a [i] index for a particular node */
  _constructIndex: function(node) {
    var index = '';
    do {
      if (node.id) index = '[' + node.position + ']' + index;
    } while ((node = node.parent) != null);
    return index;
  },

  sequence: function(element) {
    element = $(element);
    var options = Object.extend(this.options(element), arguments[1] || { });
    
    return $(this.findElements(element, options) || []).map( function(item) {
      return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
    });
  },

  setSequence: function(element, new_sequence) {
    element = $(element);
    var options = Object.extend(this.options(element), arguments[2] || { });
    
    var nodeMap = { };
    this.findElements(element, options).each( function(n) {
        if (n.id.match(options.format))
            nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
        n.parentNode.removeChild(n);
    });
   
    new_sequence.each(function(ident) {
      var n = nodeMap[ident];
      if (n) {
        n[1].appendChild(n[0]);
        delete nodeMap[ident];
      }
    });
  },
  

  serialize: function(element) {
    element = $(element);
    var options = Object.extend(Bucket.options(element), arguments[1] || { });
    var name = encodeURIComponent(
      (element.id.indexOf("-")>0 ) ? element.id.split("-")[0] : element.id);
    
    if (options.tree) {
      return Bucket.tree(element, arguments[1]).children.map( function (item) {
        return [name + Bucket._constructIndex(item) + "[id]=" + 
                encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
      }).flatten().join('&');
    } else {
      return Bucket.sequence(element, arguments[1]).map( function(item) {
        return name + "[]=" + encodeURIComponent(item);
      }).join('&');
    }
  },
	
	validate: function(element) {
		element = $(element);
		return (Bucket.sequence(element, arguments[1]).size()>1);
	}
}

function submit_non_ajax(action, object, target)
{
	form = $(object).up('.form');
	form.target=target;
	form.action = action; 
	form.ignore_ajax = true;
	form.submit();
	return true;
}

function submit_ajax(action, object, target)
{
	form = $(object).up('.form');
	form.target='_self';
	form.action = action; 
	form.ignore_ajax = false;
	form.onsubmit();
	return false;
}





function valid_date( entered_date )
{
	myDate = new Date(entered_date);
	if (myDate=='Invalid Date') 
		return false;
	else
		return true;
}
function validate_mail_center(){
	// Make sure they picked a campaign/ecard
	var error = "";
	
	if (!(jQuery('#sequences_id_').val()>0 || jQuery('#campaigns_id_').val()	>0))
	{
		error = "Please Select a Campaign or eCard to send!";
		jQuery('#campaign_header').addClass('entry_error');
	}
	else
	{
		jQuery('#campaign_header').removeClass('entry_error');
	}
	// Make sure they picked a date
	if (!valid_date(jQuery('#start_time').val()))
	{
		error += "<br>Please Select a date to send the eCard/Campaign";
		jQuery('#date_header').addClass('entry_error');
	}
	else
	{
		jQuery('#date_header').removeClass('entry_error');
		
	}
	// make sure they picked someone to send it too. 
	if (!(jQuery('.prospects_ids:checked').length > 0))
	{
		error +="<br> Please Select someone to send it to.";
		jQuery('#prospects_header').addClass('entry_error');
	}
	else
	{
		jQuery('#prospects_header').removeClass('entry_error');
		
	}
	
	if (error.length==0)
	{
		return true;
	}
	else
	{
		show_notifications(error, 'error');
		return false;
	}
}
function adjust_imagemanager_frame() {
	var totalHeight = jQuery('#viewcontainer').height();
	var viewcontainer = jQuery('#viewcontainer');
	var containerWidth = viewcontainer.width() - viewcontainer.css('padding-left'); 
	var filelist = jQuery('#filelist');
	if (filelist.children() && filelist.children().length > 0)
	{
		var imageWidth = filelist.children()[0].width();
		var imagesPerLine = Math.floor(containerWidth/imageWidth);
		var rows = Math.floor(filelist.children().length / imagesPerLine);
		
	}
}
