Element.addMethods({
    appendText: function(element, text)
    {
        text = document.createTextNode(text);
        element.appendChild(text);
        return $(element);
    },
    
    appendChildren: function(element)
    {
        for (var i = 1; i < arguments.length; i++)
            element.appendChild(arguments[i]);
        
        return $(element);
    }
});

function enlarge(id,something)
{

    attr = $(id);
    tr = attr.src;
    $('large_image2').src=tr;
		
}



function clearOnce(input)
{
  if (input.cleared)
    return;
  
  input.value = '';
  input.cleared = true;
}

function SID()
{
    var s = document.cookie;
    var res = s.match('PHPSESSID=(.*?)(;|$)');
    if (res != null && res != '')
    	return res[1]; 
	else
		return false; 
}


var Map = Class.create({
  initialize: function(options)
  {
    options = options || {};
    
    this.domToggleLink = $('quickFilter').down('.hidemap');
    this.domMapContainer = $('flashcontent');
    this.domTopCorners = $('topcorners');
    
    
    try
    {
      if (!this.isHidden())
        this.domToggleLink.update('Hide Map');
      
      
      this.domToggleLink.observe('click', this.toggle.bind(this));
    }
    catch (e)
    {}
    
    if (options.show != false)
    {
      this.show();
    }
    else
    {
      this.hide();
    }  
    
    
  },
  
  isHidden: function()
  {
    try
    {
      if (this.domTopCorners.getStyle('display') == 'block')
        return true;
    }
    catch (e)
    {return false;}
    
    return false;
  },

  show: function()
  {
    try
    {
      this.domMapContainer.style.border = '';
      this.domMapContainer.style.height = '';
      this.domMapContainer.style.display = 'block';

      this.domTopCorners.hide();
      this.domToggleLink.update('Hide Map');
    }
    catch (e)
    {}
  },
  
  hide: function()
  {
    try
    {
      this.domMapContainer.style.border = 'none';
      this.domMapContainer.style.height = '0';
      this.domMapContainer.style.display = 'none';

      this.domTopCorners.show();
      this.domToggleLink.update('Show Map');
    }
    catch (e)
    {}  
  },
  
  toggle: function()
  {
    try
    {
      if (!this.isHidden())
        this.hide();
      else
        this.show();
    }
    catch (e)
    {}      
  }
});




var LoginMenu = Class.create({
  initialize: function()
  {
    this.domContainer = $('topMenu');
    this.domLoginLink  = this.domContainer.down('a[nav=login]');
    this.domSlidingDiv  = this.domContainer.down('.center_bg');
    this.domForm = this.domSlidingDiv.down('form');

    this.domLoginLink.onfocus = function() {this.blur()}
    this.domLoginLink.observe('click', this.loginClick.bindAsEventListener(this));
    this.bodyClickBound = this.bodyClick.bindAsEventListener(this);
    
    this.visible = false;
  },
  
  loginClick: function(event)
  {
    if (this.visible)
      this.hide();
    else
      this.show();
    
    event.stop();
  },
  
  show: function()
  {
    if (this.effect)
      this.effect.cancel();
    this.effect = new Effect.Morph(this.domSlidingDiv, {style: 'height: '+(this.domForm.getHeight()+14)+'px', duration: 0.8});
    
    $(document.body).observe('click', this.bodyClickBound);
    this.visible = true;
  },
  
  hide: function()
  {
    if (this.effect)
      this.effect.cancel();
    this.effect = new Effect.Morph(this.domSlidingDiv, {style: 'height: 5px', duration: 0.8});
    
    this.visible = false;
  },
  
  bodyClick: function(event)
  {
    if (event.element().descendantOf( this.domContainer))
      return;
    
    this.hide();
  }
  
});






Ajax.Request.prototype.evalResponse = function()
{
  if (!this.options.evalContext)
    this.options.evalContext = this;

    try {
      
      toEval = (this.transport.responseText || '').unfilterJSON();
      return function() {eval(toEval)}.bind(this.options.evalContext)();
    } catch (e) {
      this.dispatchException(e);
    }  
};




var AjaxObject = Class.create({
  showLoading: function()
  {
    
  },
  
  hideLoading: function()
  {
    
  },
  
  ajaxFailed: function(req)
  {
    if (req.status == 401)
    {
      new Ajax.Request('/users/register',{method: 'get',onSuccess: this.showRegistration.bind(this),onFailure: this.ajaxFailed.bind(this)});
    }  
    else
    {
      this.hideLoading();
      alert('Sorry. request failed.');  
    }
  },

  showRegistration: function(req){
    this.hideLoading();

    new PopupDiv(req.responseText,null,null,'registration-ajax-form');
  }
});


var AlertVerification = Class.create(AjaxObject, {
  initialize: function(element)
  {
    this.domElement = $(element);
    this.domElement.select('.yes', '.no').each(function(e) {
      e.observe('click', this.buttonClick.bindAsEventListener(this));
    }.bind(this));
  },
    
  buttonClick: function(event)
  {
    if (this.domElement.hasClassName('inactive_l') || this.domElement.hasClassName('inactive_v'))
    {
      event.stop();
      return;
    }

    this.showLoading();
    new Ajax.Request(event.element().href, {onSuccess: this.ajaxSuccess.bind(this), onFailure: this.ajaxFailed.bind(this)});
    
    event.stop();
  },
  
  ajaxSuccess: function(req)
  {
    this.domElement.replace(req.responseText);
  }
});


var ToggleActive = Class.create(AjaxObject, {
  initialize: function(container)
  {
    this.domContainer = $(container);
    this.domCheckbox = $(container).down('input[type=checkbox]');
    this.domLink = $(container).down('a');

    this.domLink.observe('click', this.linkClick.bindAsEventListener(this));
    this.domCheckbox.observe('click', this.sendRequest.bind(this));
  },
   
  linkClick: function(event)
  {
    event.stop();
    this.domCheckbox.checked = !this.domCheckbox.checked;
    this.sendRequest();
  },
  
  sendRequest: function()
  {
    new Ajax.Request(this.domLink.href, {onSuccess: this.requestSuccessful.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },
  
  requestSuccessful: function(req)
  {
    //this.domContainer.fire('List:reload');
    //new PopupDiv('alert updated');
    
    new Notification('Alert updated');
  }
});

var EntitiesList = Class.create(AjaxObject, {
  initialize: function(container, firstPageUrl, currentPageUrl, currentPageXmlUrl)
  {
    this.firstPageUrl = firstPageUrl;
    this.currentPageUrl = currentPageUrl;
    
    
    this.domContainer = $(container);
    this.domPagers = this.domContainer.select('.pager');
    this.domList = this.domContainer.down('.p_list');


    this.domContainer.jsObject = this;

    if (this.domPagers.length)
    {
      for (var i = 0; i < this.domPagers.length; i++)
      {
        this.initPager(this.domPagers[i]);
      }  
    }
    //load new feed into map
    if (currentPageXmlUrl)
    {
      if (window.mapLoaded)
      {
        $("MSMV").loadMapFeed(currentPageXmlUrl);
      }
      else
      {
        window.xmlToLoad = currentPageXmlUrl;
      }  
    }

    this.domContainer.observe('List:reload', this.reload.bind(this));
    this.domContainer.observe('List:showLoading', this.showLoading.bind(this));
    this.domContainer.observe('List:hideLoading', this.hideLoading.bind(this));
  },
  
  initPager: function(domPager)
  {
      domPager.select('.pageNum > a').each(function(link) {
        link.onfocus = function() {this.blur();}
        if (link.href == 'javascript:void(0)')
          return;
        link.observe('click', this.pageClick.bindAsEventListener(this))
      }.bind(this));
      var domPageSize;
      if (domPageSize = domPager.down('select[name=page_size]'))
      {
        domPageSize.onchange = this.loadPageForm.bind(this, domPageSize.form);
      }  
  },
  
  showLoading: function()
  {
      if (this.domContainer.down('img.loading'))
        this.domContainer.down('img.loading').show();
  },
  
  hideLoading: function()
  {
      if (this.domContainer.down('img.loading'))
        this.domContainer.down('img.loading').hide();
  },
  
  loadPage: function(pageUrl)
  {
    this.showLoading();
    new Ajax.Request(pageUrl, {onSuccess: this.onListLoad.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },
  
  loadPageForm: function(form)
  {
   
    this.showLoading();
    $(form).request({onSuccess: this.onListLoad.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },
  
  pageClick: function(event)
  {
    
    this.loadPage(event.element().href);
    event.stop();
  },

  reload: function()
  {
    this.loadPage(this.currentPageUrl);
  },
  
  reset: function()
  {
    this.loadPage(this.firstPageUrl);
  },

  onListLoad: function(response)
  {
    this.domContainer.replace(response.responseText);
//    alert('success') ;
    this.hideLoading();
    $(document).fire('List:relocalize_time');
  }
});

var AlertList = Class.create(AjaxObject, {
  initialize: function(container, alias)
  {
    this.currentPageUrl = alias;
    this.domContainer = $(container);
    this.params = {page:'1', category_id:'', country_id:'', continent:'', age:'1', sort:'update', page_size: '15', q:''};
    this.domContainer.observe('List:reload', this.reload.bind(this));
    this.domContainer.observe('List:showLoading', this.showLoading.bind(this));
    this.domContainer.observe('List:hideLoading', this.hideLoading.bind(this));
  },

  loadMap: function() {
    currentPageXmlUrl = '/get-xml.php?type=alerts';
	for (i in this.params) {
		currentPageXmlUrl+='&'+i+'='+this.params[i];
	}
    if (currentPageXmlUrl)
    {
      if (window.mapLoaded)
      {
        $("MSMV").loadMapFeed(currentPageXmlUrl);
      }
      else
      {
        window.xmlToLoad = currentPageXmlUrl;
      }  
    } 
  },

  resetPage: function() {
	this.params['page'] = '1';
  },

  setParam: function(key, val) {
		this.params[key] = val;
  },
  
  getParams: function() {		
		return this.params;
  },

  showLoading: function()
  {
      if (this.domContainer.down('img.loading'))
        this.domContainer.down('img.loading').show();
  },
  
  hideLoading: function()
  {
      if (this.domContainer.down('img.loading'))
        this.domContainer.down('img.loading').hide();
  },
  
  loadPage: function(pageUrl)
  {
    this.showLoading();
    new Ajax.Request(pageUrl, {parameters:this.params, onSuccess: this.onListLoad.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },

  loadPageAlternative: function(link, num)
  {
  	if (link.className.indexOf('end') != -1) {
		return false;
	}	
    if(num>0)
    	this.params['page']++;
    else
    	this.params['page']--;
	this.reload();
  },

  loadPageForm: function(form)
  {
    this.showLoading();
    $(form).request({onSuccess: this.onListLoad.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },
  
  pageClick: function(event)
  {  	
    this.loadPage(this.currentPageUrl);
    event.stop();
  },

  reload: function()
  {
    this.loadPage(this.currentPageUrl);
  },
  
  reset: function()
  {
    this.loadPage(this.firstPageUrl);
  },

  onListLoad: function(response)
  {
    this.domContainer.update(response.responseText);    
    this.hideLoading();
    $(document).fire('List:relocalize_time');
  }
});

var AlertItem = Class.create(AjaxObject, {
  initialize: function(container)
  {
    this.domContainer = $(container);
    
    this.domWatchlistLink = this.domContainer.down('.actions a[class*=wl_]');
    if (this.domWatchlistLink)
    {
      this.domWatchlistLink.observe('click', this.onWatchlistClick.bindAsEventListener(this));
    }  
  },
  
  onWatchlistClick: function(event)
  {
    event.stop();
  
    this.showLoading();
    new Ajax.Request(event.element().href, {onSuccess: this.onReload.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },
  
  onReload: function(req)
  {
    this.hideLoading();
    this.domContainer.replace(req.responseText);
  },
  
  showLoading: function()
  {
    this.domContainer.fire('List:showLoading');
  },
  
  hideLoading: function()
  {
    this.domContainer.fire('List:hideLoading');
  }
});


var UserList = Class.create(EntitiesList, {
  initialize: function($super, container, firstPageUrl, currentPageUrl, currentPageXmlUrl)
  {
    $super(container, firstPageUrl, currentPageUrl, currentPageXmlUrl);
    
    
    var mouseoverBound = this.itemMouseOver.bindAsEventListener(this);
    var mouseoutBound = this.itemMouseOut.bindAsEventListener(this);
    
    this.domList.select('li.photo4').each(function(e) {
      e.observe('mouseover', mouseoverBound);
      e.observe('mouseout', mouseoutBound);
    }.bind(this));
  },
  
  itemMouseOver: function(event)
  {
    e = event.findElement('li');
    e.down('.user_info').show();
  },
  
  itemMouseOut: function(event)
  {
    e = event.findElement('li');
    e.down('.user_info').hide();
  }
  
});

var CommentList = Class.create(EntitiesList, {
  initialize: function($super, container, firstPageUrl, currentPageUrl)
  {
    $super(container, firstPageUrl, currentPageUrl);
    
    this.domList = this.domContainer.down('.comments');
    this.domAddLink = this.domContainer.down('.a_add');
    
    if (this.domAddLink)
    {
      this.domAddLink.observe('click', this.showAddDialog.bindAsEventListener(this));
    }
    
     //add some text inside if list is empty
    /*
    if (!this.domList.down('div'))
    {
      this.domList.appendChildren(this.domEmptyMsg = new Element('div', {'class': 'empty_msg'}));

      if (this.domAddLink)
      {
        this.domEmptyMsg.update('There is no comments in the list. Click <a href="#">here</a> to add some.');
        this.domEmptyMsg.down('a').href = this.domAddLink.href;
        this.domEmptyMsg.down('a').observe('click', this.showAddDialog.bindAsEventListener(this));
      }
      else
      {
        this.domEmptyMsg.update('There is no comments in the list.');
      }  
    }   
    */
    
    this.domList.select('.user_info .actions a.remove').each((function(e) {
      e.observe('click', this.onDeleteClick.bindAsEventListener(this));
    }).bind(this));
    
    
  },

  onDeleteClick: function(event)
  {
    event.stop();
    
    this.showLoading();
    new Ajax.Request(event.element().href, {method: 'get', onSuccess: this.onDeleteSuccess.bind(this), onFailure: this.ajaxFailed.bind(this)})
  },

  onDeleteSuccess: function(req)
  {
    this.hideLoading();
    this.reload();
  },

  showAddDialog: function(event)
  {
    this.showLoading();
    new Ajax.Request(event.element().href, {method: 'get', onSuccess: this.addDialogReady.bind(this), onFailure: this.ajaxFailed.bind(this)});
    event.stop();
  },
  
  addDialogReady: function(req)
  {
    this.addDialogPopup = new PopupDiv(req.responseText);
    
    //process events which dialog may send
    this.addDialogPopup.toElement().observe('FormDialog:success', this.newCommentPosted.bindAsEventListener(this));
    this.hideLoading();
  },
  
  newCommentPosted: function(event)
  {
    this.reset();
  } 
});


var PhotoList = Class.create(EntitiesList, {
  initialize: function($super, container, firstPageUrl, currentPageUrl, hook)
  {
    $super(container, firstPageUrl, currentPageUrl);
    
    this.domList = this.domContainer.down('.gallery');
    this.domAddLink = this.domContainer.down('.links2 .a_add');
    this.onReloadHook=hook;
    
    if (this.domAddLink)
    {
      this.domAddLink.observe('click', this.showAddDialog.bindAsEventListener(this));
    }

    var domSort;
    if (domSort = this.domPagers[0].down('select[name=sort]'))
    {
      domSort.onchange = this.loadPageForm.bind(this, domSort.form);
    }  
  },
  
  
  
  
  showAddDialog: function(event)
  {
    this.showLoading();
    new Ajax.Request(event.element().href, {method: 'get', onSuccess: this.addDialogReady.bind(this), onFailure: this.ajaxFailed.bind(this)});
    event.stop();
  },
  
  addDialogReady: function(req)
  {
    this.addDialogPopup = new PopupDiv(req.responseText);
    
    //process events which dialog may send
    this.addDialogPopup.toElement().observe('AddPhotoDialog:posted', this.newPhotosPosted.bindAsEventListener(this));
    this.hideLoading();
  },
  
  newPhotosPosted: function(event)
  {
    if(this.onReloadHook)
      this.onReloadHook();
    this.reset();
  },
  
  reload: function($super,event){
    if(this.onReloadHook)
      this.onReloadHook();
    $super(event);
  },
  
  //details dialog
  
  showDetails: function(domItem)
  {
    this.domCurrentItem = domItem;

    this.showLoading();
    new Ajax.Request(domItem.href, {method: 'get', onSuccess: this.detailsDialogReady.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },
  
  detailsDialogReady: function(req)
  {
    this.detailsPopup = new PopupDiv(req.responseText);
    
    //add next/prev links
    
    this.hideLoading();
  }
});


var PhotoThumb = Class.create(AjaxObject, {
  initialize: function(container)
  {
  	//alert('creating ajax object');
    this.domContainer = $(container);
    this.domLink = this.domContainer.down('a');
    this.domEditLink = this.domContainer.down('.photo_actions .p_edit');
    this.domDeleteLink = this.domContainer.down('.photo_actions .p_remove');

    this.domContainer.jsObject = this;
   
    this.domLink.onfocus = function() {this.blur()}
       
    this.domContainer.observe('mouseover', this.onMouseOver.bindAsEventListener(this));
    this.domContainer.observe('mouseout', this.onMouseOut.bindAsEventListener(this));
    this.domLink.observe('click', this.onClick.bindAsEventListener(this));
    
    if (this.domEditLink)
    {
      this.domEditLink.observe('click', this.onEditClick.bindAsEventListener(this));
    }
    
    if (this.domDeleteLink)
    {
      this.domDeleteLink.observe('click', this.onDeleteClick.bindAsEventListener(this));
    }
  },
  
  showLoading: function()
  {
    try
    {
      this.domContainer.up('.list_wrapper').down('img.loading').show();
    }
    catch (e) {}
  },
  
  hideLoading: function()
  {
    try
    {
      this.domContainer.up('.list_wrapper').down('img.loading').hide();
    }
    catch (e) {}
  },
  
  onMouseOver: function(event)
  {
    this.domContainer.addClassName('p_hover');
  },
  
  onMouseOut: function(event)
  {
    this.domContainer.removeClassName('p_hover');
  },
  
  onClick: function(event)
  {
  	//alert('in onclick function');
    event.stop();
    var domLink = event.findElement('a');
    if (domLink == document)
      return;
    
    if (domLink.href == 'javascript:void(0)')
      return;
    
    
    this.showLoading();
    new Ajax.Request(domLink.href, {onSuccess: this.popupLoaded.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },
 
  popupLoaded: function(req)
  {
    this.detailsPopup = new PopupDiv(req.responseText, null, null, 'photo_thumb_popup');
    
    var domPrevLink =  this.detailsPopup.domContainer.down('.pageNum .prev');
    var domNextLink =  this.detailsPopup.domContainer.down('.pageNum .next');
    
    if (domPrevLink)
      domPrevLink.observe('click', this.onClick.bindAsEventListener(this));
    
    if (domNextLink)
      domNextLink.observe('click', this.onClick.bindAsEventListener(this));
    
    
    this.hideLoading();
  },
  
  
  onEditClick: function(event)
  {
    event.stop();
    domLink = event.findElement('a');
    
    this.showLoading();
    new Ajax.Request(domLink.href, {method: 'get', onSuccess: this.editPopupLoaded.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },
  
  editPopupLoaded: function(req)
  {
    this.editPopup = new PopupDiv(req.responseText);
    this.hideLoading();
  },
  
  
  onDeleteClick: function(event)
  {
    event.stop();
    domLink = event.findElement('a');
    
    msg = domLink.readAttribute('confirm_message');

    if (msg && msg != '')
    {
      if (!confirm(msg))
        return;
    }
    
    new Ajax.Request(domLink.href, {method: 'post', onSuccess: this.deleteSuccess.bind(this), onFailure: this.ajaxFailed.bind(this)});

  },
  
  deleteSuccess: function(req)
  {
    this.domContainer.fire('List:reload');
  }
});


var RegisterForm = Class.create({
  initialize: function(upload_url, form_hidden_field, image_container, progress_bar, upload_link, remove_link,img_path)
  {
    this.folder_name = '180x180-fit';
    this.uploadUrl = upload_url;
    this.domImageIdInput = $(form_hidden_field);
    this.domImage = $(image_container);
    this.domProgressBar = $(progress_bar);
    this.domUploadLink = $(upload_link);
    //this.domRemoveLink = $(remove_link);
    this.domActions=this.domImage.next('.actions');
    this.ImagePath = img_path;
    this.width = '180';
	this.height = '180';
    
    this.domImageHolder = this.domImage.down('span');

    if((this.domIAgree=$('i_agree')))
      this.domIAgree.up('form').observe('submit',this.on_submit.bind(this));

    if((this.domRecieveMessages=$('user_recive_messages'))){
      var self=this;
      Event.observe(window,'load',function(){
        self.domNotificationsSelector=$('notifications_selector');
        self.show_hide_notifications();
        self.domRecieveMessages.observe('click',self.show_hide_notifications.bind(self));
      });
    }

    this.domUploadLink.hide();
    this.domProgressBar.hide();

    this.show_hide();
    this.initUploader.bind(this).delay(0);
  },

  show_hide_notifications: function(){
    if(this.domRecieveMessages.checked){
    	this.domNotificationsSelector.setStyle({display:'block'});
	      if(!this.notification_showed){
	        //if((this.domIAgree&&!this.domIAgree.checked)||!$('user_notify_by_email').checked){
	          //$('user_notify_by_email').checked=true;
	          //$('user_notification_email').value=$('user_email').value;
	        //}
	        this.notification_showed=true;
	      }
    }else{
		this.domNotificationsSelector.setStyle({display:'none'});
    }
  },

  on_submit: function(evt){
    if(!this.domIAgree.checked){
      alert('Please confirm you have read and agree with terms of use and privacy policy.');
      Event.stop(evt);
    }
  },

  show_hide: function(){
    if(this.domImageHolder.style.backgroundImage){
      this.domImage.show();
    }else{
      this.domImage.hide();
      this.domActions.addClassName('no-margin-top');
    }
  },

  initUploader: function()
  {
        uploadUrl = this.uploadUrl;
        if (this.uploadUrl.match(/\?/))
            uploadUrl += '&';
        else
            uploadUrl += '?';

		uploadUrl += 'swfupload_sid='+SID();
		if(getFlashVersion() != '0,0,0') {
			this.swfu = new SWFUpload({
	            upload_url: uploadUrl, 
	            flash_url:  '/js/dui/swfupload/swfupload.swf',
				post_params: {folder: this.folder_name, type:'user'},
	            file_size_limit: "200",
	            file_types_description : "Image Files",
	            file_types : "*.jpg;*.gif;*.png",
	            button_placeholder_id: this.domUploadLink.id,
	            button_image_url: this.ImagePath,
	            button_width: 89,
	            button_height: 22,
	
	            //events
	            swfupload_loaded_handler: this.onFlashLoaded.bind(this),
	            file_queued_handler: this.onFileQueued.bind(this),
	            upload_progress_handler: this.uploadProgress.bind(this),
	            upload_success_handler: this.uploadSuccess.bind(this)
	      });
      } else {
		 $('upload_photo_disable').setStyle({display:'block'})
	  }
  },

  onFlashLoaded: function()
  {
    this.domUploadLink.show();
  },


  browse: function()
  {
    //clear prev file if there is one
    this.swfu.cancelUpload(); 
    this.swfu.selectFile();
  },
  
  onFileQueued: function(file)
  {
    this.domUploadLink.hide();
    //this.domRemoveLink.hide();
    
    this.domProgressBar.down().style.width = '0';
    this.domProgressBar.show();
    
    this.swfu.startUpload();
  },
  
  uploadProgress: function(file, complete, total)
  {
      this.domProgressBar.down().style.width = (100*complete/total)+'%'
  },
  
  uploadSuccess: function(file, response)
  {
	var serverFileInfo = response.evalJSON();
	this.domProgressBar.hide();
	this.domUploadLink.show();
	if(serverFileInfo.success == true) {
	    //this.domRemoveLink.show();
		this.domImageIdInput.value = serverFileInfo.id;
		this.domImage.down().style.backgroundImage = "url('/utils/phpThumb?src=/resampled/#{size}/uploads/#{filename}&w=#{width}&h=#{height}')".interpolate({width:this.width, height:this.height, size:this.folder_name, filename:serverFileInfo.filename});
		this.show_hide();
    }
  },
  
  remove: function()
  {
    this.domImageIdInput.value = '';
    this.domImage.down().style.backgroundImage = '';
    this.show_hide();
  }
  
});



var EditAlertForm = Class.create(AjaxObject, {
  initialize: function(ajaxUrl, isNewRecod)
  {
    this.ajaxUrl = ajaxUrl
    this.isNewRecord = isNewRecod;
    this.domForm = $('edit_alert_form');
    this.domCategorySelect = $('alert_category_id');
    
    
    /*if (!this.isNewRecord)
    {
      $('alert_title').addClassName('ff_disabled').disabled = true;
      $('alert_category_id').addClassName('ff_disabled').disabled = true;
    }*/
    
    //this.domCategorySelect.insert({after: '<img src="/images/e.gif" id="alert_category_icon"/>'});
    this.updateCategoryIcon();

    //this.domCategorySelect.observe('change', this.categoryChanged.bind(this));
    this.domCategorySelect.observe('change', this.updateCategoryIcon.bind(this));
  },

  updateCategoryIcon: function()
  {
    iconPath = categoryIcons[$F(this.domCategorySelect)];
    if (iconPath)
    {
      $('alert_category_icon').src = iconPath;
    }
    else
    {
      $('alert_category_icon').src = '/img/e.gif';
    }  
  },
  
  categoryChanged: function()
  {
    this.showLoading();
    new Ajax.Request(this.ajaxUrl, {parameters: $H({category_id: $F(this.domCategorySelect)}), onSuccess: this.contentLoaded.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },
  
  contentLoaded: function(req)
  {
    //let's delete old html'
    first_row = this.domForm.down('[sc=start]').up();
    last_row = this.domForm.down('[sc=end]').up();
    
    to_delete = []
    row = first_row.next();
    while(1)
    {
      to_delete.push(row);
      
      if (row == last_row)
        break;
      
      row = row.next();
    }
    
    for (var i = 0; i < to_delete.length; i++)
      to_delete[i].remove();
    
    
    first_row.replace(req.responseText);
    
    this.hideLoading();
  }
});

var PopupDiv = Class.create({
  initialize: function(content, width, height, containerId)
  {
    if (containerId && $(containerId))
    {
      previousClosed = true;
      $(containerId).fire('Window:close');
    }  
    else
    {
      previousClosed = false;
    }  


    this.domContainer = new Element('div', {id: 'popup_'+Math.random().toString().substring(2)}).appendChildren(
      this.domCloseLink = new Element('a', {href: 'javascript:void(0)'}).appendText('Close Window'),
      this.domLoading = new Element('img', {src: '/images/loading2.gif', style: 'display: none;'}),
      this.domContent = new Element('div')
    );
    this.domContainer.addClassName('popup');
    this.domCloseLink.addClassName('a_close redButton');
    this.domLoading.addClassName('loading');
    
    
    this.domContent.update(content);
    this.domCloseLink.observe('click', this.close.bind(this));
   
    this.domContainer.observe('Window:close', this.close.bind(this));
    this.domContainer.observe('Window:center', this.center.bindAsEventListener(this));
    this.domContainer.observe('Window:showLoading', this.showLoading.bind(this));
    this.domContainer.observe('Window:hideLoading', this.hideLoading.bind(this));

    this.domContainer.style.width = (width || 'auto');
    this.domContainer.style.height = (height || 'auto');
    
    this.domContainer.style.display = 'none';
    document.body.appendChild(this.domContainer);
    
    this.center();
    
    if (previousClosed)
    {  
      this.domContainer.show();
    }
    else
    {
      new Effect.Appear(this.domContainer, {duration: 0.2});      
    }
  },

  setContent: function(content)
  {
    this.domContent.update(content);
    this.center();
  },

  center: function(effectOrEvent)
  {
      var showEffect = false;
      
      if(effectOrEvent && effectOrEvent.eventName)
      {
        if (effectOrEvent.memo == true)
          showEffect = true;
      }
      else
      {
        showEffect = effectOrEvent;
      }  
      
      
      
      
      var viewportSize = document.viewport.getDimensions();
      var popupSize = this.domContainer.getDimensions();
      
      var targetViewportOffset = [(viewportSize.width-popupSize.width)/2, (viewportSize.height-popupSize.height)/2];
      var currentViewportOffset = this.domContainer.viewportOffset();
      
      var currentDocumentOffset = this.domContainer.cumulativeOffset();
      var targetDocumentOffset = [
        targetViewportOffset[0]-currentViewportOffset[0]+currentDocumentOffset[0],
        targetViewportOffset[1]-currentViewportOffset[1]+currentDocumentOffset[1]
      ];
      
      
      var styleLeft = targetDocumentOffset[0]+'px';
      var styleTop = targetDocumentOffset[1]+'px';

      if (showEffect)
      {
        new Effect.Morph(this.domContainer, {style: {left: styleLeft, top: styleTop}, duration: 0.5});
      }
      else
      {
        
        this.domContainer.style.left = styleLeft;
        this.domContainer.style.top = styleTop;
      }
  },
  
  toElement: function()
  {
    return this.domContainer;
  },
  
  close: function()
  {
    this.domContainer.id = null;
    this.remove();
    
    //new Effect.Fade(this.domContainer, {duration: 0.2, afterFinish: this.remove.bind(this)});
  },
  
  remove: function()
  {
    this.domContainer.remove();
  },
  
  showLoading: function()
  {
    this.domLoading.show();
  },
  
  hideLoading: function()
  {
    this.domLoading.hide();
  }
});



var AddPhotoDialog = Class.create(AjaxObject, {
  initialize: function(uploadUrl, container,img_pth)
  {
    this.uploadUrl = uploadUrl;

    this.domContainer = $(container);
    this.domList = this.domContainer.down('.uploads_list');
    this.initUploader.bind(this).delay(0); //ie sucks
    this.ImagePath=img_pth;
    
    this.domUploadButton=this.domContainer.down('#upload_photos');
    //this.domUploadButton = this.domContainer.down('[action=upload]');
    this.domPostButton = this.domContainer.down('[action=post]');
    
    //this.domUploadButton.observe('click', this.browse.bindAsEventListener(this));
    //this.domUploadButton.disabled = true;
    
    this.domPostButton.observe('click', this.postSelected.bindAsEventListener(this));
  },
  
  showLoading: function()
  {
    this.domContainer.fire('Window:showLoading');
  },
  
  hideLoading: function()
  {
    this.domContainer.fire('Window:hideLoading');
  },
  
  
  initUploader: function()
  {
        uploadUrl = this.uploadUrl;
        if (this.uploadUrl.match(/\?/))
            uploadUrl += '&';
        else
            uploadUrl += '?';
        
        uploadUrl += 'swfupload_sid='+SID();
      
      
      if(getFlashVersion() != '0,0,0') {
	      this.swfu = new SWFUpload({
	            upload_url: uploadUrl, 
	            flash_url:  '/js/dui/swfupload/swfupload.swf',
	
	            file_size_limit: '3000',
	            file_types : "*.jpg;*.gif;*.png",
	
	            button_placeholder_id: this.domUploadButton.id,
	            button_image_url: this.ImagePath,
	            button_width: 126,
	            button_height: 22,
	            
	            //events
	            swfupload_loaded_handler: this.onFlashLoaded.bind(this),
	            file_queued_handler: this.onFileQueued.bind(this),
	            upload_progress_handler: this.uploadProgress.bind(this),
	            upload_success_handler: this.uploadSuccess.bind(this),
	            upload_complete_handler: this.uploadComplete.bind(this),
	            file_dialog_complete_handler: this.fileDialogComplete.bind(this)
	      });
      }
      
  },

  onFlashLoaded: function()
  {
    this.domUploadButton.disabled = false;
  },


  browse: function(event)
  {
    this.swfu.selectFiles();
    event.stop();
  },
  
  onFileQueued: function(file)
  {
    var domBlock = new Element('div', {'class': 'uploadBlock', file_id: file.id}).appendChildren(
      new Element('div', {'class': 'p_progress'}).appendChildren(
        new Element('div').appendChildren(
          new Element('span').appendText(file.name))
      )
    );

    //add separator if needed
    if (this.domList.down('.uploadBlock'))
    {
      this.domList.insert({top: '<p class="pl">&nbsp;</p>'});
    }
    
    this.domList.insert({top: domBlock});
  },
  
  uploadProgress: function(file, complete, total)
  {
      this.domList.down('[file_id='+file.id+']').down('.p_progress div').style.width = (100*complete/total)+'%';
  },
  
  uploadSuccess: function(file, response)
  {
    this.domList.down('[file_id='+file.id+']').replace(response);
  },
  
  uploadComplete: function(file)
  {
    this.swfu.startUpload();
    
    stats = this.swfu.getStats();
    if (stats.files_queued == 0)
    {
      this.done();
    }
  },
  
  fileDialogComplete: function(selected, queued)
  {
    if (selected == 0)
      return;
    
    this.domPostButton.disabled = true;
    this.domUploadButton.disabled = true;
    this.showLoading();
    
    this.swfu.startUpload();
  },
  
  done: function()
  {
    this.domUploadButton.disabled = false;
    this.domPostButton.disabled = false;
    this.hideLoading();
  },
  
  
  postSelected: function(event)
  {
    if (this.domContainer.up('.popup'))
    {
      //we're in popup window... do ajax
      event.stop();
      
      this.showLoading();
      this.domContainer.down('form').request({method: 'post', onSuccess: this.postSelectedSuccess.bind(this), onFailure: this.ajaxFailed.bind(this)});
      return;
    }
  },
  
  postSelectedSuccess: function(req)
  {
    //this event will be caught by photos list
    this.domContainer.fire('AddPhotoDialog:posted');
    
    //and this - by window
    this.domContainer.fire('Window:close');
    this.hideLoading();
  }
});


var BaseFormDialog = Class.create(AjaxObject, {
  initialize: function(container)
  {
    this.domContainer = $(container);
    
    if (!this.domContainer.up('.popup'))
    {
      return;
    }
    
    this.domContainer.down('form input[type=submit]').observe('click', this.onSubmitClick.bindAsEventListener(this));
	
  },
  
  showLoading: function()
  {
    this.domContainer.fire('Window:showLoading');
  },
  
  hideLoading: function()
  {
    this.domContainer.fire('Window:hideLoading');
  },
  
  onSubmitClick: function(event)
  {
    event.stop();
    this.showLoading();
    this.domContainer.down('form').request({method: 'post', onSuccess: this.submitSuccess.bind(this), onFailure: this.ajaxFailed.bind(this)});
  },
  
  submitSuccess: function(req)
  {
    this.hideLoading();
    
    if(req.responseJSON)
    {
      this.domContainer.fire('FormDialog:success');
      this.domContainer.fire('Window:close');
    }
    else
    {
      this.domContainer.replace(req.responseText);
      this.domContainer.fire('Window:center');  
    }
    
    
  }
});




var EditPhotoDialog = Class.create(BaseFormDialog, {});
 


var AddCommentDialog = Class.create(BaseFormDialog, {});



var Notification = Class.create({
  timeout: 2,
    
  initialize: function(text, className)
  {
    this.initContainer();
    this.initList();
    
    this.domNotification = new Element('li', {'class': (className || '')}).appendText(text);
    this.domList.insert({bottom: this.domNotification});
    //this.domNotification.hide();

    setTimeout(this.onTimeout.bind(this), this.timeout*1000);
  },
  
  initContainer: function()
  {
    this.domContainer = $('notifications_container'); 
    
    if (this.domContainer)
      return;
    
    
    this.domContainer = new Element('div', {id: 'notifications_container'});
    $(document.body).insert({bottom: this.domContainer});
    $(document.body).observe('mousemove', this.onMouseMove.bindAsEventListener(this));
  },
  
  initList: function()
  {
    this.domList = this.domContainer.down('ul');
    
    if (this.domList)
      return;
    
    
    this.domList = new Element('ul');
    this.domContainer.insert({bottom: this.domList});
  },
  
  onMouseMove: function(event)
  {
    this.domContainer.style.left = event.pointerX()+'px';
    this.domContainer.style.top = event.pointerY()+'px';
  },
  
  onTimeout: function()
  {
    this.domNotification.remove();
    
    if (!this.domList.down('li'))
    {
      this.domList.remove();
    }  
  }
  
});





var VideoList = Class.create(PhotoList, {
  addDialogReady: function($super, req)
  {
    $super(req);
    this.addDialogPopup.toElement().observe('FormDialog:success', this.newPhotosPosted.bindAsEventListener(this));
  }
});

var VideoThumb = Class.create(PhotoThumb, {
});

var AddVideoDialog = Class.create(BaseFormDialog, {
});




var UpdateList = Class.create(CommentList, {
});

var AddUpdateDialog = Class.create(BaseFormDialog, {
});



var NewlinksList = Class.create(AjaxObject, {
  initialize: function(container, listUrl)
  {
    this.domContainer = $(container);
    this.listUrl = listUrl;
    
    this.domAddLink = this.domContainer.down('.links2 .add');
    this.domAddLink.observe('click', this.showAddDialog.bindAsEventListener(this));
    
    this.addHandlers();
  },
  
  addHandlers: function()
  {
    this.domContainer.select('li .actions .remove').each(function(link) {
      link.observe('click', this.deleteClick.bindAsEventListener(this));
    }.bind(this));
  },
  
  reloadList: function()
  {
    new Ajax.Request(this.listUrl, {method: 'get', onSuccess: this.onlistLoad.bind(this), onFailure: this.ajaxFailed.bind(this)});  
  },
  
  onlistLoad: function(req)
  {
    this.domContainer.down('ul.news').update(req.responseText);
    this.addHandlers();
  },
  
  
  showAddDialog: function(event)
  {
    this.showLoading();
    new Ajax.Request(event.element().href, {method: 'get', onSuccess: this.addDialogReady.bind(this), onFailure: this.ajaxFailed.bind(this)});  
    event.stop();
  },
    
  addDialogReady: function(req)
  {
    this.addDialogPopup = new PopupDiv(req.responseText);
    
    //process events which dialog may send
    this.addDialogPopup.toElement().observe('FormDialog:success', this.reloadList.bind(this));
    this.hideLoading();
  },
  
  
  
  deleteClick: function(event)
  {
    event.stop();
    new Ajax.Request(event.element().href, {method: 'get', onSuccess: this.reloadList.bind(this), onFailure: this.ajaxFailed.bind(this)});  
    
  }
});


var UploadBlock = Class.create(AjaxObject, {
  initialize: function(container)
  {
    this.domContainer = $(container);
    this.domToggleLink = this.domContainer.down('.p_toggle');
    
    this.domToggleLink.observe('click', this.toggle.bind(this));
  },
  
  expand: function()
  {
    this.domContainer.adjacent('.ub_expanded').each(function(e) {
      e.removeClassName('ub_expanded');
    });
    
    this.domContainer.addClassName('ub_expanded');
    this.domContainer.up().scrollTop = this.domContainer.positionedOffset()[1];
    
  },
  
  collapse: function()
  {
    this.domContainer.removeClassName('ub_expanded');
  },
  
  toggle: function()
  {
    if (this.domContainer.hasClassName('ub_expanded'))
      this.collapse();
    else
      this.expand();
  }
});

function go_to(url){
  location.href=url;
  return false;
}

function create_reload_for_alert(elem,url){
  if(!$(elem))
    return null;

  return function(){
    new Ajax.Request(url);
  };
}

var video_types_by_value={
  other: {
    holder_class: '',
    code_url_text: 'Code:',
    code_url_desc: 'Paste embed code here'
  },
  youtube: {
    holder_class: 'invisible-field',
    code_url_text: 'Code or url:',
    code_url_desc: 'Paste code or url from youtube.com here'
  }
};

function embedded_video_type_change(btn){
  var top=btn.up('table');
  var ev=top.down('.embedded-video-code-or-url');
  top.rows[top.rows.length-2].className=video_types_by_value[btn.value].holder_class;
  ev.next('.field_decription').update(video_types_by_value[btn.value].code_url_desc);
  ev.up('tr').down('label').update(video_types_by_value[btn.value].code_url_text);
}

function video_type_change(elem){
  var holder=$('thumb_holder'),conf={};
  $('thumb_holder').className=video_types_by_value[elem.value].holder_class;
  //$('video_code_or_url').next('.field_decription').update(video_types_by_value[elem.value].code_url_desc);
  //$('video_code_or_url').up('tr').down('label').update(video_types_by_value[elem.value].code_url_text);
}

function mapIsLoaded()
{
  window.mapLoaded = true;
  
  
  if (window.xmlToLoad)
    $("MSMV").loadMapFeed(window.xmlToLoad);
}

function show_hide_us(sel,st){
  try{
    if($(sel).value!=61){
      ($(st)||$('states_selector')).hide();
    }else{
      ($(st)||$('states_selector')).show();
    }
  }catch(e){};
}

var obs=function(){
  $$('.local_time').each(function(e){
    try{
      e.writeAttribute('unconverted',e.innerHTML);
      e.update((new Date(e.innerHTML)).toLocaleString());
    }catch(e){}
  });
};

document.observe('dom:loaded', obs);
document.observe('List:relocalize_time', obs);

function defaulter(fields){
  var obj={};
  for(var i=0;i<arguments.length;++i){
    var t=$(arguments[i]);
    obj[t.id]=t.value;

    t.observe('focus',function(){
      if(this.value==obj[this.id])
        this.value='';
    });

    t.observe('blur',function(){
      if(this.value.length==0)
        this.value=obj[this.id];
    });
  }
}

function disable_text(to,obj){
  if(to)
    to=$(to);

  for(var i in obj){
    var x=$(i);
    obj[i]={handler: obj[i],value: x.value};

    x.observe('focus',function(evt){
      if(obj[this.id].handler)
        obj[this.id].handler(evt);
      Event.stop(evt);
      to.focus();
    });

    x.observe('change',function(evt){
      if(obj[this.id].handler)
        obj[this.id].handler(evt);
      this.value=obj[this.id].value;
      Event.stop(evt);
      to.focus();
    });
  }
}


var Locker=Class.create({
  initialize: function(elem,show_spinner,color){
    if(elem){
      this.elem=$(elem);

      if(!this.elem.id)
        this.elem.id=this.unique_id();
    }

    this.color=color||'#000';
    this.show_spinner=Object.isUndefined(show_spinner) ? true : show_spinner;
    this.locker={};
  },
  
  lock: function(elem,show_spinner){
    elem=elem?$(elem)||this.elem:this.elem;

    if(Object.isUndefined(show_spinner))
      show_spinner=this.show_spinner;

    if(!elem.id)
      elem.id=this.unique_id();

    if(!elem||this.locker[elem.id])
      return false;
    
    var locker=new Element('div',{'class': 'locker'});
    locker.setOpacity(0.5);
    locker.style.backgroundColor=this.color;
    document.body.appendChild(locker);
    locker.clonePosition(elem);


    var spin=null;
    if(show_spinner){
      spin=new Element('img',{src: '/images/spinner.gif','class': 'locker'});
      var off=locker.cumulativeOffset();

      spin.setStyle({
        top: (off[1]+parseInt(locker.getHeight()/2-24))+'px',
        left: (off[0]+parseInt(locker.getWidth()/2-24))+'px'
      });

      document.body.appendChild(spin);
    }

    this.locker[elem.id]={spinner: spin, lock: locker};

    return true;
  },

  unique_id: function(){
    var str="dynamic_id_";
    do{
      str+=Math.random().toString().substring(2);
    }while($(str));
    return str;
  },

  unlock: function(elem){
    elem=elem?$(elem)||this.elem:this.elem;
    if(!elem||!this.locker[elem.id])
      return false;

    if(this.locker[elem.id].spinner)
      this.locker[elem.id].spinner.remove();
    this.locker[elem.id].lock.remove();
    delete this.locker[elem.id];

    return true;
  }
});

var MultiLock=Class.create({
  initialize: function(obj){
    this.locker=new Locker(null,Object.isUndefined(obj.show_spinner) ? true : obj.show_spinner,obj.color||'#000');
    this.to_lock=$A(['div','input','select']);
    if(obj.elem){
      this.elem=$(obj.elem);
      if(obj.lock)
        this.lock();
    }
  },

  lock: function(elem){
    return this.pass_through_elms(elem,'lock');
  },

  unlock: function(elem){
    return this.pass_through_elms(elem,'unlock');
  },

  pass_through_elms: function(p,func){
    if(!(p=$(p))&&!(p=this.elem))
      return false;
    var t=$(p).getElementsByTagName('*');
    for(var i=0;i<t.length;++i){
      if(Object.isElement(t[i])&&this.to_lock.indexOf(t[i].nodeName.toLowerCase())!=-1)
        this.locker[func](t[i]);
    }

    return true;
  }
});

var NamedInsertion=Class.create({
  initialize: function(){
    this.insertions={};
  },

  add: function(name,e,c,pre){
    this.insertions[name]={
      element: $(e),
      content: c,
      predicate: pre
    };
  },

  insert_for: function(name){
    if(!(name in this.insertions))
      return;

    this.insertions[name].element.insert({bottom: this.insertions[name].predicate ? this.insertions[name].predicate(this.insertions[name].content) : this.insertions[name].content});
  }
});

function degree_to_km(degree){
  // Seetting default radius to 500 km/Miles
   if ((Math.round(((6378137*Math.PI*degree)/180)/1000)) < 500)
   {
   
	return(500)
   }
   else //actual radius
   {
  return (Math.round(((6378137*Math.PI*degree)/180)/1000)) 
  }
}

function radius_degree(km){
  return (km*180*1000)/(6378137*Math.PI);
}



function change_radius(){
  var v=this.value;

  if(change_radius.prev==v)
    return;
  change_radius.prev=v;

  if(!v.match(/^\d+(?:\.\d+)?$/)){
    $(this).addClassName('error-radius-input');
    return;
  }

  $(this).removeClassName('error-radius-input');
  $('MAPIT').changeFlashRadius(radius_degree(parseFloat(v))*(miles()?1.609344:1));
}

function flashIsLoaded(){

}
function fade_page()
{
	if($('layer_test')) {
  		$('layer_test').update("&nbsp;");
  	}
	if($('layer_test2')) {
  		$('layer_test2').update("&nbsp;");
  	}
  
  document.getElementById('page').style.opacity="0.9999";
    if(document.getElementById('page').style.filter) {
		document.getElementById('page').style.filter = 'alpha(opacity=10000)';
	}
	if($('video_from_utube')) {
		Effect.toggle('video_from_utube');
	}
	if($('video_snapshot')) {
		Effect.toggle('video_snapshot');
	}
	  
}

function hide_flash_object(){
	if($('video_from_utube')) {
		Effect.toggle('video_from_utube');
	}
	if($('video_snapshot')) {
		Effect.toggle('video_snapshot');
	}	
}

function set_border(ph_id,current_ph_id){
	carousel_images=document.getElementsByClassName('img_all');
	for (i=0;i<carousel_images.length;i++)
	{
		document.getElementById(carousel_images[i].id).style.border="0px solid red";
	}
	document.getElementById("img_bdr_"+ph_id).style.border="1px solid red";
}

function border_on_hover(ph_id,current_ph_id){
	if (document.getElementById("img_bdr_"+ph_id).activeElement){
	  document.getElementById("img_bdr_"+ph_id).style.border="1px solid red";	
	}
	document.getElementById("img_bdr_"+ph_id).style.border="0";	
}
function remove_border(ph_id,current_ph_id)
{
	
	document.getElementById("img_bdr_"+ph_id).style.border="0";
	if (document.getElementById("large_photo_id")){
		large_id = document.getElementById("large_photo_id").value;
		if(large_id == ph_id) {
			document.getElementById("img_bdr_" + ph_id).style.border = "1px solid red";
		}  
	}
}

function show_email_form(id){
	Effect.toggle('email_to_friend','blind');

		if(id == "email_plus"){
			document.getElementById(id).style.display= 'none';
			document.getElementById('email_minus').style.display= 'block';							
		}
		if(id == "email_minus"){

			document.getElementById(id).style.display= 'none';
			document.getElementById('email_plus').style.display= 'block';							
		}						

}

function show_minus(){
	document.getElementById('share_plus_minus').style.display = "block";
	document.getElementById('share_minus_plus').style.display = "none";			
}

function show_plus(){
	document.getElementById('share_plus_minus').style.display = "none";
	document.getElementById('share_minus_plus').style.display = "block";			
}
function watchlist_option(id){
		if(id == "watch_plus"){
			document.getElementById(id).style.display= 'none';
			document.getElementById('watch_minus').style.display= 'block';							
		}
		if(id == "watch_minus"){

			document.getElementById(id).style.display= 'none';
			document.getElementById('watch_plus').style.display= 'block';							
		}						

}
function watchlist_lists_update(el){
	
		if(el.className == "watch_add"){	
			el.innerHTML = "remove from watchlist";
			el.className = "watch_remove";
		}
		else if(el.className == "watch_remove"){
			el.innerHTML = "add to watchlist";
			el.className = "watch_add";							
		}
}
function text_options(id){
		if(id == "text_plus"){
			document.getElementById(id).style.display= 'none';
			document.getElementById('text_minus').style.display= 'block';							
		}
		if(id == "text_minus"){

			document.getElementById(id).style.display= 'none';
			document.getElementById('text_plus').style.display= 'block';							
		}	
		Effect.toggle('text_size','blind');					

}

function getFlashVersion(){ 
  // ie 
  try { 
    try { 
      // avoid fp6 minor version lookup issues 
      // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/ 
      var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
      try { axo.AllowScriptAccess = 'always'; } 
      catch(e) { return '6,0,0'; } 
    } catch(e) {} 
    return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; 
  // other browsers 
  } catch(e) { 
    try { 
      if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){ 
        return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; 
      } 
    } catch(e) {} 
  } 
  return '0,0,0'; 
} 

function changeContinent(continent, el) {
	$('filter_content').select('div.manage_row > a').each(function(e) {
		e.removeClassName('current_manager');
    });
	new Ajax.Updater(
		'managed_rows', 
		'/countries_list', 
		{
			asynchronous:true, 
			evalScripts:false, 
			parameters:'continent='+continent
		}
	);
	el.addClassName('current_manager');
	if(continent == 'all')
		continent = 'All Countries';
	$('filter_select_countries').update(continent);
}

function changeFilterDate(el, val, is_show_calendar) {
	$('filter_content').select('div.manage_row > a').each(function(e) {
		e.removeClassName('current_manager');
	});
	el.addClassName('current_manager');
	if (is_show_calendar)
		$('managed_rows').show();
	else {
		$('managed_rows').hide();
		AList.resetPage();
		AList.setParam('age', val);
		AList.reload();
	}
}

function changeFilterCategory(el, val) {
	$('filter_content').select('div.managed_row > a').each(function(e) {
		e.removeClassName('current_managed');
    });
	el.addClassName('current_managed');
	AList.resetPage();
	AList.setParam('category_id', val);
	AList.reload();
	//$('filter_select_date').update(el.innerHTML);
}

function changeFilterDateCustom() {
	var d1 = $('filter_date_field1').innerHTML;
	var d2 = $('filter_date_field2').innerHTML;
	if (d1.match(/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d/) && d2.match(/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d/)) {
  		AList.setParam('age', d1+','+d2);
  		AList.reload();
	} else {
		alert('Please choose date');
	}
}

function mainMenuChange(el, val) {
	$('mainMenu').select('a').each(function(e) {
		e.removeClassName('current');
    });
	AList.setParam('sort', val);
	AList.resetPage();
	AList.reload();
	el.addClassName('current');
}

function pageSizeChange(val) {
	AList.setParam('page_size', val);
	AList.resetPage();
	AList.reload();
}

function closeFilterBlocks() {
	//filter_selector
	$('filter_selectors').getElementsBySelector('dl > dd > a').each(function(e) {
		e.removeClassName('filter_selector_current');
    });
    $('filter_block_parent').update('');
}

function manageFilterBlocks(el) {
	$('filter_selectors').getElementsBySelector('dl > dd > a').each(function(e) {
		e.removeClassName('filter_selector_current');
    });
	el.addClassName('filter_selector_current');
	params = AList.getParams();
	if(el.id == 'filter_select_countries') {
		params.filter_type = 'location';
		new Ajax.Updater(
			'filter_block_parent', 
			'/filter', 
			{
				asynchronous:true, 
				evalScripts:false, 
				parameters:params
			});
	} else if(el.id == 'filter_select_date') {
		params.filter_type = 'date';
		new Ajax.Updater(
			'filter_block_parent', 
			'/filter', 
			{
				asynchronous:true, 
				evalScripts:true, 
				parameters:params,
				onComplete:function(e) {
					fsxml = '<configs><statecfg><mindate>2007-01-01</mindate><maxdate>2011-10-10</maxdate><dateformat>m/d/Y</dateformat></statecfg><initcfg><mode>flat</mode><multiselect>no</multiselect></initcfg></configs>';
			  		
					cal1 = new EpochPrime(
						document.getElementById('filter_calendar1'),
						fsxml, 
						false, 
						function(c){
							$('filter_date_field1').update(c.value);
						}
					);
					cal2 = new EpochPrime(
						document.getElementById('filter_calendar2'),
						fsxml, 
						false, 
						function(c){
							$('filter_date_field2').update(c.value);
						}
					);
				}
			}
		);
	} else if(el.id == 'filter_select_category') {
		params.filter_type = 'category';
		new Ajax.Updater(
			'filter_block_parent', 
			'/filter', 
			{
				asynchronous:true, 
				evalScripts:false, 
				parameters:params
			});		
	}
}

function contactFormChange(val) {
	$('contact_descriptions').getElementsBySelector('p').each(function(e) {
		e.hide();
    });
    if (val!=null && val!="") {
    	$('contact_descr-'+val).show();
    }
}