/**
  * PeerVu - the social decision making
  *
  * Main Javascript file for peervu.com
  *
  */

/* general functions */
function preloader(id) {  $(id).update(new Element('div', {'class':'preloader'}));  }

var Peervu = new Object()

var window_id = null;

Peervu._flash = true
Peervu._id = 'jsflash'
Peervu.token = ''
Peervu.flash = function(message) {
   if (this._flash==false) return
   if (!$(this.jsflash)) return
   var flash_id = this.jsflash
   $(this.jsflash).update(message)
   $(this.jsflash).show()
   new Effect.Highlight(flash_id ,{
     duration:2
   });
   setTimeout(function() {
     new Effect.Fade(flash_id)
   }, 1000)

}

Peervu.Tabs = new Object()
Peervu.Tabs.current = null;
Peervu.Tabs.currentTab = null;
Peervu.Tabs.init = function() {
  $$('.tabber').each(function(item) {
    item.classNames().each(function(cls) {
      var name = cls.substr(0, 9)
      var id = ''
      if (name =='tabbable_' ) {
        id = 'tabbable_'+cls.gsub(name, '')
        item._tab_id = id
        $(id).hide()
      }
      if (cls=='firsttab') {
        Peervu.Tabs.currentTab = $(item._tab_id)
        Peervu.Tabs.current = $(item)
        $(item._tab_id).show()
      }
    });
    Event.observe(item, 'click', function() {
      
      $(this._tab_id).show();
      $(this._tab_id).setOpacity(0)
      $(this._tab_id).appear({duration:0.5});
      if (Peervu.Tabs.currentTab!=null) Peervu.Tabs.currentTab.hide()
      if (Peervu.Tabs.current!=null) Peervu.Tabs.current.src = Peervu.Tabs.current.src.gsub('on.', 'off.');
      this.src = this.src.gsub('off.', 'on.');
      Peervu.Tabs.current = this 
      Peervu.Tabs.currentTab = $(this._tab_id)

    });

  });
}
// Blinds
Peervu.blinds_replacement = 'CLICK FOR LESS PEERVU [-]'

Peervu.initiateBlinds = function() {
  // initiate blinded tabs
  $$('.blind_button').each(function(element) {

    element._target_id =  element.id.replace('button_', '');
    element._original_label = element.innerHTML;
    Event.observe(element, 'click', function() {
      if (this.innerHTML==this._original_label) {
        this.innerHTML = Peervu.blinds_replacement
      } else {
        this.innerHTML = this._original_label;
      }
      Effect.toggle(this._target_id, 'blind');
      return false;
    });
  });
}

// Peervu.Edit
Peervu.Edit = new Object();
Peervu.Edit.Link = new Object();
Peervu.Edit.Link._items = new Array();
Peervu.Edit.Link._template = '';
Peervu.Edit.Link._token = '';
Peervu.Edit.Link._flash = true;

Peervu.Edit.Link.register = function(id, url, name, description, image_url) {
  var item = new Object()
  item.id = id
  item.url = url
  item.name = name
  item.description = description
  item.image_url  = image_url
  this._items[this._items.length] = item
}

Peervu.Edit.Link.init = function() {
  // load template
  new Ajax.Request('/events/addlink', {
    method: 'get',
    parameters:'authenticity_token='+encodeURIComponent(Peervu.Edit.Link._token),
    onSuccess: function(transport) {
      Peervu.Edit.Link._template = transport.responseText
      // launch finishInit as a callback
      Peervu.Edit.Link.finishInit()
    }
  });
}

Peervu.Edit.Link.finishInit = function() {
  // load _items using addLink
  this._flash = false;
  this._items.each(function(item) {
     // load form
     Peervu.Edit.Link.form();
     // fill form
     $('event_links__name').value = item.name
     $('event_links__name').value = item.name
     $('event_links__url').value = item.url
     $('event_links__description').value = item.description
     $('event_links__image_url').value = item.image_url
     // $('product_form_id').insert(new Element('input', { 'name':'event_links[][id]', 'type':'hidden', "value":item.id }))
     // add
     Peervu.Edit.Link.add();
  });
  $('products_preloader').hide()
  $('products').show()
  this._flash = true;
}

Peervu.Edit.Link.cancel = function(link) { 
   if (link.id == 'cancelbutton') {
      $('product_id').remove()
   } else {
      $( link.id.gsub('_cancelbutton', '') ).hide()
   }
   
}

Peervu.Edit.Link.edit   = function(link) {
    // if a add form is open, remove it
    if ($('product_id')) $('product_id').remove()
    $(link).ancestors().each(function(element) {
       if (element.className=='product_info') {
         $( element.id.gsub('preview_', '') ).show()
       }
    });
}

Peervu.Edit.Link.form = function() {
  if ($('product_id')) {
    return
  }
  $('addlink').insert(this._template)
  Peervu.Hint.Init();
  Peervu.Grablet.Clear();
}

Peervu.Edit.Link.flash = function(message) {
   if (this._flash==false) return
   $('addlinkflash').update(message)
   $('addlinkflash').show()
   new Effect.Highlight('addlinkflash',{
     duration:2
   });
   setTimeout(function() {
     new Effect.Fade('addlinkflash')
   }, 1000)
}

Peervu.Edit.Link.check = function() {
   name =  $('event_links__name').value
   price =  $('event_links__price').value
   var errors=[];
   if (name=='' || name=='undefined')
       errors.push("Please enter the name of the item you wish to add");
   if (price!='' && price!='undefined' && !price.match(/^[0-9]+((\.[0-9]{2})?||(,[0-9]{2})?)$/))   ////////VALIDATE NUMERICALITY!!!
      errors.push("Please enter a numerical price or leave it blank");
    if (errors.length > 0){
      if ($('product_id').select('.error') == null) {
        $('add_product').select('.error').first().update(errors.join("<br />")).show('medium');} else {
       $('product_id').select('.error').first().update(errors.join("<br />")).show('medium');}
     return;
    }
    if (errors.length == 0)
       $('add_product_form').submit();
  }
 

Peervu.Edit.Link.add = function() {
   id = ''+$('addedlinks').childElements.length + '_' + new Date().getTime() + '_' + Math.round(1000000*Math.random())
   name =  $('event_links__name').value
   price =  $('event_links__price').value
   var errors=[];
   if (name=='' || name=='undefined')
     errors.push("Please enter the name of the item you wish to add");
   if (price!='' && price!='undefined' && !price.match(/^[0-9]+((\.[0-9]{2})?||(,[0-9]{2})?)$/))   ////////VALIDATE NUMERICALITY!!!
     errors.push("Please enter a numerical price or leave it blank");
   if (errors.length > 0){
     $('product_id').select('.error').first().update(errors.join("<br />")).show('medium');
     return;
   }
 
   $('product_id').setAttribute('id', id)
   $('product_info_id').setAttribute('id', 'product_info_'+id)
   $('product_form_id').setAttribute('id', 'product_form_'+id)
   $('event_links__name').id = id + '_name'
   $('event_links__url').id = id + '_url'
   $('event_links__description').id = id + '_description'
   $('event_links__image_url').id = id + '_image_url'
   $('event_links__image_file').id = id + '_image_file'
   $('addbutton').id = id+'_addbutton'
   $('editbutton').id = id+'_editbutton'
   $('cancelbutton').id = id+'_cancelbutton'

   Peervu.Edit.Link.save(id)
   
   duplicate = new Element('div').update($('product_info_'+id).innerHTML)
   duplicate.setAttribute('id', 'preview_'+id)
   duplicate.className = 'product_info'
   duplicate.setAttribute('class', 'product_info')
   $('addedlinks').insert(duplicate)
   $(id).hide()
   $('linksheader').show()
   this.flash('Link added')
   $("grabletContainer").remove(); // remove grablet from the form
}

Peervu.Edit.Link.update = function(link) {
    link.ancestors().each(function(element) {
       if (element.className=='product_link_add') {
         id = element.id 
         Peervu.Edit.Link.save( id );
         $('preview_'+id).update($('product_info_'+id).innerHTML)
         $(id).hide()
         Peervu.Edit.Link.flash('Link updated')
       }
    });
}


Peervu.Edit.Link.save = function(id) {
   $(id).select('.error').first().hide();
   name_holder =  $(id).select('.product_info .name').first();
   image_holder =  $(id).select('.product_info .image').first();
   name =  $(id+'_name').value
   image =  $(id+'_image_url').value
   if ((!image) || (image==""))
     image = "/images/product-thumbnail.gif" // THUMB DUMMY
   name_holder.innerHTML = name;
   image_holder.update(new Element('img', { 'src': image, 'width':80 }));
   $(id+'_addbutton').hide();
   $(id+'_editbutton').show();
}

Peervu.Edit.Link.remove = function(link) { 
  if (confirm('Are you sure?')) {
    $(link).ancestors().each(function(element) {
       if (element.className=='product_info') {
          $( element.id.gsub('preview_', '') ).remove()
          element.remove()
          Peervu.Edit.Link.flash('Link removed')
       }
    });
  }
}


// Modules
Peervu.Modules = new Object();

// Did you know module
Peervu.Modules.Didyouknow = new Object()
Peervu.Modules.Didyouknow.id = 'didyouknowslider'
Peervu.Modules.Didyouknow.items = 0;
Peervu.Modules.Didyouknow.item_width = 252;
Peervu.Modules.Didyouknow.current = 0;

/**
  * Relocate based on current settings
  */
Peervu.Modules.Didyouknow.relocate = function() {
  obj = document.getElementById(this.id);
  new Effect.MoveBy($(this.id), 0, 0 - this.item_width * this.current, { mode: 'absolute' })
}
/**
  * Move left
  */
Peervu.Modules.Didyouknow.left = function() {
  if (this.current<this.items-1) {
    this.current++;
    this.relocate();
  }
  if (this.current==this.items-1) {
	 $('didyouknow-left').style.visibility = 'visible';
	 $('didyouknow-right').style.visibility = 'hidden';
	 // alert('at last')
  } else {
	 $('didyouknow-left').style.visibility = 'visible';
	 $('didyouknow-right').style.visibility = 'visible';
  }
}
/**
  * Move right
  */
Peervu.Modules.Didyouknow.right = function() {
  if (this.current>0) {
    this.current--;
    this.relocate();
  }
  if (this.current==0) {
	 $('didyouknow-left').style.visibility = 'hidden';
	 $('didyouknow-right').style.visibility = 'visible';
	 // alert('at last')
  } else {
	 $('didyouknow-left').style.visibility = 'visible';
	 $('didyouknow-right').style.visibility = 'visible';
  }
}

// Did you know module
Peervu.Modules.Groupslider = new Object()
Peervu.Modules.Groupslider.id = 'groupslider'
Peervu.Modules.Groupslider.items = 0;
Peervu.Modules.Groupslider.item_width = 408;
Peervu.Modules.Groupslider.current = 0;

/**
  * Relocate based on current settings
  */
Peervu.Modules.Groupslider.relocate = function() {
  obj = document.getElementById(this.id);
  new Effect.MoveBy($(this.id), 0,0 - this.item_width * this.current, { mode: 'absolute' })
}
/**
  * Move left
  */
Peervu.Modules.Groupslider.left = function() {
  if (this.current<this.items-1) {
    this.current++;
    this.relocate();
  }
  if (this.current==this.items-1) {
	 $(this.id + '-left').style.visibility = 'visible';
     $(this.id + '-left1').style.visibility = 'visible';
	 $(this.id + '-right').style.visibility = 'hidden';
     $(this.id + '-right1').style.visibility = 'hidden';
	 // alert('at last')
  } else {
	 $(this.id + '-left').style.visibility = 'visible';
     $(this.id + '-left1').style.visibility = 'visible';
	 $(this.id + '-right').style.visibility = 'visible';
     $(this.id + '-right1').style.visibility = 'visible';
  }
}
/**
  * Move right
  */
Peervu.Modules.Groupslider.right = function() {
  if (this.current>0) {
    this.current--;
    this.relocate();
  }
  if (this.current==0) {
	 $(this.id + '-left').style.visibility = 'hidden';
     $(this.id + '-left1').style.visibility = 'hidden';
	 $(this.id + '-right').style.visibility = 'visible';
     $(this.id + '-right1').style.visibility = 'visible';
	 // alert('at last')
  } else {
	 $(this.id + '-left').style.visibility = 'visible';
     $(this.id + '-left1').style.visibility = 'visible';
	 $(this.id + '-right').style.visibility = 'visible';
     $(this.id + '-right1').style.visibility = 'visible';
  }
}




/* Windows */
Peervu.Windows = new Object()

Peervu.Windows.open = function(options) {
  if (!options.width) options.width = 300
  if (!options.title) options.title = 'Window'
  if (!options.height) options.height = 300
  if (!options.locationx) options.locationx = 300;
  if (!options.locationy) options.locationy = 200;
  // show bg
//  document.body.style.overflow='hidden'


   $(document.body).insert(new Element('div', { 'id':'window_background_pane', 'class':'window_bg' } ))

  window['launchAfter'] = options.launchAfter;

  var win = new Window({
    className: "peervu_win",
    title: options.title,
    width:options.width,
    height:options.height,
    destroyOnClose: true,
    recenterAuto:false,
    draggable:false,
    effectOptions:{duration:1},
    onClose:Peervu.Windows.close
  });
 
  wrappers = $$('.peervu_win_content')
  window_id = wrappers[1].id

  $$('.dialog').first().style.zIndex = 130
  win.getContent().update("");
  if (options.url) {
    win.setAjaxContent(options.url, {method:'get'})
  }

  new Effect.Opacity('window_background_pane', {duration:0, from:0.0, to:0.6,
    afterFinish: function() {
    win.setLocation(options.locationx, options.locationy);
    win.show();
    }
  });
}

Peervu.Windows.close = function() {
 // if ($('window_background_pane')) $('window_background_pane').remove()
  new Effect.Opacity('window_background_pane', {duration:0.5, from:0.6, to:0.0, 
    afterFinish:function() {
      $('window_background_pane').remove();
  //    document.body.style.overflow = 'auto'
    if (window['launchAfter'])
      setTimeout(window['launchAfter'], 10);
    }
  }); 
}

/* jumping select Infopop */

var jsinfopop_id = 'jsinfopop'
Peervu.JSInfopop = new Object();
Peervu.JSInfopop.kill = function() {
  if ($(jsinfopop_id)) { 
    if ($(jsinfopop_id)._request) {
      if ($(jsinfopop_id)._request.transport.readyState!=4) {
        $(jsinfopop_id)._request.transport.abort()
      }
    }
    $(jsinfopop_id)._open = false;
    $(jsinfopop_id)._clicked = false;

    $(jsinfopop_id).style.marginTop = 0
    $(jsinfopop_id).style.marginLeft = 0
    $(jsinfopop_id).hide()
  }
}

Peervu.JSInfopop.init = function() {
 // document.body.innerHTML += '<div id="'+infopop_id+'" style="display:none">&nbsp;</div>'
   $(document.body).insert(new Element('div', { id:jsinfopop_id, style:'display:none;' }).update('&nbsp'))

  $$('.jsinfopop').each(function(item) {
    item.onmouseover = function() {
      $(jsinfopop_id)._facebook = false
      element = item;
      if (item.innerHTML) {
       if (item.firstChild.tagName.toLowerCase() == 'img') {
         element = item.firstChild
       } else {
         element = item.firstChild.firstChild
       }
       $(jsinfopop_id)._facebook = true

      }
      $(jsinfopop_id)._clicked = false;
      $(jsinfopop_id).className = 'jsinfopop_small'
      $(jsinfopop_id).style.marginTop = 0
      $(jsinfopop_id).style.marginLeft = 0

      $(jsinfopop_id).style.visibility = 'hidden'
      $(jsinfopop_id).style.display = 'block'

      $(jsinfopop_id).clonePosition(element)
      $(jsinfopop_id).show()
      $(jsinfopop_id).update(new Element('div', {id: jsinfopop_id + '_image_wrapper' }).update(new Element('img', {id:jsinfopop_id+'_image',src:element.src, title:item.title, style:'position:absolute;top:7px;left:7px;width:'+this.width+'px;height:'+this.height+'px'})))
      $(jsinfopop_id).style.width = $(jsinfopop_id).getWidth() + 10 + 'px'
      $(jsinfopop_id).style.height = $(jsinfopop_id).getHeight() + 10 + 'px'
      loc = $(jsinfopop_id).cumulativeOffset()
      $(jsinfopop_id).style.left = loc.left - 9 + 'px'
      $(jsinfopop_id).style.top = loc.top - 9 + 'px'
      $(jsinfopop_id).style.visibility = 'visible'
    }
  });

  $(jsinfopop_id).onmouseout = function() {
   if (!$(jsinfopop_id)._open) {
      Peervu.JSInfopop.kill()
    }

  }
}

Peervu.JSInfopop.click = function() {
   var obj = $(jsinfopop_id);
   nodetitle = obj.firstChild.firstChild.title.replace("(f)", "");
   if (document.getElementById('peerVuUserSelectAvailable') != null) {
     type = 'peerVuUserSelect'; }
   else if(document.getElementById('peerVuUserReferSelectAvailable') != null) {
     type = 'peerVuUserReferSelect'; }
   else {
     type = 'peerGroupUserSelect';
   }
   window[type].select(nodetitle);
}

/* InfoPop */

var infopop_id = 'infopop'
Peervu.Infopop = new Object();
Peervu.Infopop.Cache = new Object();
Peervu.Infopop.kill = function() {
  if ($(infopop_id)) { 
    if ($(infopop_id)._request) {
      if ($(infopop_id)._request.transport.readyState!=4) {
        $(infopop_id)._request.transport.abort() 
      }
    }
    $(infopop_id)._open = false;
    $(infopop_id)._clicked = false;

    $(infopop_id).style.marginTop = 0
    $(infopop_id).style.marginLeft = 0
    $(infopop_id).hide() 
  }
}
Peervu.Infopop.init = function() {
if (disable_infopops == true) return
 // document.body.innerHTML += '<div id="'+infopop_id+'" style="display:none">&nbsp;</div>'
   $(document.body).insert(new Element('div', { id:infopop_id, style:'display:none' }).update('&nbsp'))

  $(infopop_id).cache = new Object()

  $$('.infopop').each(function(item) {
    item.onmouseover = function() {
      $(infopop_id)._facebook = false
      element = item
      if (item.innerHTML) {
       if (item.firstChild.tagName.toLowerCase() == 'img') {
         element = item.firstChild
       } else {
         element = item.firstChild.firstChild
       }
       $(infopop_id)._facebook = true
      
      }
      $(infopop_id)._open = false;
      $(infopop_id)._clicked = false;
      $(infopop_id).className = 'infopop_small'
      $(infopop_id)._product = false
      if (item.hasClassName('product')) {
         $(infopop_id)._product = true
      }
      $(infopop_id).style.marginTop = 0
      $(infopop_id).style.marginLeft = 0

      $(infopop_id).style.visibility = 'hidden'
      $(infopop_id).style.display = 'block'

      $(infopop_id).clonePosition(element)
      $(infopop_id).show()
      if (element.alt == 'invalid user') {

        $(infopop_id).title = 'Loading from facebook...'
      } else {
        $(infopop_id).title = element.alt
      }
  
      $(infopop_id).url = this.title
      $(infopop_id).update(new Element('div', {id: infopop_id + '_image_wrapper' }).update(new Element('img', {id:infopop_id+'_image',src:element.src, style:'position:absolute;top:7px;left:7px;width:'+this.width+'px;height:'+this.height+'px'})))
      $(infopop_id).style.width = $(infopop_id).getWidth() + 10 + 'px'
      $(infopop_id).style.height = $(infopop_id).getHeight() + 10 + 'px'
      loc = $(infopop_id).cumulativeOffset()
      $(infopop_id).style.left = loc.left - 9 + 'px'
      $(infopop_id).style.top = loc.top - 9 + 'px'
      $(infopop_id).style.visibility = 'visible'
    }
  });

  $(infopop_id).onmouseout = function() {
    // if (!$(infopop_id)._clicked) return
	
    if (!$(infopop_id)._open) {
      Peervu.Infopop.kill()
    }
  }

}

Peervu.Infopop.click = function() {
  var obj = $(infopop_id)
  obj._clicked = true;
  if (obj._open) return
  obj.className = infopop_id+'_open'
  if (obj._product) {
    obj.className += ' ' +infopop_id + '_product_open'
  }

  if (obj._product) {
    $(infopop_id+'_image').style.width = '192px'
  } else {
  $(infopop_id+'_image').style.width = '100px'

  }
  $(infopop_id+'_image').style.height = 'auto'
  $(infopop_id+'_image').style.position = 'static'
  offsets = obj.viewportOffset();
  viewport = document.viewport.getDimensions()

  obj._open    = true;

  $(obj).insert(new Element('p', { id:infopop_id+'_title', style:'' }).update(obj.title))
  $(obj).insert(new Element('p', { id:infopop_id+'_menu_compiled', style:'display:none' }).update(''))
  $(obj).insert(new Element('p', { id:infopop_id+'_close', style:'position:absolute;bottom:0;right:3px;font-size:12px;' }).update(obj.title))
  $(infopop_id+'_close').innerHTML = '<a href="javascript:void(0)" onclick="Peervu.Infopop.kill()">Close</a>'

  $(obj).insert(new Element('div', { id:infopop_id+'_body', 'class':'preloader'}).update('Loading'))

  if (Peervu.Infopop.Cache[obj.url.gsub('/','')]) {
    // read from cache
    var content = Peervu.Infopop.Cache[obj.url.gsub('/','')]
    $(infopop_id+'_body').className = ''
    $(infopop_id+'_body').update(content)
    if ($('infopop_menu')) { 
	   $(infopop_id + '_menu_compiled').update($('infopop_menu').innerHTML) 
	   $(infopop_id + '_menu_compiled').style.display = 'block'
	}
  } else {
    // load from server 
    obj._request = new Ajax.Updater(infopop_id+'_body', obj.url, {  
      parameters:'authenticity_token='+encodeURIComponent(Peervu.token),
      onComplete:function(response) {
        $(infopop_id+'_body').className = ''
        var key = $(infopop_id).url.gsub('/', '')
		if ($('infopop_menu')) { 
			$(infopop_id + '_menu_compiled').update($('infopop_menu').innerHTML) 
			$(infopop_id + '_menu_compiled').style.display = 'block'
		}
        Peervu.Infopop.Cache[''+key] = response.responseText + ''
	    
      }
    });

  }

  if (offsets.top > viewport.height / 2) {
    obj.style.marginTop = $(infopop_id).getHeight() - 300+'px'
  } else {
  }

  if (offsets.left > Math.round(viewport.width/2)) {
	 
    obj.style.marginLeft = $(infopop_id).getWidth() - 300+'px'

  } else {
  }

  if (obj._product) {
    obj.style.width = '450px'
    obj.style.height = '400px'
  } else {
    obj.style.width = '300px'
    obj.style.height = '300px'
  } 
  
}

Event.observe(document, 'click', function() {
  if ($(infopop_id)) {
    if (!$(infopop_id)._clicked) {
      Peervu.Infopop.kill()
    }
    $(infopop_id)._clicked = false;
  }
});


// callbacks when document is ready

Peervu.Startup = function() {
  Tooltip.init();
  Peervu.Infopop.init()
  Peervu.Tabs.init();
  Peervu.Tags.init();
  Peervu.initiateBlinds();
  Peervu.JSInfopop.init();
  Event.observe(infopop_id, 'click', function() {
    Peervu.Infopop.click(); 
  });
  Event.observe(jsinfopop_id, 'click', function() {
    Peervu.JSInfopop.click();
  });
}

Event.observe(window, 'load', Peervu.Startup);

Peervu.Tags = new Object()
Peervu.Tags.collection = new Array()
Peervu.Tags.init = function() {
  if ($('user_tag_list') && $('user_tag_list_render')) {
    $('user_tag_list').hide()
    $('newtag').onkeypress = function(e) { return Peervu.Tags.newTagCallback(e) }
    this.read();
    Event.observe('user_profile_form', 'submit', function() { Peervu.Tags.add() })
  }
}
Peervu.Tags.render = function() {
  html = ''
  this.collection.each(function(item) {
    html += '<div class="topicbox"><div class="topicboxtxt"><strong>'+item+'</strong></div><div class="cell"><a href="javascript:void(0);" onclick="Peervu.Tags.remove(\''+item+'\')"><img src="/images/delete-icon.gif" alt="" /></a></div><div class="clr">&nbsp;</div></div>';
  });
  $('user_tag_list_render').update(html)
}

Peervu.Tags.remove = function(tag) {
  var temp = new Array()
  this.collection.each(function(item) {
    if (item.strip()!='' && item.strip()!= tag) temp.push(item)
  });
  this.collection = temp;
  this.write()
  this.read()
}

Peervu.Tags.sort = function() {
  this.collection = this.collection.sort()
}

Peervu.Tags.write = function() {
  this.sort()
  this.collection.compact()
  $('user_tag_list').value = this.collection.join(',');
  this.render()
}

Peervu.Tags.add = function() {
  if ($('newtag').value == '') return
  this.collection.push($('newtag').value.strip())
  $('newtag').value = ''
  this.write()
}

Peervu.Tags.read = function() {
  this.collection.clear()
  $('user_tag_list').value.split(',').each(function(item) {
    if (item.strip()!='') {
      Peervu.Tags.collection.push(item.strip())
    }
  });
  this.collection = this.collection.compact()
  this.sort()
  this.render()
}

Peervu.Tags.newTagCallback = function(e) {
  if (window.event && window.event.keyCode == 13) {
    Peervu.Tags.add()
    return false
  } else if (e && e.which == 13) {
    Peervu.Tags.add()
    return false;
  }
}

Peervu.updateFlash = function(options) {
  var content = "";
  if (options.notice)
    content += '<div class="flash notice">'+options.notice+'</div>';
  if (options.warning)
    content += '<div class="flash warning">'+options.warning+'</div>';
  Element.update("flash", content);
  var time = 5000; //Default timeout for the message appearance
  if (options.disappear){
    if (typeof(options.disappear) == 'number')
      time = options.disappear;
    setTimeout('Element.update("flash", "")', time);
  }
}

Peervu.Grablet = {
  url: ""
}

Peervu.Grablet.Load = function(urlInputId, delay){
  var urlInput = $(urlInputId);
  if (urlInput && (urlInput.value != this.url||($("grabletContainer").innerHTML==''))) {
    // clear previous Timeout if any
    if (window['grablet_delayed_load_id']){
      clearTimeout(window['grablet_delayed_load_id']);
      window['grablet_delayed_load_id'] = null;
    }
    // setTimeout if the request needs to be delayed
    if (delay) {
      window['grablet_delayed_load_id'] = window.setTimeout('Peervu.Grablet.Load("'+urlInputId+'", null);', 1*delay);
    } else { // or proceed if not
      this.url = urlInput.value;
      if (urlInput.value > '') { //If there is an url load grablet
        Element.update("grabletContainer", '<div class="preloader"></div><p>Loading images from<br />'+this.url+'</p>');
        new Ajax.Request('/grablet/'+this.url.replace('?', '_P_R_M'), {method: 'get'});
      } else {
        Element.update("grabletContainer", '<p>Please enter an url to search for images.</p>');
      }
    }
  }
}

Peervu.Grablet.Clear = function(){
  if (window['grablet_delayed_load_id']){
    clearTimeout(window['grablet_delayed_load_id']);
    window['grablet_delayed_load_id'] = null;
  }
  Peervu.Grablet.url = '';
}

Peervu.Grablet.Init = function() {
  Peervu.Grablet.ShowPage(0);
}

Peervu.Grablet.ShowPage = function(page, perPage){
//  if (perPage)
  //  perPage = 0 + perPage;
//  else
    perPage = 10;
  var from = ((0 + page) * perPage) + 1;
  var to = (1 + page) * perPage;
  $$(".imageContainer").each(function(image) {
  nr = 0+(1*image.id.replace("imageContainer_", ""));
  if  ((nr > to)||(nr < from))
    image.style.display = "none";
  else
    image.style.display = "block";
  })
}

Peervu.Grablet.SetUrl = function(url, sender) {
  if (!window['id_counter'])
    window['id_counter'] = 0;
  partialName = 'imagePartial_'+(++window['id_counter']);
  if ($(partialName))
    $(partialName).remove();
  var imagePartial='<div id="'+ partialName +'" class="grabletPartial"><img src="'+url+'" /><input type="hidden" id="product_new_image_attributes__url" name="product[new_image_attributes][][url]" value="'+url+'"><a href="#" onclick="Element.update(\''+ partialName +'\', \'\')">remove</a></div>';
  if ($("images")){
    new Insertion.Bottom("images", imagePartial);
  }
  if (sender){
    $$('.imageContainer').each(function(item) {item.className = "imageContainer"});
    sender.className = "imageContainer selected";
    var senderImage=$$('#'+sender.id + ' img');
    if (senderImage &&  (senderImage[0]))
      new Effect.Pulsate(senderImage[0], { pulses: 5, duration: 0.5 });
    else
      new Effect.Highlight(sender, { startcolor: '#ffff99', endcolor: '#ffffff' });
//    sender.style.border = "1px #FF0000 solid";
  }
  if ($("event_links__image_url"))
    $("event_links__image_url").value = url;
  if ($("product_image_url"))
    $("product_image_url").value = url;
}

function saveRanking(url) {
	if ($('rank_done_button')) {
		$('rank_done_button').disabled = true
		$('rank_done_button').value = 'Saving...'
	}
	new Ajax.Request(url, {asynchronous:true, evalScripts:true, onComplete:function(request){Windows.closeAll()}, parameters:Sortable.serialize("product_rankings") + '&authenticity_token=' + encodeURIComponent(Peervu.token)})
  }

function format_ranking(ranking) {
  ranking = ranking + ""
  ranking = ranking.toArray()
  last = ranking[ranking.length-1]
  if (last == '1' && ranking[ranking.length-2] == '1') return ranking + 'th'
  if (last == '1') return ranking + 'st'
  if (last == '2') return ranking + 'nd'
  if (last == '3') return ranking + 'rd'
  return ranking + 'th'	
}

function relabel_ranking() {
	var counter = 1;
	$('product_rankings').childElements().each(function(node) {
		node.down().className = 'ranking rank-'+counter
		node.down().update(format_ranking(counter))
		counter++;
	});
}

/******* HINT *******/

Peervu.Hint = new Object();
Peervu.Hint.Init = function() {
  $$('.hint').each(function(item) {
    item.onmouseover = function() {
      $('hint').style.visibility = "hidden";
      $('hint').clonePosition(item, {offsetTop: 25});
      $('hint').innerHTML = '<p>'+item.alt+'</p>';
      $('hint').style.height = ''+($$('#hint p')[0].getHeight())+'px';
      $('hint').style.visibility = "visible";
    }
    item.onmouseout = function() {
      $('hint').style.visibility = "hidden";
    }
  });
}
var FB = {}

function fbml() {
  if (FB.XFBML) { 
    FB.XFBML.Host.parseDomTree()
  }
}



  function preText(obj, pre_text) {
     obj._label = pre_text
     if (obj.value == '') obj.value = pre_text
     obj.onfocus = function() {
        if (this.value == this._label) {
          this.value = ''
        }
     }
     obj.onblur = function() {
        if (this.value == '') {
          this.value = this._label
        }
     }
  }
 
