// Place your application-specific JavaScript functions and classes here
//  This file is automatically included by javascript_include_tag :defaults

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled, 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') = '1');
  }
};

if(!Cookie.get('tzoffset')) {
	Cookie.set('tzoffset', (new Date()).getTimezoneOffset() * 60);
}


function hideEmbeds() {
	if ($$('.embed-mask').length == 0) {
		var objects = (navigator.appName.indexOf("Microsoft") > -1) ? $$('object') : $$('embed');
		var body = $$('body')[0];

		for (var i = 0; i < objects.length; i++) {
			var object = objects[i];
			
			// obviously, we don't want to hide flash players inside the window
			if (!Element.descendantOf(object, $("window_id"))) {
				var position = Position.cumulativeOffset(object);
		
				// insert the mask just after the embed object to "replate" it
				var style = "top: " + position[1] + "px; left: " + position[0] + "px; width: " + object.getWidth() + "px; height: " + object.getHeight() + "px;";						
				new Insertion.Top(body, "<div class='embed-mask' style='" + style + "'></div>");	
			
				// hide embed object			
				object.setStyle({ visibility: 'hidden' });
			}
		}
	}
}

function showEmbeds() {
	var objects = (navigator.appName.indexOf("Microsoft") > -1) ? $$('object') : $$('embed');

	for (var i = 0; i < objects.length; i++) {
		var object = objects[i];
		
		if (!Element.descendantOf(object, $("window_id"))) {
			// show object
			object.setStyle({ visibility: 'visible' });
		}
	}
	
	// we don't need masks anymore
	$$('.embed-mask').each(function(embed) { embed.remove(); });
}

function quickWindow(html, width, height, updateWidth, updateHeight, window_id) {
	if (!window_id) window_id = 'window_id';

    var pos = Position.positionedOffset($('lightbox'));
    var top = (pos[1] - height - 35);
    var left = Math.round((1000 - width) / 2);

	options = {
		className: "alphacube",
		height: height,
		left: left,
		maximizable: false,
		minimizable: false,
		resizable: false,
		top: top,
		width: width
	};
	win = new Window(window_id, options);

	win.hasEffectLib = false;
	win.updateWidthAfterSetup = updateWidth;
	win.updateHeightAfterSetup = updateHeight;
	win.showFunction = "show";
	win.showModal = true;
    win.getContent().innerHTML = html;
    win[win.showFunction](win.showModal);
	win.setDestroyOnClose();
}

function simpleWindow(url,width, height, updateWidth, updateHeight, window_id) {
	if (!window_id) window_id = 'window_id';
	win = new Window(window_id, {destroyOnClose: true, className: "alphacube", minimizable: false, maximizable: false, width: width, height: height});
	win.setAjaxContent(url,{method: 'get'},false,true);
	win.showCenter();
}

function simpleWindowUpdate(effect) {
	var i = 0;
	var win;
	win = Windows.getWindow(effect.element.id );

	//This loop is only for IE
	for (i=0; i < 100; i++) {
		if (win.updateHeightAfterSetup) win.updateHeight();
		if (win.updateWidthAfterSetup) win.updateWidth();
	}
	win._center();
}

function overlay(url, options, height, width) {
  if(width==null) width=550;
	if (options == null) options = {}
	Dialog.alert({url: url, options: options}, {windowParameters: {className: "alphacube", width: width, height: height, showEffect: Element.show, hideEffect:Element.hide}})
}

function media_preview(url,width, height) {
	Dialog.alert({url: url}, {windowParameters: {className: "alphacube", width: width, height: height}})
}

function popup(url) {
	var modal = new Control.Modal(false, { 	contents: function(){ new Ajax.Request(url, { onComplete: function(request){ modal.update(request.responseText); } }); return ''; },
					         										    containerClassName: 'processing',
  					        										  overlayClassName: 'processing',
	    				        										width: 550,
	    				        										overlayCloseOnClick: true,
	    				        										opacity: 0.25 });
	modal.open();
}

function error(msg) {
    Dialog.alert(msg, {windowParameters: {className: "alphacube", width: 550, showEffect: Element.show, hideEffect:Element.hide}});

}

function addUpload() {
	// if there's an input empty no need to create one
	if ($$('input[type="file"]').pluck('value').indexOf("") == -1 ) {
    new Insertion.Before('upload_last', "<br/><input  name='medium[file_data][]' size='70' type='file'/ onchange='addUpload()''>")
		if (window.oLightBox)
	  	window.oLightBox.SetLightBox();
	}
}

function updatePlayer(request) {
	flashReloadXmlFile('/lightbox/mysession_playlist')
}

// generate uri by concatanating a param
// ex: addParamToUrl('http://www.bla.com',$H({'no_render': 1}))
// will return http://www.bla.com?norender=1
function addParamToUrl(uri,params_hash){
	concatenator = '?'
	if(uri.indexOf('?')>0){
		concatenator = '&';
	}
	return uri.strip()+concatenator+params_hash.toQueryString();
}

// Class to handle tabs: 
Tabs = {
	currentContent: null,

	// link: the <a> caller object 
	// url:  url to call (Ajax) to fill tab in tab content does not exists
	// update_url:  update_url to call (Ajax) to fill tab in tab content exists
	switchTo: function(link, url, update_url, method) {
		// Get parent
		var parent = link.parentNode.parentNode;
		var kids = $(parent).getElementsByClassName("tab");
		var current = $(link.parentNode);
		currentContent = $('content_' + current.id);
		method = typeof method == "undefined" ? "post" : method

		// currentContent exists, show it
		if (currentContent) {
			Tabs.closeTabs(kids);
			currentContent.show();
			current.addClassName("tabselected");
			if (update_url)
			new Ajax.Request(addParamToUrl(update_url,$H({'no_render': 1})), { method: method, onComplete: updatePlayer});
		}
		// Else run Ajax request
		// onSuccess the request hides all tabs and adds tabselected to the new one
		else {
			Tabs.showSpinner(parent.parentNode);
			new Ajax.Request(url, { method: method, onSuccess: function(t) { Tabs.closeTabs(kids); Tabs.showSpinner(parent.parentNode, true); current.addClassName("tabselected"); }});
		}
	},

	//Close all tabs and remove all 'tabselected' classes
	closeTabs: function(kids) {
		$A(kids).each(function(element) {
			$(element).removeClassName("tabselected")
			var content = $('content_' + element.id);
			if (content){
			    content.hide();
			}
		});
	},

	showSpinner: function(parent, hide) {
		var parent = $(parent);
		var overlay = parent.down('div.overlay');			
		var spinner = parent.down('div.spinner');
		var height = parent.down('div.tabcontents').getHeight();
		hide = typeof hide == "undefined" ? false : hide
		
		if (overlay == null)
			return ;
					
		if (hide == false) {
			overlay.setStyle({ height: height + "px" });
			overlay.show();
			spinner.show();
		} else {
			overlay.hide();
			spinner.hide();
		}
	}
}

// Class to handle category: expand/collapse category, multiselection of categories/sub categories
Categories = {
  currenExpandedtId: null, 
  animRunning: false,
  disableRequest: false,
  
  toggle: function(id) {
    if (Categories.animRunning == true)
      return;
    Categories.animRunning = true
      
    // Same id just toggle the current element
    if (id == this.currenExpandedtId) {
      var visible = $('contentof_' + id).visible();
      
      this._toggleCategory(id);
      this.currenExpandedtId = !visible ? id : null;
    }
    // Else close current element and open the new one
    else {
      this._toggleCategory(this.currenExpandedtId);
      this.currenExpandedtId = id
      this._toggleCategory(this.currenExpandedtId, true);
    }
  },
  
  select: function(id) {
    if (this.disableRequest)
      return;
    
    if ($(id).hasClassName('category_selected'))
      $(id).removeClassName('category_selected')
    else
      $(id).addClassName('category_selected')  
      
    // Check if it's a category, to select/unselect subcategories
    if (id.match(/^category/)) {
      var add = $(id).hasClassName('category_selected');  
      $$('div#contentof_' + id + ' li a').each(function(element) {add ? element.addClassName('category_selected') : element.removeClassName('category_selected')})
    }
  },
  
  sendSelection: function(url) {
    if (this.disableRequest)
      return;
    // Collect all selected ids: It selects all <a> included in an ul.category, and creates an array of id (exctracted from <a>'s id)
    var ids = $$("ul.category a.category_selected").inject([], function(array, element) {return array.concat(element.id.match(new RegExp(/\d+/)))});
    if (ids.length == 0)
      alert("Nothing has been selected")
    else {
      this.disableRequest = true;
      var params = "categories[]=" + ids.join("&categories[]=")
      new Ajax.Request(url, {parameters: params});
    }
  },
  
  doubleClick: function(id, url) {
    if (this.disableRequest)
      return;
    
    this.select(id);
    this.sendSelection(url);
  },
  
  setSelection: function(id) {
    var ids = $$("ul.category a.category_selected").inject([], function(array, element) {return array.concat(element.id.match(new RegExp(/\d+/)))});
  	$(id).value = ids.join(',');
  },
  
  deselectAll: function() {
    $$("ul.category a.category_selected").each(function(element) {element.removeClassName('category_selected')})
  },
  
  selectAll: function() {
    $$("ul.category a").each(function(element) {element.addClassName('category_selected')})
  },
  
  _toggleCategory: function(id) {
    if (id != null) {
      var visible = $('contentof_' + id).visible();

      // Start effect
      Effect.toggle($('contentof_' + id), 'blind', {duration: 0.5, afterFinish: Categories._afterFinishAnim, queue: "categories"})
      
      // Update icons
      var image = $('handle_' + id);
      if (visible) 
        image.src = image.src.gsub("minus.gif", "plus.gif");
      else 
        image.src = image.src.gsub("plus.gif", "minus.gif");
    }
  },
  
  _afterFinishAnim: function() {
    Categories.animRunning = false;
  }
}

// Carousel 
CarouselCallback = {
  buttonStateHandler: function (button, enabled) {
    $(button).style.visibility =  enabled ? "visible" : "hidden"
  },
  
  animHandler: function(carouselID, status, direction) {
    var region = $(carouselID).getElementsByClassName('carousel-clip-region')[0]
    
    if (status == "before") {
      Effect.Fade(region, {to: 0.3, queue: { position:'end', scope: "carousel" }, duration: 0.2})
    }
    if (status == "after") {
      Effect.Fade(region, {to: 1, queue: { position:'end', scope: "carousel" }, duration: 0.2})
    }
  },

  // Show/hide "loading" overlay before and after ajax request
  ajaxHandler: function(carousel, status) {
    var overlay = $('overlay_' + carousel.carouselElemID );    
    var className = $(carousel.carouselElemID).hasClassName("carousel_100") ? "carousel_overlay_100" : "carousel_overlay_50"
    
    if (status == "before") {
      if (overlay) {
        overlay.setOpacity(0);
        overlay.show();
        Effect.Fade(overlay, {from: 0, to: 0.8, duration: 0.2})
      }
      else
        new Insertion.Top(carousel.carouselElemID, "<div class='" + className + "' id='overlay_" + carousel.carouselElemID + "' ></div>");
    }
    else 
      Effect.Fade(overlay, {from: 0.8, to: 0.0, duration: 0.2})
  }
}


function getPageSize() {
  var xScroll, yScroll;

  if (window.innerHeight && window.scrollMaxY) {  
    xScroll = document.body.scrollWidth;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }

  var windowWidth, windowHeight;
  if (self.innerHeight) { // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  } 

  // for small pages with total height less then height of the viewport
  pageHeight = Math.max(windowHeight, yScroll);

  // for small pages with total width less then width of the viewport
  pageWidth = Math.max(windowWidth, xScroll);

  return { page: { width: pageWidth, height: pageHeight }, window: { width: windowWidth, height: windowHeight } };
}


function windowForMessage(window_id, contact_id, url) {
    win = new Window(window_id, {className: "alphacube", minimizable: false, maximizable: false, showEffectOptions: {afterSetup: simpleWindowUpdate}, width: '400px', height: '200px'});
    win.setAjaxContent(url,{method: 'get', parameters: 'id=' + contact_id },false,true);
    win.setDestroyOnClose();
}

// Contacts
Contact = {
    addContact: function(contact){
        if (bUserLoggedIn) {
            windowForMessage('add-contact', contact, '/beta/userpage/ask_for_contact_to_be_added');
        }
        else
        {
            Account.login('/me/request_contact/' + contact, null);
        }
    }
}

// Messages
Message = {
    send: function(contact){
        if (bUserLoggedIn) {
            windowForMessage('send-message', contact, '/beta/userpage/send_message_to_contact');
        }
        else
        {
            Account.login(request_url, "send_message:1");
        }
    }
}

SendMediaToFriend = {
    send: function(media) {
        if (bUserLoggedIn) {
            win = new Window('send-media-to-friend', {className: "alphacube", minimizable: false, maximizable: false, showEffectOptions: {afterSetup: simpleWindowUpdate}, width: '400px', height: '250px'});
            win.setAjaxContent('/media/send_media_to_friend',{method: 'get', parameters: 'id=' + media },false,true);
            win.setDestroyOnClose();
        }
        else
        {
            Account.login(request_url, "send_media_to_friend:1");
        }
    }
}



ReadMessage = {
    read: function(id, type, options){
        if (bUserLoggedIn) {
			if (options == null) options = { method: 'get' }
            win = new Window('message', {className: "alphacube", minimizable: false, maximizable: false, showEffectOptions: {afterSetup: simpleWindowUpdate}, width: '500px', height: '300px'});
            win.setAjaxContent('/me/read/'+type+'/'+id, options ,false,true);
            win.setDestroyOnClose();
        }
        else
        {
            Account.login(request_url, "read_message:1");
        }
    }
}



// Permalink
MobilePermalink = {
    show: function(mediaId) {
            win = new Window('permalink', {className: "alphacube", minimizable: false, maximizable: false, showEffectOptions: {afterSetup: simpleWindowUpdate}, width: '400px', height: '100px'});
            win.setAjaxContent('/media/get_mobile_permalink',{parameters: 'id=' + mediaId},false,true);
            win.setDestroyOnClose();
    }
}

WebPermalink = {
    show: function(mediaId) {
            win = new Window('webpermalink', {className: "alphacube", minimizable: false, maximizable: false, showEffectOptions: {afterSetup: simpleWindowUpdate}, width: '400px', height: '100px'});
            win.setAjaxContent('/media/get_web_permalink',{parameters: 'id=' + mediaId},false,true);
            win.setDestroyOnClose();
    }
}


Groups = {
  show: function(media) {
    win = new Window('groups-window', {className: "alphacube", minimizable: false, maximizable: false, showEffectOptions: {afterSetup: simpleWindowUpdate}, width: '400px', height: '420px'});
    win.setAjaxContent('/media/show_groups/'+media,{},false,true);
    win.setDestroyOnClose();
  },
  
  showUpload: function() {
    win = new Window('groups-window', {className: "alphacube", minimizable: false, maximizable: false, showEffectOptions: {afterSetup: simpleWindowUpdate}, width: '400px', height: '420px'});
    win.setAjaxContent('/me/upload/show_groups/',{},false,true);
    win.setDestroyOnClose();
  },

	toggle: function() {
		$('active-group-content').toggle();		
		$('expired-group-content').toggle();
	}
}

// Account
Account = {
    login: function(url, session){
        if (bUserLoggedIn) {
            window.location = url;
        }
        else
        {
			var params = "?";
			if (url)
				params += "url=" + url + "&l=true&"
			if (session)
				params += "session=" + session + "&"
            popup('/beta/account/popup_login' + params);
        }
    }
}

//Function to toggle visibility of an item by clicking on an image which is also updated
//Vars : 
// - image : image element to be updated
// - elementToToggle : Element to be toggled
// - imagePlus : name of image when hidden
// - imageMinus : name of image when visible
function toggleFromImage(image, elementToToggle, imagePlus, imageMinus){
	if (elementToToggle != null && image != null) {
	  var visible = $(elementToToggle).visible();

	  // Toggle Item
	  Element.toggle(elementToToggle);
	  
	  // Update icons
	  if (visible)
		image.src = image.src.gsub(imageMinus, imagePlus);
	  else 
		image.src = image.src.gsub(imagePlus, imageMinus);
	}
}

//Function to toggle the class of an element
//Vars :
// - element_id : element to affect
// - class1 & class2 : classes to toggle
function toggleClass(element_id, class1, class2){
	if (e = $(element_id))
		e.className = (e.className == class1) ? class2 : class1;
}

//Function specific to the pods and categories eyeka helper
//It checks for each pod if it should be highlighted(selected) then it closes
//every categories, show the ones corresponding to the current pod and highlight
//it.
function pod_click(pod, vt_id, pod_div, checkbox_prefix, category_div, category_prefix, class_neutral, class_selected, class_current){

	var cat_id;

	$A($(pod_div).childNodes).each(
		function(child){
			if(child.id){
				cat_id = (child.id).split("_")[1];
				if($(checkbox_prefix + cat_id).checked == true){
					child.setAttribute("class", class_selected);
				}
				else{
					child.setAttribute("class", class_neutral);
					$A($(category_prefix + cat_id).childNodes).each(
						function(cat){
							if(cat.id){
								if(cat.checked == true){
									child.setAttribute("class", class_selected);
								}
							}
						}
					)
				}
			}
		}
	);
	
	$A($(category_div).childNodes).each(
		function(child){
			if(child.id)
				Element.hide(child.id);
		}
	);
	
	Element.show($(category_prefix + vt_id));
	
	pod.setAttribute("class", class_current);
	
}


function loginMessage(check, login, elementId) {
    // retrieve the login on the textfield
    var logins = $A($(elementId).value.split(','));
 
    var newLogin = logins.collect(function(el) {
        return el.gsub(/  */, '');
    });
    
    var newLogin = newLogin.reject(function(el) {
        return el == login
    });
    
    
    if(check.checked) {
        newLogin.push(login);
    }
    
    if($(elementId).value != '') {
        $(elementId).value = newLogin.join(',')
    } else {
        $(elementId).value = login;
    }
}

/* On upload page */
//select the corresponding limit listbox value
function setLimitCounter(count){
	if (count == 'Nb per page'){
  	$('items_5').selected=true;                    
	} else {
		$('items_'+count).selected=true;                    
	}
}

//MULTIPLE SELECTS
//This provide function to create a multiple select.
//
//A multiple select consists of three parts:
// - summary: a text input which displays the list of the selected options.
// - choices: starting hidden, 'choices' appear when clicking on 'summary'.
//            'choices' is a list (ul) containing checkboxes. When clicking
//            these checkboxes, summary is updated. For display reasons
//            (overlaping, position) 'choices' is a child of the document body.
// - values:  as 'choices' is attached to body, it does not appear when
//            submiting a form. To fix this, hidden fields are stored where the
//            summary is. They are updated when clicking on any checkbox of
//            'choices'.
//
//TODO: 
// - remove function is not complete.
// - there is still a bug on firefox when the multiple select is child of a
//   javascript window that is being closed.
// - multiple select still suffers from the overlapping comboboxes in IE6.
// - still some minor css glitches in IE.
var MultipleSelects = {

    multipleselects: [],

    remove: function(element) {
    //Remove multiple select from the page
    //Not complete, must remove observer and hidden fields
        var choices = $(element + '_choices');
        if(choices)
            Element.remove(choices);

        var summary = $(element + '_summary');
        if(summary)
            Element.remove(summary);
    },
    
    update: function(element){
    //Set content of summary by joining checked input's labels
    //Set values of hidden fields with selected values
    
        //Default value
        var separator = '; ';
        
        var choices = $(element + '_choices');
        var summary = $(element + '_summary');
        
        var content = [];
        var input;
        
        //Getting into LI's
        $A(choices.childNodes).each(
            function(child, child_index){
                input = Element.down(child, 'input');
                if($F(input) != null){
                    //Update summary
                    content.push($(input.id + '_label').innerHTML.unescapeHTML());
                    //Update hidden tag
                    $(input.id.split('_').without('choices').join('_')).value = 1;
                }
                else{
                    //Update hidden tag
                    $(input.id.split('_').without('choices').join('_')).value = 0;
                }
            }
        )
        summary.value = content.join(separator);
    },
    
    add: function(element) {
    //Register the multiple select

        //Remove any multiple select previously registered with the same name
        ///MultipleSelects.remove(element);
        var choices = $(element + '_choices');
        var summary = $(element + '_summary');
        
        choices.hide();

        //Position the choice panel
        //MultipleSelects.position(element);

        //Update summary
        MultipleSelects.update(element);
        
        //Register the multiple select
        MultipleSelects.multipleselects.push(element);
        
        //Observe click outside multiple select
        if(MultipleSelects.multipleselects.length == 1)
            Event.observe(document, 'click', function(e){MultipleSelects.closeAllIfOutside(e)});
        
    },
    
    position: function(element){
    //Position the choice panel select by attaching it to the body, setting top,
    //left, z-index and position styles.
        var choices = $(element + '_choices');
        var summary = $(element + '_summary');
        
        //Must bind it to the body in order to allow multiple select to overlap
        //anything and to be correctly positionned.
        Element.remove(choices);
        document.body.appendChild(choices);

        var pos = Position.cumulativeOffset(summary);

        var left = pos.first();
        var top  = pos.last();
        
        Element.setStyle(choices, {
	 		left:left + "px",
            position:'absolute',
	 		top:top + "px",
	 		'z-index': '150'
	 	});                

    },
    
    clear: function(element){
        
        var choices = $(element + '_choices');
        var summary = $(element + '_summary');
        
        var input;
        
        //Getting into LI's
        $A(choices.childNodes).each(
            function(child, child_index){
                input = Element.down(child, 'input');

                input.checked = '';
                $(input.id.split('_').without('choices').join('_')).value = 0;

            }
        )     
        summary.value = '';
    },
    
    closeAllIfOutside: function(event){
    //Close each multiple select if the event is outside its bounds.
        MultipleSelects.multipleselects.each(
            function(ms, index){
                var choices = $(ms + '_choices');
                var summary = $(ms + '_summary');
                
                if (summary){
                //The multiple select still exists
                    if(choices && !Position.within(choices, Event.pointerX(event), Event.pointerY(event)) && !Position.within(summary, Event.pointerX(event), Event.pointerY(event))){
                    //Event is not in bound of summary or choices
                        choices.hide();
                    }
                }
                else{
                //The multiple select doesn't exists anymore, delete it
                    MultipleSelects.remove(ms);
                }
            }
        )
    }
 }
 
/* Search results page */
function processNewSort(originalRequest){
	res = eval(originalRequest.responseText);
  init_vignbnk(res[0].last());
  flashReloadXmlFile(res[0].first());
	url_search = res[1];
	searchResultsDisplays['search'].goToFirst();
}

function ajaxCall(link){
	new Ajax.Request(link, {method: 'get', onComplete: processNewSort});
}

/*
	This class handles most of search results page behavior (including the group/contributions tabs + pagination behavior)
*/
searchResultsDisplays = {};

var SearchResultsDisplay = Class.create();
SearchResultsDisplay.prototype = {
	//Constructor
	initialize: function(name, urls, counts) {
		this.tabs = $(name+'_tabs');
		this.pagination = $(name + '_pagination');
		this.goToFirstLink = $(this.pageLinkId('first'));
		this.goToLastLink = $(this.pageLinkId('last'));
		this.urls = urls;
		this.counts = counts;
		this.options = Object.extend({
			pageRange: 3, //Number of pages displayed before and after current page
			startPage: 1, //Highlight this page by default in pagination
			nbPerPage: 100, //Nb results per page
			responseType: 0,
			startMode: 1,
			sizes: null //Array of sizes the vign_bnk must use for each mode
			//responseType: 0 //Use 1 when on search results pages
		}, arguments[3] || {});

		this.currentPage = this.options.startPage;
		//this.currentMode = this.options.startMode;
		//url_search = urls[this.currentMode];
		this.synchronize(this.options.startMode);
		
		this.displayPagination();
    
    this.afterHandler = this.goToPageAfterHandler;
    if (this.options.responseType == 1)
      this.afterHandler = this.goToPageAfterHandler1;

		//register
		searchResultsDisplays[name] = this;
	},

	//Destroyer
	destroy: function(){
	},
	
	//
	switchTab: function(index){
    var linkId = this.tabLinkId(index);
    Tabs.closeTabs(this.tabs.getElementsByClassName("tab"));
    $(linkId).addClassName('tabselected');
    this.synchronize(index);
		this.goToPage(1);
	},
	
	// Prepare display && parameters
	synchronize: function(index){
		this.currentMode = index;
		if (this.urls[index-1] != '')
			url_search = this.urls[index-1];
	  
		// resize vignet bank
		if (this.options.sizes != null)
			window.oVignBnk.ReSize(this.options.sizes[this.currentMode-1]);
	}, 

	// Go to a page by updating player, vignetbank and pagination
	goToPage: function(pageNumber){
		this.currentPage = pageNumber;
		var linkId = this.pageLinkId(pageNumber);
		var index = (pageNumber - 1) * this.options.nbPerPage
		new Ajax.Request(url_search + ',offset:' + index, {
	  	method: 'get',
      onComplete: this.afterHandler
		});
		this.displayPagination();
	},

	// go to first page for current mode
	goToFirst: function(){
		this.goToPage(1);
	},

	// go to last page for current mode
	goToLast: function(){
		this.goToPage(this.counts[this.currentMode-1]);
	},

	//
	goToPageAfterHandler: function(originalRequest){
		var res = eval(originalRequest.responseText);
	  init_vignbnk(res.last());
	  flashReloadXmlFile(res.first());
	},

  //
	goToPageAfterHandler1: function(originalRequest){
		var res = eval(originalRequest.responseText);
		res = res[0];
	  init_vignbnk(res.last());
	  flashReloadXmlFile(res.first());
	},

	// Highlight the first page
	resetPagination: function (){
		var tpage = $A(this.pagination.getElementsByTagName('a'));
		tpage.each (function(t) {t.className = "tab";});
		tpage[0].className = "tabselected tab";
	},

	// gives id of a tab link
	tabLinkId: function(index){
		return this.tabs.id + '_' + index;
	},

	// gives id of a pagination link
	pageLinkId: function(index){
		return this.pagination.id + '_' + index;
	},

	// hides unused pagination links (and display a nice pagination)
	// currentPage: the page being displayed
	// maxPage: the last page to display
	// pageRange: number of page to display before and after current page
	displayPagination: function(){
  
		var currentPage = this.currentPage;
		var maxPage = this.counts[this.currentMode-1];
		var pageRange = this.options.pageRange;
		var tpage = $A(this.pagination.getElementsByTagName('a'));

		tpage.each (function(t) {t.className = "tab"; Element.hide(t)});

		if (maxPage > 1){
			this.pagination.show();
			for(i=currentPage-pageRange; i<=currentPage+pageRange; i++){
				if (i >= 1 && i <= maxPage)
					tpage[i].show();
			}
			if(currentPage-pageRange > 1){
				this.goToFirstLink.addClassName('first');
				this.goToFirstLink.show();
			}
			if(currentPage+pageRange < maxPage){
				this.goToLastLink.addClassName('last');
				this.goToLastLink.innerHTML = '...' + maxPage;
				this.goToLastLink.show();
			}
			tpage[currentPage].className = "tabselected tab";
		}
		else{
			this.pagination.hide();
		}
	}
}

// to be used in conjunction with the colorpicker form helper implemented in application.rb
// element_name: the color element
// color: hexa code
// target_name: hidden field to be filled with the color
function set_color_picker(element_name,color,target_name){
	$(element_name).siblings().each(function(node){
		node.removeClassName('cp_selected');
	})
	$(element_name).addClassName('cp_selected');
	$(target_name).value = color;
}

// Helper class for verification field plugin (has_verified_field)

var FieldVerificationManager = Class.create();

FieldVerificationManager.prototype = {
	//Constructor
	initialize: function(field) {
		this.field = field;
		
		this.options = Object.extend({
			sendCodeUrl: '/',
			sendEmailRequestUrl: '/',			
			sendSmsRequestUrl: '/',
			sendEmailandSmsRequestUrl: '/'
		}, arguments[1] || {});
		
		this.submitting = false;	// to avoid double submitting
		this.modalWindow = null;	// reference to the modal window
	},
	
	// Send verification code typed by the user to check its validity
 	sendCode: function() {
		if (this.submitting == false) {
			this.showSpinner();						
			
			// get the input code
			var code = $$('div#' + this.field.gsub('_', '-') + '-verification input#verification_code')[0].value;
							
			this.submitting = true;
					
			new Ajax.Request(this.options.sendCodeUrl, {asynchronous:true, evalScripts:true, method:'post', parameters:'code=' + code})							
		}
	},
	
	// Send verification request by email (1) or SMS (2) or both of them (3)
	sendVerificationRequest: function (type) {
		if (this.submitting == false) {			
			var url = null;
			
			this.showSpinner();						
			
			this.submitting = true;
								
			switch(type) {
				case 1: url = this.options.sendEmailRequestUrl; break;
				case 2: url = this.options.sendSmsRequestUrl; break;
				case 3: url = this.options.sendEmailandSmsRequestUrl; break;
				default: url = this.options.sendEmailRequestUrl;
			}
		
			new Ajax.Request(url, {asynchronous:true, evalScripts:true, method:'post'});
		}
	},
	
	// When the request has been sent, we display a result status message 
	displaySentVerificationMessage: function() {
		this.openModalWindow($(this.field.gsub('_', '-') + "-verification-sent").innerHTML);
	},
	
	// Occurs when the user typed a wrong verification code
	displayWrongCodeMessage: function() {
		this.openModalWindow($(this.field.gsub('_', '-') + "-verification-wrong-code").innerHTML);
	},	
	
	openModalWindow: function(content) {		
		var template = $(this.field.gsub('_', '-') + "-verification-modal-window");
								
		// update the template by the given content
		Element.down(template, "div.content").innerHTML = content;
																								
		if (this.modalWindow == null)
			this.modalWindow = new Control.Modal(false, { contents: function() { return template.innerHTML; },
																										containerClassName: 'processing', 
																										overlayClassName: 'processing', 
																										width: 300,
																										overlayCloseOnClick: false,
																										opacity: 0.25 });  
		else
			this.modalWindow.update(template.innerHTML);
																									
		this.modalWindow.open();			
	},
	
	closeModalWindow: function() {
		this.submitting = false; 
		this.modalWindow.close();
	},
	
	allowSubmitAgain: function() {
		this.submitting = false; 
	},	
	
	showSpinner: function() {
		// hide the status and display the spinner instead
		Element.down($(this.field.gsub('_', '-') + "-status"), 'em').hide();
		$(this.field.gsub('_', '-') + "-verification-spinner").show();
	}, 
	
	hideSpinner: function() {
		// hide the spinner and display the status instead
		$(this.field.gsub('_', '-') + "-verification-spinner").hide();
		Element.down($(this.field.gsub('_', '-') + "-status"), 'em').show();		
	}	
}

var MultiSelect = Class.create();
MultiSelect.prototype = {
  initialize: function(elementsPattern, options) {
    this.elements = $$(elementsPattern);				
    this.options = Object.extend({
      idPattern: /^.*([0-9]*).*$/,
      selectedClassName: "selected",
      matchId: 1,
      hiddenField: null
      }, options || {});
    
    select = this;
    this.elements.each(function(element) {
      Event.observe(element, 'click', select._selectEvent.bindAsEventListener(select));
    });
  },
  
  select: function(element) {
    this._selectElement(element);
  },
  
  selectAll: function() {

    className = this.options.selectedClassName
    this.elements.each(function(el) {
        if(!Element.hasClassName(el, className)) {
        el.addClassName(className);
      }
    });
  },
  
  selectNone: function() {
    className = this.options.selectedClassName;
    this.elements.each(function(el) { Element.removeClassName(el, className); });
  },
  
  _selectEvent: function(event) {
    element = Event.element(event);
    this._selectElement(element);
  },
  
  _selectElement: function(element) {
    var medium_id = "";
    matchId = this.options.matchId;
    just_id = element.id.gsub(this.options.idPattern, function(match){ return match[matchId] });
    
    if(element.id.indexOf('no_crop') == -1) {
      medium_id = 'medium_no_crop_' + just_id;
    } else {
      medium_id = 'medium_crop_' + just_id;
    }
    if(element.hasClassName(this.options.selectedClassName)) {
      element.removeClassName(this.options.selectedClassName);
      if($(medium_id))
        $(medium_id).removeClassName(this.options.selectedClassName);
    } else {
      element.addClassName(this.options.selectedClassName);
      if($(medium_id))
        $(medium_id).addClassName(this.options.selectedClassName);
    }
  },
  
  serialize: function() {
    className         = this.options.selectedClassName;
    selectedElements 	= this.elements.findAll(function(element) { return Element.hasClassName(element, className); });
    pattern           = this.options.idPattern;
    matchId           = this.options.matchId;
    ids               = selectedElements.pluck('id').map(function(el) { return el.gsub(pattern, function(match){ return match[matchId] })});

    if(this.options.hiddenField){
      $(this.options.hiddenField).value = ids.join(',');
    }
    else{
      return(ids.join(','));
    }
  }
};




// Gallery
//var GalleryViewMode = Class.create();
//GalleryViewMode.prototype = {
//	initialize: function(viewModes, defaultViewMode, options) {
//		this.viewModes 				= viewModes;
//		this.currentViewMode 	= defaultViewMode;
//		this.options = Object.extend({
//			galleryTabPattern: ".gallery-tabs img"
//		}, options || {});
//	},
//	
//	changeViewMode: function(viewMode) {
//		// if the last view mode is the same than viewMode param
//		if(this.currentViewMode == viewMode)
//			return false;
//		
//		if(this.currentViewMode) {
//			$('view-mode-'+this.currentViewMode).src = $('view-mode-'+this.currentViewMode).src.gsub('_on.gif', '_off.gif');
//			$('view-content-'+this.currentViewMode).hide();
//		}
//			
//		$('view-mode-'+viewMode).src = $('view-mode-'+viewMode).src.gsub('_off.gif', '_on.gif');
//		$('view-content-'+viewMode).show();
//		
//		// Update pagination links to keep the right view mode
//		var vmode = this;
//		$$('.pagination a').each(function(link) {
//			link.href = vmode.changeViewModeInUrl(link.href, viewMode);
//		});
//		
//		// Store the last view mode
//		this.currentViewMode = viewMode;
//	},
//
//	changeViewModeInUrl: function(url, viewMode) {
//		params 			 			= $H(url.toQueryParams());
//		params.view_mode 	= viewMode;
//		return url.gsub(/(.*)\?.*/, function(match) { return match[1] + '?' + params.toQueryString()});
//	}
//}


// Gallery
var GalleryViewMode = Class.create();
GalleryViewMode.prototype = {
	initialize: function(viewModes, defaultViewMode, options) {
		this.viewModes 				= viewModes;
		this.currentViewMode 	= defaultViewMode;
		this.options = Object.extend({
			galleryTabPattern: ".gallery-tabs img"
		}, options || {});
	},

	changeViewMode: function(viewMode) {
		// if the last view mode is the same than viewMode param
		if(this.currentViewMode == viewMode)
			return false;

		if(this.currentViewMode) {
			$('view-mode-'+this.currentViewMode).src = $('view-mode-'+this.currentViewMode).src.gsub('_on.gif', '_off.gif');
			$('view-content-'+this.currentViewMode).hide();
		}

		$('view-mode-'+viewMode).src = $('view-mode-'+viewMode).src.gsub('_off.gif', '_on.gif');
		$('view-content-'+viewMode).show();

		if($('view_mode')) { $('view_mode').value = viewMode }
		
		// Update pagination links to keep the right view mode
		var vmode = this;
		$$('.pagination a').each(function(link) {
			link.href = vmode.changeViewModeInUrl(link.href, viewMode);
		});

		// Store the last view mode
		this.currentViewMode = viewMode;
		
		// Hide all active micro player
		this.hideMicroPlayer();
	},
	
	hideMicroPlayer: function() {
		mp = $$('embed');
		//mp.each(function(m) {alert('flash vars : '+m.readAttribute('FlashVars').gsub)});
		
	},

	changeViewModeInUrl: function(url, viewMode) {
		params 			 			= $H(url.toQueryParams());
		params.view_mode = viewMode;
		res = url.gsub(/(.*)\?.*/, function(match) { return match[1] + '?' + params.toQueryString()});
		return res;
	}
}

// MicroPlayer
Microplayer = {
	start: function(ContentIdToReplace, imagePath, videoPath, options1) {
		linkURL = '';
		
		// Use Default options
		options = $H({width: 100, height: 100, streamCloseTime: 3, lineColor: ''}).merge(options1);
		
		
		// SWFObject 2
		/*
		var flashvars = {
		  videoURL: videoPath,
		  imageURL: imagePath,
		  linkURL: linkURL,
			lineColor: options.lineColor,
			streamCloseTime: options.streamCloseTime
		};
		
		var params = {
		  menu: "true",
			quality: 'high',
			allowScriptAccess: 'sameDomain',
			scale: 'noscale'
		};
		var attributes = {
		  id: ContentIdToReplace + "-movie"
		};

		swfobject.embedSWF("/micro_player_v0.3.swf", ContentIdToReplace, options.width, options.height, "9.0.0","expressInstall.swf", flashvars, params, attributes);
		*/


		//var div = $(ContentIdToReplace);
		//$A(div.getElementsByTagName('img')).each(function(element) {
		//	element.remove();	
		//});
		
		
		
		var so = new SWFObject("/micro_player_v0.3.swf", ContentIdToReplace + "-movie", options.width, options.height, "9", "#ffffff", "hight");
   	so.addParam("menu", 'true');
   	so.addParam("allowScriptAccess", 'sameDomain');
   	so.addParam("scale", 'noscale');
	 	so.addVariable("videoURL", videoPath);
	 	so.addVariable("imageURL", imagePath);
	 	so.addVariable("linkURL", linkURL);
	 	so.addVariable("lineColor", options.lineColor);
	 	so.addVariable("streamCloseTime", options.streamCloseTime);
		
		var div = $(ContentIdToReplace);
		$A(div.getElementsByTagName('img')).each(function(element) {
			element.remove();	
		});
		new Insertion.Top(div, so.getSWFHTML());
		alert('contenu : '+so.getSWFHTML());
		
		
		
   	//so.addParam("flashvars", "videoURL=" + videoPath + "&imageURL=" + imagePath + "&linkURL=" + linkURL + "&lineColor=" + options.lineColor + "&streamCloseTime=" + options.streamCloseTime);		
		//html = 	"<div><object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='" + options.width + "' height='" + options.height + "'>";
   	//html += "<param name='movie' value='/micro_player_v0.3.swf' />";
   	//html += "<param name='bgcolor' value='#ffffff' />";
   	//html += "<param name='quality' value='high' />";
   	//html += "<param name='menu' value='true' />";
   	//html += "<param name='allowScriptAccess' value='sameDomain' />";
   	//html += "<param name='scale' value='noscale' />";
   	//html += "<param name='flashvars' value='videoURL=" + videoPath + "&imageURL=" + imagePath + "&linkURL=" + linkURL + "&lineColor=" + options.lineColor + "&streamCloseTime=" + options.streamCloseTime + "' />";
   	//html += "<embed src='/micro_player_v0.3.swf' quality=high bgcolor=#FFFFFF WIDTH='" + options.width + "' HEIGHT='" + options.height + "' FlashVars='videoURL=" + videoPath + "&imageURL=" + imagePath + "&linkURL=" + options.linkURL + "&lineColor=" + options.lineColor + "&streamCloseTime=" + options.streamCloseTime + "' TYPE='application/x-shockwave-flash' PLUGINSPAGE='http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash'></embed>";
   	//html += "</object></div>";

	}
};

// Abuse motives selector (flag content as illicit)
var AbuseMotivesSelector = Class.create();
AbuseMotivesSelector.prototype = {
	initialize: function(url) {
		this.url = url;
		this.modalWindow =  new Control.Modal(false, { 	contents: function() { return $('abuse-motives').innerHTML; },
			containerClassName: 'processing', 
			overlayClassName: 'processing', 
			width: 300,
			overlayCloseOnClick: false,
			opacity: 0.25 });
			
		this.submitting = false;	
	},
	
	choose: function(mask, email, comment) {
		this.modalWindow.update($('abuse-motives').innerHTML);
		this.modalWindow.open();
		this.submitting = false;	
		
		if (mask != null) {
			var index = 0;
			$$('#modal_container ul.abuse-motives-list input').each(function(input) {
				input.checked = (mask[index] == "1")
				index++;
			});										
		}

		if (email != null && email.length > 0)
			$$('#modal_container p.email-for-abuse-motive input')[0].value = email;

		if (comment != null) 
			$$('#modal_container p.comment-for-abuse-motive textarea')[0].value = comment;
	},
	
	send: function() {
		if (this.submitting == false) {
			// first protection to avoid the double submit
			this.submitting = true;
			
			new Ajax.Request(this.url, { 
				asynchronous:true, 
				evalScripts:true, 
				method:'post', 
				parameters:'motives=' + this.getMotives() + '&email=' + this.getEmail() + '&comment=' + this.getComment()
			});
			
			this.modalWindow.update($('info-message').innerHTML);					
		}
	},
	
	thank: function() {
		this.modalWindow.update($('thanks-message').innerHTML);
	},
	
	close: function() {
		this.submitting = false;
		this.modalWindow.close();
	},
		
	getMotives: function() {
		var value = "";
		$$('#modal_container ul.abuse-motives-list input').each(function(input) {
			value += input.checked ? "1" : "0";
		});					
		return value;
	},
	
	getEmail: function() {
		var input = $$('#modal_container p.email-for-abuse-motive input')[0];
		return input ? input.value : "";
	},
	
	getComment: function() {
		var input = $$('#modal_container p.comment-for-abuse-motive textarea')[0];
		return input ? input.value : "";
	}
}

