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');
  }
});

function entityMenuChange(el, val, alert_id) {
	$('mainMenu').select('li').each(function(e) {
		e.removeClassName('current');
    });
	
	AList.setUrl(val);
	AList.setParam('alert_id', alert_id);
	AList.resetPage();
	AList.reload();
	
	if (el.parentNode) el.parentNode.addClassName('current');
}

var AlertList = Class.create(AjaxObject, {
  initialize: function(container, alias, isLoadMap, params)
  {
    this.setUrl(alias);
    this.domContainer = $(container);
    this.isLoadMap = isLoadMap;
    this.params = params;
    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() {
	  BingMapsObj = new BingMaps('flashmap2',this.getUrl());
	  BingMapsObj.init();
  },

  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();
    if (this.isLoadMap) {
	    BingMapsObj.url = this.getUrl();
		BingMapsObj.loadXML();
    }

	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) {
    	if ((this.params['max_page']>1) && (this.params['page']<this.params['max_page'])) { 
    		this.params['page']++;
    	} else {
    		return false;
    	}
    } else {
    	if (this.params['page']>1) { 
        	this.params['page']--;
    	} else {
    		return false;
    	}
    }
	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)
  {
	if (response.responseText) {
		 var response_extra_index = response.responseText.indexOf('(extra):');
		 if (response_extra_index==-1) {
			this.domContainer.update(response.responseText);
		 } else {
			this.domContainer.update(response.responseText.substring(0,response_extra_index-1));
			if ($('categories_cloud')) {
				$('categories_cloud').update(response.responseText.substring(response_extra_index+8));
			}
		 }
	}
    this.hideLoading();
    $(document).fire('List:relocalize_time');
  },

  getUrl: function() {
	    currentPageXmlUrl = '/get-xml.php?type=alerts';
		for (i in this.params) {
			currentPageXmlUrl+='&'+i+'='+this.params[i];
		}
		return currentPageXmlUrl; 
  
  },
  setUrl: function(url) {
		this.currentPageUrl = url;
  }
});

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, width, height)
  {
  	//alert('creating ajax object');
    this.domContainer = $(container);
    this.domLink = $(this.domContainer.id+'-a');
    this.domLink2 = $(this.domContainer.id+'-a2');
    this.domEditLink = this.domContainer.down('.p_edit');
    this.domDeleteLink = this.domContainer.down('.p_remove');
    this.width = width;
    this.height = height;

    this.domContainer.jsObject = this;
   
    if (this.domLink) {
    	this.domLink.onfocus = function() {this.blur()}
    }
       
    this.domContainer.observe('mouseover', this.onMouseOver.bindAsEventListener(this));
    this.domContainer.observe('mouseout', this.onMouseOut.bindAsEventListener(this));
    if (this.domLink) {
    	this.domLink.observe('click', this.onClick.bindAsEventListener(this));
    }
    if (this.domLink2) {
    	this.domLink2.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)
  {
    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, this.width, this.height, '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)
  {
	var deleted_entity;
	
	if (this.domContainer.id.indexOf('news') != -1) {
		deleted_entity = 'news';
	}
	if (this.domContainer.id.indexOf('photo') != -1) {
		deleted_entity = 'images';
	}
	if (this.domContainer.id.indexOf('video') != -1) {
		deleted_entity = 'videos';
	}
	if (deleted_entity) {
		el = $('entity-menu-item-'+deleted_entity).down('b').down('small').down('span');
		if (el) {
			el.update(parseInt(el.innerHTML)-1);
		}
	}
    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, width, height, map_render)
  {
    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 = width;
	this.height = height;
	this.map_render = map_render;
	this.isRenderedMap = false;
    
    this.domImageHolder = this.domImage.down('span');

    if((this.domIAgree=$('i_agree')) && (this.domIAgree.up('form')))
      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.map_render && !this.isRenderedMap) {
	        	renderUserMap();
	        	this.isRenderedMap = true;
	        }
	        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({
				button_window_mode: 'transparent',
	            upload_url: uploadUrl, 
	            flash_url:  '/js/dui/swfupload/swfupload.swf',
				post_params: {folder: this.folder_name, type:'user'},
	            file_size_limit: "5000",
	            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 ($F(this.domCategorySelect)) {
    	resetCategory('categity_'+$F(this.domCategorySelect), false);
    }
    */
    /*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.categoryChanged();
    
    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()
  {
	 new Ajax.Updater(
				'cat_spl_char', 
				'/alerts/cat_spl_char', 
				{asynchronous:true, evalScripts:true, parameters:'value=' + encodeURIComponent($F(this.domCategorySelect))}
	 );
  },
  
  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;
    }  

    document.getElementById('layer_test').style.height = document.body.parentNode.scrollHeight + 'px';
    document.getElementById('layer_test').style.display="block";
    new Effect.Opacity('layer_test', { from: 0, to: 0.2, duration: 0 });

    domContainerId = 'popup1';
    //domContainerId = 'popup_'+Math.random().toString().substring(2);
    this.domContainer = new Element('div', {id: domContainerId}).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('popup1');
    this.domCloseLink.addClassName('close');
    this.domLoading.addClassName('loading');
    
    
    this.domContent.update(content);
    this.domCloseLink.observe('click', this.close.bind(this));
    $('layer_test').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.observe('Window:loaded', this.center.bindAsEventListener(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});      
    }
  },

  showContent: function(event, content, previousClosed)
  {
	  alert(content);
	  /*
	  this.domContainer.style.display = '';
	    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.Opacity('layer_test', { from: 0.2, to: 0, duration: 0 });
    document.getElementById('layer_test').style.display="none";
    
    //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.down('form input[type=submit]')) {
    	this.domContainer.down('form input[type=submit]').observe('click', this.onSubmitClick.bindAsEventListener(this));
    }

    if (!this.domContainer.up('.popup'))
    {
      return;
    }
	
  },
  
  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');
      if (AList) {
    	AList.resetPage();
    	AList.reload();
      }
    }
    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, {
	  initialize: function($super, container, width, height)
	  {
	    $super(container, width, height);
	  }
});

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

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

var AddNewsDialog = 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){
	if (elem.value=='other') {
		document.getElementById('videos_thumb').style.display= 'block';
	} else {
		document.getElementById('videos_thumb').style.display= 'none';
	}
}

function mapIsLoaded()
{
  window.mapLoaded = true;
}

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 == "button grey"){	
		el.innerHTML = "<b>Unsubscribe</b>";
		el.className = "button grey_unsubscribe";
	}
	else if(el.className == "button grey_unsubscribe"){
		el.innerHTML = "<b>Subscribe</b>";
		el.className = "button grey";							
	}
}

function watchlist_lists_update_alert(el){

	if(el.id == "alert_not_subscribed"){	
		el.innerHTML = "<b>Unsubscribe</b>";
		el.id = "alert_subscribed";
	}
	else if(el.id == "alert_subscribed"){
		el.innerHTML = "<b>Subscribe</b>";
		el.id = "alert_not_subscribed";							
	}
}

function favoritize_alert(el){

	if(el.id == "alert_not_favorited"){	
		el.innerHTML = "<b>Remove from Favorites</b>";
		el.id = "alert_favorited";
	}
	else if(el.id == "alert_favorited"){
		el.innerHTML = "<b>Add to Favorites</b>";
		el.id = "alert_not_favorited";							
	}
}

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) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+1);
	setCookie('alerts_age', val, exdate.toUTCString());
	AList.setParam('age', val);
	AList.resetPage();
	AList.reload();
}

function changeOrder(el, val) {
	AList.setParam('order', val);
	AList.resetPage();
	AList.reload();
}


function changeFilterCategory(el, val) {
	AList.resetPage();
	AList.setParam('category_id', val);
	AList.reload();
	//$('filter_select_category_value').update(el.innerHTML);
	//closeFilterBlocks();
}

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('li').each(function(e) {
		e.removeClassName('current');
    });
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+1);
	setCookie('alerts_sort', val, exdate.toUTCString());
	AList.setParam('sort', val);
	AList.resetPage();
	AList.reload();
	el.parentNode.addClassName('current');
}

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

function closeFilterBlocks() {
	$('manageFilterBlocks').select('.selectItem').each(function(e) {
		e.removeClassName('filter_selector_current');
    });
    $('filter_block_countries').update('');
    $('filter_block_category').hide();
}

function manageFilterBlocks(el) {
	closeFilterBlocks();
	el = el.parentNode;
	$('manageFilterBlocks').select('.selectItem').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_countries', 
			'/filter', 
			{
				asynchronous:true, 
				evalScripts:true, 
				parameters:params
			});
	} else if(el.id == 'filter_select_category') {
		if (!$('categories_filter_table')) {		
			params.filter_type = 'category';
			new Ajax.Updater(
				'filter_block_category', 
				'/filter', 
				{
					asynchronous:true, 
					evalScripts:true, 
					parameters:params
				});			
		}
		$('filter_block_category').show();
	}
}

function resetFilterCategories(alistUpdate){
	$$('#categories_filter_table a[rel]').each(function(item) {
		item.removeClassName('current'); 
		item.style.display="none";
	})
	$$('#categories_filter_table tr td:first-child a[rel]').each(function(item) {item.style.display="block";})
	$('categories_breadcrumbs').update('');
	default_title = "All Categories"
	if (alistUpdate) {
		AList.setParam('category_id', '');
		//$('filter_select_category_value').update(default_title);
	} else {
		$('alert_category_id').setValue('');
		//$('filter_select_category_value').update(default_title);
		$('category_icon').setAttribute('src', '/img/e.gif');
	}
}

function resetCategory(id, alistUpdate) {
	el = $(id);
	$(el.parentNode).nextSiblings().each(function(item1) {
			item1.select("a").each(function(item2) {
			item2.removeClassName('current');
			item2.style.display="none";
		})
	});
	$(el.parentNode).select("a").each(function(item3) {
		item3.removeClassName('current');
	});
	el.className="current";
	current_id 		= el.getAttribute('rev');
	current_title 	= el.getAttribute('title');
	if (alistUpdate) {
		AList.setParam('category_id', current_id);
		//$('filter_select_category_value').update(current_title);
	} else {
		$('alert_category_id').setValue(current_id);				
		new Ajax.Updater(
			'cat_spl_char', 
			'/alerts/cat_spl_char', 
			{asynchronous:true, evalScripts:true, parameters:'value=' + encodeURIComponent(current_id)}
		);
		if (el.firstDescendant() !== null && el.firstDescendant().tagName == "IMG") {
			$('category_icon').setAttribute('src', el.firstDescendant().getAttribute('src'));
		}
		//$('filter_select_category_value').update(current_title);
	}
	$$('#categories_filter_table a[rel='+current_id+']').each(function(item) {
		item.style.display="block";
	});
	$('categories_breadcrumbs').update(getCategoriesFilterBreadCrumbs(alistUpdate));
}

function getCategoriesFilterBreadCrumbs(alistUpdate) {
	var breadcrumbs = [];
	var return_str = '';
	$$('#categories_filter_table tr td').each(function(td_el) {
		td_el.select("a").each(function(item2) {
			if(item2.hasClassName("current")) {
				breadcrumbs.push(item2);
			}
		})
	});
	if (breadcrumbs.length) {
		for (var i=0; i<breadcrumbs.length; i++) {			
			//return_str+="<a href='javascript:void(0)' onClick=\"changeFilterCategory(this, '"+breadcrumbs[i].getAttribute('rev')+"'); return false;\">"+breadcrumbs[i].getAttribute('title')+'</a>';
			return_str+="<a href='javascript:void(0)' onClick=\"resetCategory('"+breadcrumbs[i].id+"', "+alistUpdate+"); return false;\">"+breadcrumbs[i].getAttribute('title')+'</a>';
			if (breadcrumbs[i].firstDescendant() !== null && breadcrumbs[i].firstDescendant().tagName == "IMG") {
				return_str+="<img src='"+breadcrumbs[i].firstDescendant().getAttribute('src')+"'>";
			}
			if ((i+1) != breadcrumbs.length) {
				return_str+="<strong>&raquo;</strong>";	
			}
		}
	}
	return return_str;
}


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

function flashSetCountry(continent){
	$('countries_filter_continent_block').update('<strong>»</strong><a id="countries_filter_continent" href="'+continent.replace(" ","_").toLowerCase()+'" class="current_manager">'+continent+'</a>');
	$('countries_filter_country_block').update('');
}

function fireElement(objID) {
	var target=document.getElementById(objID);
	if(document.dispatchEvent) { // W3C
		var oEvent = document.createEvent( "MouseEvents" );
		oEvent.initMouseEvent("click", true, true,window, 1, 1, 1, 1, 1, false, false, false, false, 0, target);
		target.dispatchEvent( oEvent );
	} else if(document.fireEvent) { // IE
		target.fireEvent("onclick");
	}
}
function contribute_menu(tab) {
	$('contribute_block').select('li').each(function(e) {
		if (document.getElementById(e.id.replace('_tab',''))) {
			document.getElementById(e.id.replace('_tab','')).style.display= 'none';
		}
		e.removeClassName('current');
    });
	if ($('contribute_msg')) $('contribute_msg').update('');
	$(tab+'_tab').addClassName('current');
	if (document.getElementById(tab)) {
		document.getElementById(tab).style.display= 'block';
	}
}
function contribute_success(transport, entity, id) {
	if (response = transport.responseText) {
		var form_elements = $(id).getElements();
		for (var i=0;i<form_elements.length;i++) {
			if ((form_elements[i].type != 'submit') && (form_elements[i].type != 'hidden')) {
				form_elements[i].clear();
			}
		}

		$('contribute_msg').update('Information was posted!');

		if (entity == 'updates') {
			if (!$('alert_impact').visible()) $('alert_impact').show();
		}
		if (entity == 'comments') {
			current = parseInt($('alert_comments_count').innerHTML);
			$('alert_comments_count').update(current+1);
		}
		el = $('entity-menu-item-'+entity).down('b').down('small').down('span');
		if (el) {
			current = parseInt(el.innerHTML);
			if (entity == 'news') {
				if (transport.responseJSON) {
					if ((!transport.responseJSON.matched_with_alert) && ($('news_matched_with_alert'))) {
						$('news_matched_with_alert').show();
					}
					el.update(current+parseInt(transport.responseJSON.qty));
				} else {
					el.update(current+parseInt(response));
				}
			} else {
				el.update(current+1);
			}
		}
		AList.reload();
	} else {
		$('contribute_msg').update('Information wasn\'t posted!');	
	}

}

function show_hide_reply_block(id) {
	el = $('reply_block_'+id);
	if (el) {
		state = el.getStyle('display');
		if (state == 'none') {
			el.setStyle({display: 'block'});
		} else {
			el.setStyle({display: 'none'});
		}
	}
}

function addComment(type, id, parent, area) {
	var params = {
		'attachable_type' :type,
		'attachable_id'   :id,
		'parent_of'   :parent
	};
	params.comment = $F(area);
	new Ajax.Request('/comments/add', {
		method: "POST",
		parameters:params, 
		onSuccess: function(transport) {
		    AList.reload();
  		}
	});
}

function changeCommentCredibitity(comment_id, rate) {
	new Ajax.Request('/comments/comment_vote', {
		method: "POST",
		parameters:{
			'comment_id': comment_id,
			'rate': rate
		}, 
		onSuccess: function(transport) {
		    //AList.reload();
  		}
	});
}

function showEditCommentArea(id) {
	if(!$('comments_textarea_'+id)) {
		var content = $('comments_content_'+id).innerHTML;
		$('comments_content_'+id).update('<textarea id="comments_textarea_'+id+'">'+content+'</textarea>');
		$('comment_edit_handler_'+id).show();
	}
	
}

function editComment(id) {
	content = $('comments_textarea_'+id).getValue();
	new Ajax.Request('/comments/edit', {
		method: "POST",
		parameters:{
			'id': id,
			'text': content
		}, 
		onSuccess: function(transport) {
		    AList.reload();
  		}
	});	
}

function editCommentCancel(id) {
	AList.reload();
}

function removeComment(id) {
	if ( confirm("Are you sure?") ) {
		new Ajax.Request('/comments/delete', {
			method: "POST",
			parameters:{
				'id': id
			}, 
			onSuccess: function(transport) {
			    AList.reload();
	  		}
		});
	}
}

function changeQuickForm(form, self) {
	if (form == 'login') {
		$('quick_register_form').setStyle({display:'none'});
		$('quick_login_form').setStyle({display:'block'});
		if (!self) {
			$('reg_radio_login').checked = 'checked';
			new Effect.ScrollTo('quick_login_form');
			$('login_username').focus();
		}
	} else {
		$('quick_login_form').setStyle({display:'none'});
		$('quick_register_form').setStyle({display:'block'});
		if (!self) {
			$('reg_radio_register').checked = 'checked';
			new Effect.ScrollTo('quick_register_form');
			$('register_username').focus();
		}
	}
}

function QuickHandle(action) {
	if (action == 'login') {
		username = $F('login_username');
		password = $F('login_password');
		params = {
			'action': action,				
			'username': username,
			'password': password
		};
	} else if  (action == 'register') {
		photo_id = $F('user_photo_id');
		email = $F('register_email');
		i_agree = $('i_agree');
		recive_messages = $('recive_messages');
		username = $F('register_username');
		password = $F('register_password');
		re_password = $F('register_re_password');
		if (!email) {
			new PopupDiv("<h3>Error<\/h3>Please specify email", '400px');
			return false;	
		}
		if (!i_agree.checked) {
			new PopupDiv("<h3>Error<\/h3>Please confirm you have read and agree with terms of use and privacy policy.", '400px');
			return false;	
		}
		params = {
			'action': action,				
			'username': username,
			'password': password,
			'password_confirmation': re_password,
			'email': email,
			'photo_id': photo_id
		};
	}
	if (!username || !password) {
		new PopupDiv("<h3>Error<\/h3>Please specify username and password", '400px');
	} else {
		new Ajax.Request('/login/quick', {
			method: "POST",
			parameters:params, 
			onSuccess: function(transport) {				
				if(transport.responseJSON.success) {
					if (($('edit_alert_form') && ($('edit_alert_form')!='null'))) {
						window.location.href="/alerts/create?"+$('edit_alert_form').serialize();
						return false;
					}
					window.location.reload();
				} else {
			    	new PopupDiv("<h3>Error<\/h3>"+transport.responseJSON.data+"", '400px');
			    }
	  		}
		});	
	}
}

function FBLogin(response) {
	if (response.session) {
		new Ajax.Request('/login/fb', {
			method: "POST",
			parameters:{
				'session':Object.toJSON(response.session)
			},
			onSuccess: function(transport) {
				if(transport.responseJSON.success) {
					window.location.reload();
				}
	  		}
		});
	}
}

function textareaMaxChars(containerId, limit, limitContainerId) {
	if ($(containerId).value.length > limit) {
		$(containerId).value = $(containerId).value.substring(0, limit);
	} else {
		$(limitContainerId).update(limit - $(containerId).value.length);
	}
	return false;
}

function setCookie (name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function dateFormatTimezoned(timestamp) {
    var month=new Array(12);
    month[0]="Jan";
    month[1]="Febr";
    month[2]="Mar";
    month[3]="Apr";
    month[4]="May";
    month[5]="Jun";
    month[6]="Jul";
    month[7]="Aug";
    month[8]="Sep";
    month[9]="Oct";
    month[10]="Nov";
    month[11]="Dec";
    var d=new Date();
    var d2 = new Date(timestamp)
    d.setTime(d2.getTime()-(d.getTimezoneOffset()*60*1000));
    var minutes = new String(d.getMinutes());
    if (minutes.length<2) minutes = '0'+minutes;
    return month[d.getMonth()]+'. '+d.getDate()+', '+d.getFullYear()+' '+d.getHours()+':'+minutes;
}

function prefetchNews(alert_id, prefetch_meta) {
	var news_url = $('news_url');
	var news_title = $('news_title');
	var news_description = $('news_description');
	if (alert_id && news_url && news_url.value && news_title && news_description) {
		new Ajax.Request('/news?mode=news_prefetch&alert_id='+alert_id, {
			method: "POST",
			parameters:'url='+escape(news_url.value), 
			onSuccess: function(transport) {				
				if(transport.responseJSON) {
					if (transport.responseJSON.title && transport.responseJSON.title.length>0) {
						news_title.value = transport.responseJSON.title;
					}
					if (transport.responseJSON.description && transport.responseJSON.description.length>0) {
						news_description.value = transport.responseJSON.description;
					}
					if (!transport.responseJSON.matched_with_alert) {
						$('news_matched_with_alert').show();
					}
				}
	  		}
		});	
	}
	
}

function categoriesAutocompleterInit() {
	new Ajax.Autocompleter("category_name", "category_choices",
	           '/filter?filter_type=category',
	           {
					paramName: 'title',
					onSuccess: function(transport) {
						var category_choices = $('category_choices');
						category_choices.style.opacity="1";
					    if(category_choices.style.filter) {
					    	category_choices.style.filter = 'alpha(opacity=100)';
						}
					    category_choices.update(transport.responseText);
					    category_choices.show();
						
						return false;
					},
					afterUpdateElement: function () {
						$('category_name').value = 'Search for a category keyword...';
					}
	        	}
			);
}

var memberPopupAjax;

function memberPopup(el,username) {
	if ( username && (username.length>0) ) {
		x=$(el).cumulativeOffset(); 

		memberPopupAjax = new Ajax.Updater('popup', '/users/member_popup', {
			asynchronous:true, 
			evalScripts:false, 
			parameters: {'username':username },
			onSuccess: function(transport){
				if ((transport.responseText) && (transport.responseText.length>0)) {
					$('popup').setStyle({
						left:x[0]-27+'px',
						top:x[1]-210-40+'px'
					});
					$('popup').show();
				}
	    	}
		});
	}
		
}
function memberPopupHide() {
	$('popup').hide();
	if (memberPopupAjax) {
		memberPopupAjax.abort();
	}
}
